我是 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")
答案 0 :(得分:2)
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")
您可以将所有内容无限循环并在用户输入“否”时中断它。
答案 1 :(得分:0)
您的错误是您调用变量 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")