【问题标题】:Python not taking in user input correctly [duplicate]Python没有正确接受用户输入[重复]
【发布时间】:2021-02-02 18:38:58
【问题描述】:

所以我正在创建一个小型刽子手游戏来练习我的 Python,在我编写代码的 "Y""Yes" 条件部分之前,我决定测试响应以确保它正确接收用户输入.不幸的是,当我输入 "N""No" 时,代码不会跳过我的代码的 "Y""Yes" 部分并返回

“欢迎来到刽子手游戏! 请输入 Y 或 Yes 播放或输入 N 或 No 退出 no 耶!我很高兴你决定玩!嗯,让我猜一个词........好的,完成! 请输入字母或猜词!”

....任何想法为什么它不跳过代码的"Yes" 部分?

import random

list_of_words = ["banana", "monster", "development", "anarchy", "congruence", "display", "algorithm"]

word_chosen = random.choice(list_of_words)

print("Welcome to a game of Hangman! ")
user_response = str(input("Please type in Y or Yes to play or N or No to quit ")).lower()

if user_response == 'y' or 'yes':
    print("Yay! I'm glad you decided to play! Hmm let me guess a word.................ok DONE!")
    letter_guess = str(input("Please type in a letter or guess the word! ")).lower()
    
elif user_response == 'n' or 'no':
    print("Awww well come back next time if you'd like to play HANGMAN!!!! DUN DUN DUNNNN ")

【问题讨论】:

    标签: python-3.x if-statement input


    【解决方案1】:

    您的 if 条件需要一些修改:

    使用

    if user_response == 'y' or user_response == 'yes':
    

    而不是

    if user_response == 'y' or 'yes':
    

    并使用

    elif user_response == 'n' or user_response == 'no':
    

    而不是

    elif user_response == 'n' or 'no':
    

    问题在于非空字符串的布尔值等于True

    print(bool('yes'))
    # True
    

    【讨论】:

    • 是的!这行得通!感谢您的回复!
    • @jvjvalerio 不客气。我很高兴能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多