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

How to determine odd and even numbers using python

silencement
silencementOriginal
2019-06-06 18:00:3828961browse

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

Output result

输入一个整数:81
奇数

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

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.

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!

Statement:
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