如何使此代码识别我的输入?

2024-04-19 19:35:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我试图询问用户是否想再次使用我的年龄计算器工具。代码:

while True:
    import datetime
    birth_year = int(input("What year were you born? "))
    current_year = datetime.datetime.now().year
    age = current_year - birth_year
    print(f"You are {age} years old now.")
    input()
    choice = input("Do you want to go again? (yes or no) ")
if "choice" == yes:
    print("enjoy")
elif "choice" == no:
    print ("Ok, quitting now")
    quit()
else:
    print("i'll assume that means yes")

Tags: no用户youinputagedatetimecurrentyear
2条回答

您的错误是调用变量choice,并在其周围加上引号,使其成为字符串"choice"。相反,您应该检查变量choice是否包含字符串“yes”或“no”。
为此,我们可以使用两个运算符,==is运算符。
以下是一个例子:

import datetime
birth_year = int(input("What year were you born? "))
current_year = datetime.datetime.now().year
age = current_year - birth_year
print(f"You are {age} years old now.")
input()
choice = input("Do you want to go again? (yes or no) ")
if choice == 'yes': # Example using the `==` operator.
    print("enjoy")
elif choice is 'no': # Example using the `is` operator.
    print ("Ok, quitting now")
    exit() # This should be `exit` not `quit`.
else:
    print("i'll assume that means yes")
import datetime
while True:
    birth_year = int(input("What year were you born? "))
    current_year = datetime.datetime.now().year
    age = current_year - birth_year
    print(f"You are {age} years old now.")
    choice = input("Do you want to go again? (yes or no) ")
    if choice == 'yes':
        print("enjoy")
    elif choice == 'no':
        print ("Ok, quitting now")
        break
    else:
        print("i'll assume that means yes")

只要用户写“否”,您就可以将所有内容都带到无限循环中并将其中断

相关问题 更多 >