【问题标题】:Even or Odd? Python in JES Program偶数或奇数? JES 程序中的 Python
【发布时间】:2015-10-26 23:05:02
【问题描述】:

这是我的代码,我无法让最后一个 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"

【问题讨论】:

  • num % 2 ==0 or num % 2 == 1 - 为什么会比这更进一步?其中之一肯定是真的!你为什么不直接测试if ans != "odd" and ans != "even":,因为哪个号码并不重要?

标签: python if-statement jes


【解决方案1】:

问题在于,在您上一个 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'

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 2017-02-06
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多