问题分析:用Python编写一个程序,判断输入的数字是奇数还是偶数,并相应的输出信息,要判断一个数为奇数还是偶数,依据的是它被2除后的余数。因此可以用“%”运算符来计算并判断。
代码如下:
while True: try: num=int(input('输入一个整数:')) #判断输入是否为整数 except ValueError: #不是纯数字需要重新输入 print("输入的不是整数!") continue if num%2==0: print('偶数') else: print('奇数') brea
输出结果
输入一个整数:81 奇数
或者定义一个函数
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.