Compile a function. When n is an even number, call the function to calculate 1/2 + 1/4 +... + 1/n. When n is an odd number, call the function 1/1 + 1/3 +... + 1/n ., Even number
First, write a function whose n is an even number:
def peven (n):
s = 0.0
for i in range (2, n + 1,2):
s + = 1.0 / i
print 'value:', s
Write another function with n as an odd number:
def podd (n):
s = 0.0
for i in range (1, n + 1,2):
s + = 1.0 / i
Write an input box:
N = int (input ('input number :'))
Then judge the Parity:
if n % 2 == 0:
peven(n)
else:
podd(n)
The above is the analysis step, and the complete code is attached.
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 'value:', 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 'values:', s
14
15 n = int (input ('Enter a number:'))
16
17 if n% 2 == 0:
18 peven (n)
19 else:
20 podd (n)