为什么我的 if 语句不起作用?没有正确读取输入

问题描述

当我做一些 ifelif 语句时,当我去输入输入时,它没有注册我的 input,它显示错误输出。这是我的代码

def startup():
    print("Hello! Thank you for playing my game!")
    time.sleep(1)
    print("If you want to start then type 'start'.")
    time.sleep(1)
    print("If you want to exit the game then type 'exit'.")
    time.sleep(1)
    print("If you want to see the about then type 'about'.")
    time.sleep(0.5)
    while True:
        choice = input("Type an option: ")
        if choice == "start" or "Start":
            print("Ok,starting...")
            time.sleep(1)
            break
        elif choice == "exit" or "Exit":
            exit_question = input("Are you sure? Type Y or n.")
            if exit_question == Y:
                print("Exiting...")
                break
            else:
                print("Ok sorry...")
        elif choice == "about" or "About":
            about = open("about.txt","r")

然后当我运行代码时,这就是我得到的。

Hello! Thank you for playing my game!
If you want to start then type 'start'.
If you want to exit the game then type 'exit'.
If you want to see the about then type 'about'.
Type an option: about   <--------- my input
Ok,starting...

解决方法

您误用了 or 运算符。

>>> x = "about"
>>> x == "start"
False

>>> x == "start" or "Start"
'Start'

>>> bool(_)
True

>>> # Correct.
>>> x == "start" or x == "Start"
False
,

if choice == "start" or "Start": 表示选择等于字符串“start”或“Start”,在python中它总是计算为真,因为它是一个非空字符串。你需要写if choice == "start" or choice == "Start"