尝试让Python以这种形式打印出正确的出生年份

问题描述 投票:0回答:2

我对Python很陌生,在这里问了另一个问题,效果很好,所以谢谢大家,

这个问题,我知道我做错了什么,只是不知道如何解决......

代码:

# import current year to ensure code is up-to-date
from datetime import date
current_yr = date.today().year

# get name as a string
user_name = input('What is your name?'' ''\n')

# get age as an int
user_age = int(input('How old are you?'' ''\n'))

birthday_question = input('Have you had your birthday yet?'' ''\n')
# calculate birth year
birth_year = (current_yr - user_age)
birth_year1 = (current_yr - 1 - user_age)
# print greeting
my_file = open("my_file.txt", "w+")
if {birthday_question} == 'yes':
    my_file.write(f'Hello {user_name}! You were born in {birth_year}.')
else:
    my_file.write(f'Hello {user_name}! You were born in {birth_year1}.')

无论生日问题的答案如何,都会得出相同的出生年份,我相信这是因为通过将变量更改为 current_yr - user_age 它改变了答案,只是不使用 if else 语句...

只是不确定如何更正代码,并且已经尝试了几乎所有我能想到的尝试,

感谢您的帮助

贾斯汀

尝试重新编写代码以使其更简单 尝试了上面的 if else 语句 尝试将 if else 语句作为变量集等

error-correction
2个回答
0
投票

你的错误很简单: 您在

if {birthday_question} == 'yes':
行中添加了不需要的 {}。此行应更改为
if birthday_question == 'yes':


0
投票

删除生日_问题周围的 {},因为在本例中不需要它们

© www.soinside.com 2019 - 2024. All rights reserved.