我正在尝试制作一个确定数字是奇数还是偶数的程序。 该程序是用Python制作的,需要用户输入。
一个接受数字并告诉用户它是奇数还是偶数的程序
def OddorEven():
try:
number = input("Enter a number: ")
int(number)
oddoreven == number % 2
if oddoreven == 0:
print("Your number is an even number")
else:
print("Your numbe is an odd number")
except:
print("You did not enter a number!")
OddorEven()
OddorEven()
发生异常:NameError 未定义名称“ oddoreven” 文件“ C:\ Users \ istif \ OneDrive \ Desktop \ New folder \ Even.py”,第4行,在 奇数==数字%2
答案 0 :(得分:1)
如果将数字转换为int,则应存储在某个变量中。
number = int(数字) 然后做 Oddoreven =数字%2 并使用=分配符号而不是比较==符号 因为如果您不将其存储在另一个变量中,则不会将其转换为int,然后仅将其视为字符串,这就是为什么您遇到typeerror
答案 1 :(得分:0)
代码-
def OddorEven():
try:
number = input("Enter a number: ")
number = int(number) #you have to assign the conversion to the variable again.
oddoreven = number % 2 #remember = and == are not same. == is for comparison
if oddoreven == 0:
print("Your number is an even number")
else:
print("Your number is an odd number")
except:
print("You did not enter a number!")
OddorEven()
OddorEven()
两个错误-
=
和==
不同。 Quick google search would help you better in detail