Home > Backend Development > Python Tutorial > How to determine odd and even numbers using python

How to determine odd and even numbers using python

silencement
Release: 2019-06-17 15:10:41
Original
29015 people have browsed it

How to determine odd and even numbers using python

Problem analysis: Use Python to write a program to determine whether the input number is odd or even, and output the information accordingly. To determine whether a number is odd or even, it is based on whether it is an odd number or an even number. The remainder after division by 2. Therefore, you can use the "%" operator to calculate and judge.

The code is as follows:

while True:
    try:
        num=int(input('输入一个整数:')) #判断输入是否为整数
    except ValueError: #不是纯数字需要重新输入
        print("输入的不是整数!")
        continue
    if num%2==0:
        print('偶数')
    else:
        print('奇数')
    brea
Copy after login

Output result

输入一个整数:81
奇数
Copy after login

Or define a function

def judgeOdd(num):
    if num %2 >0:
        return '%i is an odd number.'%num
    else:
        return '%i is an even number.'%num
for i in range(-3,11):
    print(judgeOdd(i))
Copy after login

Output result

-3 is an odd number.
-2 is an even number.
-1 is an odd number.
0 is an even number.
1 is an odd number.
2 is an even number.
3 is an odd number.
4 is an even number.
5 is an odd number.
Copy after login

The above is the detailed content of How to determine odd and even numbers using python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template