为什么 Python 如果"String"在 UserInput:无论我在 UserInput 中输入什么,总是有效?



我正在尝试制作一个简单的python Rock,Paper,Scissors,游戏。这是我的全部代码。

import random
# The AI Respond, will be random.
print('Welcome to Rock, Paper, Scissors Game! n')
UserInput = input("Please enter Rock, Paper, or Scissors, to start the game. n")
BotChoicelist = ["Rock", "Paper", "Scissors", "Rock", "Paper", "Scissors", "Rock", "Paper", "Scissors"]
BotAwnser = random.sample(BotChoicelist, 1)
UserScore = 0
#If1
if "Rock" or "rock" in UserInput:
if "Rock" in BotAwnser:
print("Bot choose Rock, Tie")
if "Paper" in BotAwnser:
print("Bot choose Paper, Bot won.")
print("Your score is:")
print(UserScore - 1)
if "Scissors" in BotAwnser:
print("Bot choose Scissors, You won.")
print("Your score is:")
print(UserScore + 1)

#if2
if "Paper" or "paper" in UserInput:
if "Paper" in BotAwnser:
print("Bot choose Paper, Tie")
if "Scissors" in BotAwnser:
print("Bot choose Scissors, Bot won.")
print("Your score is:")
print(UserScore - 1)
if "Rock" in BotAwnser:
print("Bot choose Rock, You won.")
print("Your score is:")
print(UserScore + 1)

问题是,无论我在UserInput中输入什么,它都会启动If1和If2,我该如何解决?这里更清楚的是输出:

Welcome to Rock, Paper, Scissors Game! 
Please enter Rock, Paper, or Scissors, to start the game. 
AnyThingHere
Bot choose Scissors, You won.
Your score is:
1
Bot choose Scissors, Bot won. 
Your score is:
-1
if UserInput in ["rock","Rock"]:
#do something 
#if2
elif str(UserInput).lower() in ["paper"]:
#do soemthing else
elif (another expression)

请在网上搜索control-flow和逻辑语句

if "Rock" or "rock" in UserInput:

并没有做你认为它会做的事。

它不检查"Rock""rock"是否是UserInput的子串。相反,它检查"Rock"是否为真,或者"rock"是否是UserInput的子串。

"Rock"是一个"truthy"值,这意味着在实践中您的if条件变为:

if True or "rock" in UserInput:

可以简化为

if True:

所以你的if语句根本没有任何作用。

将条件更改为类似if "Rock" in UserInput or "rock" in UserInput:的内容会有所帮助,但为了简化条件,您可能需要查看lower()

相关内容

  • 没有找到相关文章

最新更新