【问题标题】:Can't figure out why my else statement is still calling this function with negative input不明白为什么我的 else 语句仍然用负输入调用这个函数
【发布时间】:2021-02-07 10:20:18
【问题描述】:

我正在自学 Python,并决定制作一个基于文本的简短游戏,首先我决定制作一个函数,让用户确认他们实际上确实想用“是或否”选项玩游戏但是,即使给出“否”输入,仍会调用游戏函数。任何帮助将不胜感激。

这是我进入游戏的命令提示符:

while i <= 10000000000000000:
    command = input(":")

    if command == "List commands":
        command_list()
        i += 1
    elif command == "Atlas":
        atlas_confirmation()
        i += 1

这是确认用户想要玩游戏的提示:

def atlas_confirmation():
    print("Alright, but this one's pretty spooky. Are you sure?")
    yn = input(":")

    if yn == "Yes" or "yes" or "I'm sure" or "Im sure" or "im sure" or "i'm sure":
        atlas_game()
    elif yn == "No" or "no":
        print(command_end)

这是游戏的占位符:

def atlas_game():
    print(placeholder)
    print(command_end)

当给定一个正输入时,我得到期望的输出:

Uh oh! Looks like this code has yet to be completed, but it will be available soon!
Is there anything else I can do for you?
:

但是,当我给出一个负输入时,输出仍然和上面一样 ^ 就像我给出一个正输入一样,而不是所需的输出:

Is there anything else I can do for you?
:

我预计我的“if”语句在某个地方是错误的,但我不知道在哪里或为什么。

任何帮助将不胜感激,

谢谢。

【问题讨论】:

  • 警惕yn == "No" or "no" 这被评估为(yn == "No") or "no" 而不是(yn == "No") or (yn == "no") 这可能会导致命令被忽略。您可以使用(yn == "No") or (yn == "no")yn in ["No", "no"] 来获得所需的行为者。在python中,非空字符串被认为是True所以if yn == "Yes" or "yes"...->(if yn == "Yes") or ("yes")...->(if yn == "Yes") or (True)...所以atlas_game总是会被调用
  • 太棒了,非常感谢。我会记住这一点。

标签: python function if-statement input user-input


【解决方案1】:

我认为您需要从 atlas_confirmation() 函数返回 command_end 以检查 while 循环中的中断条件。将您的 atlas_confirmation() 函数更新为:

def atlas_confirmation():
    print("Alright, but this one's pretty spooky. Are you sure?")
    yn = input(":")

    if yn == "Yes" or yn == "yes" or yn == "I'm sure" or yn == "Im sure" or yn == "im sure" or yn == "i'm sure":
        atlas_game()
    elif yn == "No" or yn == "no":
        return command_end

你的 while 循环到这个:

while i <= 10000000000000000:
    command = input(":")

    if command == "List commands":
        command_list()
        i += 1
    elif command == "Atlas":
        atlas_confirmation()
        i += 1

【讨论】:

  • 恐怕这只会导致“atlas_confirmation”函数再次被调用,并且即使像以前一样给出负输入,它仍然会在结束时打印“占位符”值。
  • 现在检查了你的 if 语句,发现你犯了一个错误,你需要在所有 or 语句中使用yn == "something"。 @JoeCox 我编辑了答案,现在检查。
  • 我的朋友,你是一位绅士和一位学者。这行得通,谢谢你的帮助,下次我做任何“或”陈述时我会记住这一点。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多