Python Exercise Example 76

Python 100例Python 100 Examples

Problem:Write a function: when the input n is even, call the function to calculate 1/2+1/4+...+1/n; when the input n is odd, call the function 1/1+1/3+...+1/n

Program analysis:None.

Program source code:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- def peven(n): i = 0 s = 0.0 for i in range(2,n + 1,2): s += 1.0 / i # In Python, integer divided by integer only yields an integer, so the floating point number 1.0 is needed return s def podd(n): s = 0.0 for i in range(1, n + 1,2): s += 1.0 / i # In Python, integer divided by integer only yields an integer, so the floating point number 1.0 is needed return s def dcall(fp,n): s = fp(n) return s if __name__ == '__main__': n = int(raw_input('input a number:\n')) if n % 2 == 0: sum = dcall(peven,n) else: sum = dcall(podd,n) print sum

The output of the above example is:

input a number:
6
0.916666666667

Python 100例Python 100 Examples

Other extensions