Python Exercise Example 76
**Problem:** Write a function: when the input n is even, call a function to compute 1/2+1/4+...+1/n; when the input n is odd, call a function to compute 1/1+1/3+...+1/n
**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, dividing an integer by an integer yields only an integer, so you need to use the floating-point number 1.0
return
s
def
podd
(
n
)
:
s
=
0.0
for
i
in
range
(
1
,
n
1
,
2
)
:
s
+=
1.0
/
i
In Python, dividing an integer by an integer yields only an integer, so you need to use the floating-point number 1.0
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
)
sum
The output of the above example is:
input a number:
6
0.916666666667
Python 100 Examples