# 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

Source: Internet
Author: User

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) ```

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.