【发布时间】:2023-03-19 05:15:01
【问题描述】:
我在使用 if/elif 语句时遇到了这个烦人的问题。我是新手,不好意思问了个愚蠢的问题。我试图找到一个修复程序,但没有人为 Python 提供它。
所以,如果两个条件都为真,我希望程序执行if 子句中的代码。据我所知,子句中的代码只有在两个条件都为真时才会执行,对吗?不过,这似乎并没有在我的代码中发生。
result = userNumber + randomNumber
if not result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is even, so you lost :(')
所以,userNumber 和 randomNumber 变量是之前设置的。在这个游戏中,发生的情况是:用户选择偶数或奇数,并输入一个从 0 到 5 的数字。然后,计算机随机选择一个从 0 到 5 的数字,使用random.randint()。
之后,变量result 设置为userNumber + randomNumber 的总和。如果该和的结果是奇数并且用户选择了奇数,则用户获胜,如果用户选择了偶数,则用户输了。如果总和是偶数,则正好相反:如果前一个总和结果的结果是偶数并且用户选择了偶数,则用户获胜,如果用户选择了奇数,则用户输了。
希望你能理解!
所以,我的代码现在的问题是它出于某种原因执行了所有四个 IF 语句,所以最终输出如下所示:
Welcome to the Even or Odd game!
Type letter 'o' if you want odd and the letter 'e' if you want even.
Your choice:o
Now, type in a number from 0 to 5:2
Your number: 2
Computer's number: 5
Adding these two numbers together, we get 7
That number is odd, so you lost :(
That number is even, so you won :)
That number is odd, so you won :)
That number is even, so you lost :(
代码如下:
import random
import time
print ('Welcome to the Even or Odd game!')
print ('Type letter \'o\' if you want odd and the letter \'e\' if you want even.')
userChoice = input('Your choice: ').lower()
time.sleep(1)
userNumber = int(input('Now, type in a number from 0 to 5: '))
randomNumber = random.randint(0,5)
time.sleep(2)
print ('Your number: ' + str(int(userNumber)))
time.sleep(2)
print ('Computer\'s number: ' + str(int(randomNumber)))
time.sleep(2)
result = userNumber + randomNumber
print (str(result))
print ('Adding these two numbers together, we get ' + str(result))
if not result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
print ('That number is even, so you lost :(')
有什么想法吗?抱歉发帖太长,如有重复请见谅!我只是没有在互联网上找到任何答案:/ 非常感谢!
编辑:我也尝试使用 elif 语句而不是所有 if,但也没有用。
【问题讨论】:
-
像
userChoice == 'e' or 'even'这样的条件检查并不像你想象的那样。
标签: python python-3.x