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):
for j in range(len(lis)-1-i):
if lis[j]>lis[j+1]:
lis[j],lis[j+1] = lis[j+1],lis[j]
return lis
if __name__ == '__main__':
sortport()
print(lis)
2、计算x的n次方
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
调用方法:
3、计算a*a + b*b + c*c + …
def calc(*numbers):
sum=0
for n in numbers:
sum=sum+n*n
return sum
print(calc(2,4,5))
4、计算阶乘 n!
#方法一
def fac():
num = int(input("请输入一个数字:"))
factorial = 1
#查看数字是负数,0或者正数
if num<0:
print("抱歉,负数没有阶乘")
elif num == 0:
print("0的阶乘为1")
else:
for i in range(1,num+1):
factorial = factorial*i
print("%d的阶乘为%d"%(num,factorial))
if __name__ == '__main__':
fac()
#方法二
def fac():
num = int(input("请输入一个数字:"))
#查看数字是负数,0或者正数
if num<0:
print("抱歉,负数没有阶乘")
elif num == 0:
print("0的阶乘为1")
else:
print("%d的阶乘为%d"%(num,factorial(num)))
def factorial(n):
result = n
for i in range(1,n):
result=result*i
return result
if __name__ == '__main__':
fac()
#方法三
def fac():
num = int(input("请输入一个数字:"))
#查看数字是负数,0或者正数
if num<0:
print("抱歉,负数没有阶乘")
elif num == 0:
print("0的阶乘为1")
else:
print("%d的阶乘为%d"%(num,fact(num)))
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
if __name__ == '__main__':
fac()
5、列出当前目录下的所有文件和目录名
import os
for d in os.listdir('.'):
print(d)
另外列表推导式代码:
[d for d in os.listdir('.')]
6、把一个list中所有的字符串变成小写:
L = ['Hello','World','IBM','Apple']
for s in L:
s=()
print(s) #将list中每个字符串都变成小写,返回每个字符串
另外列表推导式代码:
L = ['Hello','World','IBM','Apple']
print([() for s in L])#整个