【问题标题】:Why writing a correct input uppercase throws an error? [duplicate]为什么写一个正确的输入大写会引发错误? [复制]
【发布时间】:2020-12-14 15:03:33
【问题描述】:

如果用户输入了正确的大写单词,我会收到“您犯了错误”的响应。为什么user_choice.lower() 不能像我预期的那样工作?我哪里做错了?

import random

rock_paper_scissors = ("rock", "paper","scissors")
cpu_choice = random.choice(rock_paper_scissors)
user_choice = input("Rock, paper or scissors ? Enter your choice: ")


if user_choice.lower() != "rock" or "paper" or "scissors":
    print("You made a mistake. Please try again")
    user_choice = input("Rock, paper or scissors ? Enter your choice: ")

while cpu_choice == user_choice.lower():
    print ("--------------------------------------------------------")
    print(f"CPU: {cpu_choice.upper()} vs YOU: {user_choice.upper()}.  It's a tie. Try again!")
    print ("--------------------------------------------------------")
    user_choice = input("Rock, paper or scissors ? Enter your choice: ")

【问题讨论】:

  • if user_choice.lower() != "rock" or "paper" or "scissors" 不是检查多个值的正确方法。看到这个问题stackoverflow.com/q/15112125/494134
  • 查看@toRex 的回答

标签: python lowercase


【解决方案1】:

你的意思是:

if user_choice.lower() not in rock_paper_scissors:
    print("You made a mistake. Please try again")

【讨论】:

  • 也许更好:if user_choice.lower() not in rock_paper_scissors:,所以我们不必再次编写这些值。只有三个值,性能不是问题。
【解决方案2】:

您设置的条件if 不正确。试试吧

if user_choice.lower() != "rock" or user_choice.lower() != "paper" or user_choice.lower() != "scissors":

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多