编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数 1/1+1/3+...+1/n。
首先写一个n为偶数的函数:
def peven(n): s = 0.0 for i in range(2,n + 1,2): s += 1.0 / i print '值:',s
再写一个n为奇数的函数:
def podd(n): s = 0.0 for i in range(1, n + 1,2): s += 1.0 / i print '值:', s
写一个输入框:
n=int(input('输入一个数:'))
再判断一下奇偶:
if n % 2 == 0: peven(n) else: podd(n)
以上是分析的步骤,最后附上完整的代码
1 # coding:utf-8 2 def peven(n): 3 s = 0.0 4 for i in range(2,n + 1,2): 5 s += 1.0 / i 6 print '值:',s 7 8 9 def podd(n): 10 s = 0.0 11 for i in range(1, n + 1,2): 12 s += 1.0 / i 13 print '值:', s 14 15 n=int(input('输入一个数:')) 16 17 if n % 2 == 0: 18 peven(n) 19 else: 20 podd(n)