手机版的python如何运行常用数列结构_入门 | 32个常用 Python 实现
if__name__ == '__main__':
sortport
print(lis)
2、计算x的n次方
defpower(x, n):
s = 1
whilen > 0:
n = n - 1
s = s * x
returns
调用方法:
print(power( 2, 4))
3、计算a*a +b*b + c*c + …
defcalc(*numbers):
sum= 0
forn innumbers:
sum=sum+n*n
returnsum
print(calc( 2, 4, 5))
4、计算阶乘 n!
#方法一
deffac:
num = int(input( "请输入一个数字:"))
factorial = 1
#查看数字是负数,0或者正数
ifnum< 0:
print( "抱歉,负数没有阶乘")
elifnum == 0:
print( "0的阶乘为1")
else:
fori inrange( 1,num+ 1):
factorial = factorial*i
print( "%d的阶乘为%d"%(num,factorial))
if__name__ == '__main__':
fac
#方法二
deffac:
num = int(input( "请输入一个数字:"))
#查看数字是负数,0或者正数
ifnum< 0:
print( "抱歉,负数没有阶乘")
elifnum == 0:
print( "0的阶乘为1")
else:
print( "%d的阶乘为%d"%(num,factorial(num)))
deffactorial(n):
result = n
fori inrange( 1,n):
result=result*i
returnresult
if__name__ == '__main__':
fac
#方法三
deffac:
num = int(input( "请输入一个数字:"))
#查看数字是负数,0或者正数
ifnum< 0:
print( "抱歉,负数没有阶乘")
elifnum == 0:
print( "0的阶乘为1")
else:
print( "%d的阶乘为%d"%(num,fact(num)))
deffact(n):
ifn == 1:
return1
returnn * fact(n - 1)
if__name__ == '__main__':
fac
5、列出当前目录下的所有文件和目录名
importos
ford inos.listdir( '.'):
print(d)
另外列表推导式代码:
[d ford inos.listdir( '.')]
6、把一个list中所有的字符串变成小写:
L = [ 'Hello', 'World', 'IBM', 'Apple']
fors inL:
s=s.lower
print(s) #将list中每个字符串都变成小写,返回每个字符串
另外列表推导式代码:
L = [ 'Hello', 'World', 'IBM', 'Apple']
print([s.lower fors inL]) #整个list所有字符串都变成小写,返回一个list
7、输出某个路径下的所有文件和文件夹的路径
defprint_dir:
filepath = input( "请输入一个路径:")
iffilepath == "":
print( "请输入正确的路径")
else:
fori inos.listdir(filepath): #获取目录中的文件及子目录列表
print(os.path.join(filepath,i)) #把路径组合起来
print(print_dir)
8、输出某个路径及其子目录下的所有文件路径
defshow_dir(filepath):
fori inos.listdir(filepath):
path = (os.path.join(filepath, i))
print(path)
ifos.path.isdir(path): #isdir判断是否是目录
show_dir(path) #如果是目录,使用递归方法
filepath = "C:Program FilesInternet Explorer"
show_dir(filepath)
9、输出某个路径及其子目录下所有以.html为后缀的文件
defprint_dir(filepath):
fori inos.listdir(filepath):
path = os.path.join(filepath, i)
ifos.path.isdir(path):
print_dir(path)
ifpath.endswith( ".html"):
print(path)
filepath = "E:PycharmProjects"
print_dir(filepath)
10、把原字典的键值对颠倒并生产新的字典
dict1 = { "A": "a", "B": "b", "C": "c"}
dict2 = {y:x forx,y indict1.items}
print(dict2)
#输出结果为{'a': 'A', 'b': 'B', 'c': 'C'}
11、打印九九乘法表
fori inrange( 1, 10):
forj inrange( 1,i+ 1):
print( '%d x %d = %d t'%(j,i,i*j),end= '') #通过指定end参数的值,可以取消在末尾输出回车符,实现不换行。
12、替换列表中所有的3为3a
num = [ "harden", "lampard", 3, 34, 45, 56, 76, 87, 78, 45, 3, 3, 3, 87686, 98, 76]
print(num.count( 3))
print(num.index( 3))
fori inrange(num.count( 3)): #获取3出现的次数
ele_index = num.index( 3) #获取首次3出现的坐标
num[ele_index]= "3a"#修改3为3a
print(num)
13、打印每个名字
L = [ "James", "Meng", "Xin"]
fori inrange(len(L)):
print( "Hello,%s"%L[i])
14、合并去重
list1 = [ 2, 3, 8, 4, 9, 5, 6]
list2 = [ 5, 6, 10, 17, 11, 2]
list3 = list1 + list2
print(list3) #不去重只进行两个列表的组合
print(set(list3)) #去重,类型为set需要转换成list
print(list(set(list3)))
15、随机生成验证码的两种方式(数字字母)
importrandom
list1=[]
fori inrange( 65, 91):
list1.append(chr(i)) #通过for循环遍历asii追加到空列表中
forj inrange ( 97, 123):
list1.append(chr(j))
fork inrange( 48, 58):
list1.append(chr(k))
ma = random.sample(list1, 6)
print(ma) #获取到的为列表
ma = ''.join(ma) #将列表转化为字符串
print(ma) importrandom,string
str1 = "0123456789"
str2 = string.ascii_letters # string.ascii_letters 包含所有字母(大写或小写)的字符串
str3 = str1+str2
ma1 = random.sample(str3, 6) #多个字符中选取特定数量的字符
ma1 = ''.join(ma1) #使用join拼接转换为字符串
print(ma1) #通过引入string模块和random模块使用现有的方法
16、随机数字小游戏
#随机数字小游戏
importrandom
i = 1
a = random.randint( 0, 100)
b = int( input( '请输入0-100中的一个数字n然后查看是否与电脑一样:'))
whilea != b:
ifa > b:
print( '你第%d输入的数字小于电脑随机数字'%i)
b = int(input( '请再次输入数字:'))
else:
print( '你第%d输入的数字大于电脑随机数字'%i)
b = int(input( '请再次输入数字:'))
i+= 1
else:
print( '恭喜你,你第%d次输入的数字与电脑的随机数字%d一样'%(i,b))
17、计算平方根
num = float(input( '请输入一个数字:'))
num_sqrt = num ** 0.5
print( '%0.2f 的平方根为%0.2f'%(num,num_sqrt))
18、判断字符串是否只由数字组成
#方法一
defis_number(s):
try:
float(s)
returnTrue
exceptValueError:
pass
try:
importunicodedata
unicodedata.numeric(s)
returnTrue
except(TypeError,ValueError):
pass
returnFalse
t= "a12d3"
print(is_number(t))
#方法二
t = "q123"
print(t.isdigit) #检测字符串是否只由数字组成
#方法三
t = "123"
print(t.isnumeric) #检测字符串是否只由数字组成,这种方法是只针对unicode对象
19、判断奇偶数
#方法一
num = int(input( '请输入一个数字:'))
if(num % 2) == 0:
print( "{0}是偶数".format(num))
else:
print( "{0}是奇数".format(num))
#方法二
whileTrue:
try:
num = int(input( '请输入一个整数:')) #判断输入是否为整数,不是纯数字需要重新输入
exceptValueError:
print( "输入的不是整数!")
continue
if(num % 2) == 0:
print( "{0}是偶数".format(num))
else:
print( "{0}是奇数".format(num))
break
20、判断闰年
#方法一
year = int(input( "请输入一个年份:"))
if(year % 4) == 0:
if(year % 100) == 0:
if(year % 400) == 0:
print( "{0}是闰年".format(year)) #整百年能被400整除的是闰年
else:
print( "{0}不是闰年".format(year))
else:
print( "{0}是闰年".format(year)) #非整百年能被4整除的为闰年
else:
print( "{0}不是闰年".format(year))
#方法二
year = int(input( "请输入一个年份:"))
if(year % 4) == 0and(year % 100)!= 0or(year % 400) == 0:
print( "{0}是闰年".format(year))
else:
print( "{0}不是闰年".format(year))
#方法三
importcalendar
year = int(input( "请输入年份:"))
check_year=calendar.isleap(year)
ifcheck_year == True:
print( "%d是闰年"%year)
else:
print( "%d是平年"%year)
21、获取最大值
N = int(input( '输入需要对比大小的数字的个数:'))
print( "请输入需要对比的数字:")
num = []
fori inrange( 1,N+ 1):
temp = int(input( '请输入第%d个数字:'%i))
num.append(temp)
print( '您输入的数字为:',num)
print( '最大值为:',max(num))
N = int(input( '输入需要对比大小的数字的个数:n'))
num = [int(input( '请输入第%d个数字:n'%i)) fori inrange( 1,N+ 1)]
print( '您输入的数字为:',num)
print( '最大值为:',max(num))
22、斐波那契数列
斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13;特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。
# 判断输入的值是否合法
ifnterms <= 0:
print( "请输入一个正整数。")
elifnterms == 1:
print( "斐波那契数列:")
print(n1)
else:
print( "斐波那契数列:")
print(n1, ",", n2, end= " , ")
whilecount < nterms:
nth = n1 + n2
print(n1+n2, end= " , ")
# 更新值
n1 = n2
n2 = nth
count += 1
23、十进制转二进制、八进制、十六进制
# 获取输入十进制数
dec = int(input( "输入数字:"))
print( "十进制数为:", dec)
print( "转换为二进制为:", bin(dec))
print( "转换为八进制为:", oct(dec))
print( "转换为十六进制为:", hex(dec))
24、最大公约数
defhcf(x, y):
"""该函数返回两个数的最大公约数"""
# 获取最小值
ifx > y:
smaller = y
else:
smaller = x
fori inrange( 1, smaller + 1):
if((x % i == 0) and(y % i == 0)):
hcf = i
returnhcf
# 用户输入两个数字
num1 = int(input( "输入第一个数字: "))
num2 = int(input( "输入第二个数字: "))
print(num1, "和", num2, "的最大公约数为", hcf(num1, num2))
25、最小公倍数
# 定义函数
deflcm(x, y):
# 获取最大的数
ifx > y:
greater = x
else:
greater = y
while( True):
if((greater % x == 0) and(greater % y == 0)):
lcm = greater
break
greater += 1
returnlcm
# 获取用户输入
num1 = int(input( "输入第一个数字: "))
num2 = int(input( "输入第二个数字: "))
print( num1, "和", num2, "的最小公倍数为", lcm(num1, num2))
26、简单计算器
# 定义函数
defadd(x, y):
"""相加"""
returnx + y
defsubtract(x, y):
"""相减"""
returnx - y
defmultiply(x, y):
"""相乘"""
returnx * y
defdivide(x, y):
"""相除"""
returnx / y
# 用户输入
print( "选择运算:")
print( "1、相加")
print( "2、相减")
print( "3、相乘")
print( "4、相除")
choice = input( "输入你的选择(1/2/3/4):")
num1 = int(input( "输入第一个数字: "))
num2 = int(input( "输入第二个数字: "))
ifchoice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elifchoice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elifchoice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elifchoice == '4':
ifnum2 != 0:
print(num1, "/", num2, "=", divide(num1, num2))
else:
print( "分母不能为0")
else:
print( "非法输入")
27、生成日历
# 引入日历模块
importcalendar
# 输入指定年月
yy = int(input( "输入年份: "))
mm = int(input( "输入月份: "))
# 显示日历
print(calendar.month(yy, mm))
28、文件IO
# 写文件
withopen( "test.txt", "wt") asout_file:
out_file.write( "该文本会写入到文件中n看到我了吧!")
# Read a file
withopen( "test.txt", "rt") asin_file:
text = in_file.read
print(text)
29、字符串判断
# 测试实例一
print( "测试实例一")
str = "runoob.com"
print(str.isalnum) # 判断所有字符都是数字或者字母
print(str.isalpha) # 判断所有字符都是字母
print(str.isdigit) # 判断所有字符都是数字
print(str.islower) # 判断所有字符都是小写
print(str.isupper) # 判断所有字符都是大写
print(str.istitle) # 判断所有单词都是首字母大写,像标题
print(str.isspace) # 判断所有字符都是空白字符、t、n、r
print( "------------------------")
# 测试实例二
print( "测试实例二")
str = "Bake corN"
print(str.isalnum)
print(str.isalpha)
print(str.isdigit)
print(str.islower)
print(str.isupper)
print(str.istitle)
print(str.isspace)
30、字符串大小写转换
str = "https://www.cnblogs.com/ailiailan/"
print(str.upper) # 把所有字符中的小写字母转换成大写字母
print(str.lower) # 把所有字符中的大写字母转换成小写字母
print(str.capitalize) # 把第一个字母转化为大写字母,其余小写
print(str.title) # 把每个单词的第一个字母转化为大写,其余小写
31、计算每个月天数
importcalendar
monthRange = calendar.monthrange( 2016, 9)
print(monthRange)
32、获取昨天的日期
# 引入 datetime 模块
importdatetime
defgetYesterday:
today=datetime.date.today
oneday=datetime.timedelta(days= 1)
yesterday=today-oneday
returnyesterday
# 输出
print(getYesterday)
手机版的python如何运行常用数列结构_入门 | 32个常用 Python 实现相关推荐
- python程序运行按什么键_太惨!学Python方法用错,直接从入门到放弃!
原标题:太惨!学Python方法用错,直接从入门到放弃! 从你开始学习编程的那一刻起,就注定了以后所要走的路-从编程学习者开始,依次经历实习生.程序员.软件工程师.架构师.CTO等职位的磨砺:当你站在 ...
- python 正数变成负数_入门 | 32个常用 Python 实现
1.冒泡排序 lis = [56,12,1,8,354,10,100,34,56,7,23,456,234,-58]def sortport():for i in range(len(lis)-1): ...
- python手机版打了代码运行不了-如何用iPad运行Python代码?
代码在我的Macbook电脑上跑,没有问题.还拿到学生的Windows 7上跑,也没有问题.这才上传到了Github. 在发布的教程文章里,我也已经把安装软件包的说明写得非常详细. 还针对 Anaco ...
- python手机版打了代码运行不了-三款可以在安卓手机上运行Python代码的软件
导语 READ 我相信大家平时大多数时间肯定都是在电脑上面敲Python代码,有时候出门外或者不方便使用电脑的时候,你是否曾想用手机就能编写和运行Python代码呢?本文将会介绍3款不同的安卓软件帮忙 ...
- 手机版python3h如何自制游戏_Python 飞机大战|10 分钟学会用 python 写游戏
Python 飞机大战|10 分钟学会用 python 写游戏 2018 年 python 语言大火, 这把火看趋势已然延续到了 2019 年! 除了在科学计算领域 python 有用武之地之外, 在 ...
- python 倒计时运行程序怎么关闭_如何让电脑自动倒计时关机?我Python拭魅战告诉你...
在日常使用电脑的过程中,很多小伙伴都有让电脑按时自动关机的需求.通常而言,年夜家一般城市有几种选择. 假如哪一天,你女神问你,有没有什么按时关机的好体例,你怎么告诉她? 一.熟悉计算机操作的话,可以使 ...
- python 实现网站_python 实现网站_用web.py实现python网站版hello world网页
github源码安装 浏览器打开https://github.com/webpy/webpy,下载源码zip格式,解压出来.cmd打开,cd到解压目录,输入 python setup.py insta ...
- python里面两个大于号_【课堂笔记】Python常用的数值类型有哪些?
学习了视频课程<财务Python基础>,小编特为大家归纳了Python常用的数值类型和运算符,大家一起来查缺补漏吧~~ 数值类型 整型(int):整型对应我们现实世界的整数,比如1,2,1 ...
- python 程序运行计时 动态_python中time库clock 使用Python,实现程序运行计时的数码管表示...
python编程中time模块下的clock()函数怎么用?pr想起现在的孩子在玩荡秋千回想小编们的第一次.高高兴兴的荡秋千.多久都不累 python编程中time模块下的clock()函数怎么用?在 ...
最新文章
- 【NOI2016】优秀的拆分(后缀数组)
- PowerDesigner使用教程 —— 概念数据模型详解
- 对js数组去重的研究
- zbb20180710 maven Failed to read artifact descriptor--maven
- 管理学定律--彼得原理
- 预备作业03 20162320刘先润
- 在Windows下编译ffmpeg完全手册
- STM32工作笔记0011---认识跳线帽
- 阿里云大学python教程下载_阿里大学开放 11 门免费 Python 视频课程
- SAS Planet软件使用教程及下载Googlemap地图
- asp毕业设计——基于asp+access的WEB网上留言板设计与实现(毕业论文+程序源码)——网上留言板
- 电商系统如何实现订单超时自动取消?
- matlab如何编newton-raphson,Matlab中的Newton-Raphson方法
- PGM学习之四 Factor,Reasoning
- 2022年最简单旋转PDF页面的方法推荐
- 【庄碰辉】万般滋味,皆是生活常态
- GBase 8c产品简介
- MAC 常见的终端指令
- 数据分析之Numpy创建二维空数组
- 贾立平是中科学院计算机所博士,在思考中砥砺前行——记我校计算机与软件工程学院青年教师王晓明博士...