美文网首页从零开始学Python
Python习题册021:判断奇偶数

Python习题册021:判断奇偶数

作者: iLester | 来源:发表于2019-01-19 14:16 被阅读0次

任务021描述

用Python编写一个程序,判断输入的数字是奇数还是偶数,并相应的输出信息。

分析及示例

要判断一个数为奇数还是偶数,依据的是它被2除后的余数。因此可以用“%”运算符来计算并判断。

示例代码:

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

运行结果:

-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.
6 is an even number.
7 is an odd number.
8 is an even number.
9 is an odd number.
10 is an even number.

相关文章

网友评论

    本文标题:Python习题册021:判断奇偶数

    本文链接:https://www.haomeiwen.com/subject/fgtzdqtx.html