我想做一个小游戏,但它结束了

2024-03-28 20:30:20 发布

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

我是python的绝对初学者,我正在尝试制作一个小游戏,你可以看到你将在哪一年达到某个年龄。第一部分计算你何时会100岁,但当我来到第二部分,我回答是的时候,它会问问题,直到我填写当前年龄,然后它就关闭了

这是我的代码:

import datetime
import time
name = input("What is your name: ") # name input
age = int(input("How old are you: ")) # age input
year1 = str((datetime.datetime.now().year - age)+100) # calculates in what year age will be 100
print(name + " will be 100 years old in the year " + year1)

answer = input("Do you want to know another age: ")
if answer == "yes": 
    age1 = int(input("What age do you want to know: ")) # asks for different age than 100 if answer was yes
    age = int(input("How old are you: ")) # age input
    year2 = str((datetime.datetime.now().year - age)+age1) # calculates in what year input age will be
    print(name + " will be", age1, "years old in the year " + year2)
if answer == "no":
    print("Have a nice day!")
    time.sleep(5) 
    exit()

有人能告诉我为什么会这样以及如何修复它吗


1条回答
网友
1楼 · 发布于 2024-03-28 20:30:20

当答案为no时,可以使用while Truebreak,如下所示:

import datetime
import time
name = input("What is your name: ") # name input
age = int(input("How old are you: ")) # age input
year1 = str((datetime.datetime.now().year - age)+100) # calculates in what year age will be 100
print(name + " will be 100 years old in the year " + year1)

while True:
    answer = input("Do you want to know another age: ")
    if answer == "yes": 
        age1 = int(input("What age do you want to know: ")) # asks for different age than 100 if answer was yes
        age = int(input("How old are you: ")) # age input
        year2 = str((datetime.datetime.now().year - age)+age1) # calculates in what year input age will be
        print(name + " will be", age1, "years old in the year " + year2)
    if answer == "no":
        print("Have a nice day!")
        break

输出:

What is your name: sample
How old are you: 24
sample will be 100 years old in the year 2097
Do you want to know another age: yes
What age do you want to know: 200
How old are you: 24
sample will be 200 years old in the year 2197
Do you want to know another age: yes
What age do you want to know: 300
How old are you: 24
sample will be 300 years old in the year 2297
Do you want to know another age: no
Have a nice day!

相关问题 更多 >