def func(n): if n % 2 == 0: start, step = 2, 2 # 如果n是偶数,设置循环的起始值和步长为2 else: start, step = 1, 2 # 如果n是奇数,设置循环的起始值为1,步长为2 sum = 0 for i in range(start, n+1, step): sum += 1 / i return sum # 主函数输入一个自然数n,调用之前已定义函数输出表达式结果且保留2位小数 n = int(input("请输入一个自然数n:")) r = func(n) print("表达式的值为:{:.2f}".format(r))
def func(n): sum = 0 for i in range(1, n+1): if i%2 ==0: sum -=1/(i*(i+1)) else: sum += 1 /(i*(i+1)) return sum n=int(input("请输入正整数n:")) print("表达式的值为:{:.2f}".format(func(n)))
零星的代码
美元转换
1 2 3 4 5 6 7 8 9 10
while True: money = input("请输入美元或者人民币(提示:美元用$,人民币用R,r或者¥)") if money [-1]in['$']: D = 6 * eval(money[0:-1]) print("美元转换成人民币: {:.2f}R".format(D)) elif money [-1] in ['R', 'r','¥']: R=eval(money[0:-1])/6 print("人民币转换成美元: {:.2f}$".format(R)) else: print("格式有误重新输入!!!")
def dealVoa(orgtxts,Eng,Chn): fi = open(orgtxts,'r',encoding='utf-8') foe = open(Eng,'w') foc = open(Chn,'w') elist = ',.' clist = ',。' for line in fi: if len(line) > 1: if ',' in line or '。' in line or line.find(' ') == -1: foc.write(line) elif ',' in line or '.' in line or line.find(' '): foe.write(line) fi.close() foe.close() foc.close() orgtxts = '测试' Eng = orgtxts + '_e' + '.txt' Chn = orgtxts + '_c' + '.txt' orgtxts = '测试' + '.txt' dealVoa(orgtxts,Eng,Chn)#只适合,。和,.分离不在同一行的中英分离
import random s = [] for i inrange(20): s.append(random.randint(0,100)) a = s[0:10] a.sort() b = s[10:20] b.sort() b.reverse()#也可以在sort中加reverse=True print(s) print(a) print(b) s = a + b print(s)
输入列表:
1 2 3 4 5 6 7 8 9 10 11 12 13
n = input("请以列表格式输入一个列表:\n") s = list(n[1:-1].split(",")) #将输入的字符串转化为字符串列表 s = list(map(int,s)) #将字符串列表转换为数字列表,这两步必须有 a = s[0:10] a.sort() b = s[10:20] b.sort() b.reverse() print(s) print(a) print(b) s = a + b print(s)