这是我的代码,我有麻烦让最后的IF语句正常工作,我希望它只在答案不是偶数或奇数时打印,但它几乎每次都打印。我该怎么修理它?
def evenOdd(x):
for x in range (1, 6):
num= random.randrange(1,101)
ans=raw_input("Is" + str(num) + "Odd or Even?")
if (num % 2 == 0 and ans=="even") or (num % 2 == 1 and ans == "odd"):
print "correct"
if (num % 2 == 0 and ans=="odd") or (num % 2==1 and ans == "even"):
print "incorrect"
if (num % 2 ==0 or num % 2 == 1 and ans != "odd" or ans != "even"):
print "Please answer with Even or Odd"
问题是,在您的最后一个if
中,您单独检查每个等式,而不是作为组。
您需要将它们分组为逻辑分组。另外,我不知道为什么这个函数的输入是你永远不会用到的。
import random
for x in range(1, 6):
num = random.randrange(1, 101)
ans = input("Is" + str(num) + "Odd or Even?")
if (num % 2 == 0 and ans == "even") or (num % 2 == 1 and ans == "odd"):
print("correct")
if (num % 2 == 0 and ans == "odd") or (num % 2 == 1 and ans == "even"):
print("incorrect")
if (ans != "odd" or ans != "even"):
print("Please answer with Even or Odd")
最后一行的变化是因为您实际上不需要检查数字是奇数还是偶数,只要用户响应的不是'odd'
或'even'
。