gpt4 book ai didi

python - 变量未定义错误,if语句不执行

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:32 25 4
gpt4 key购买 nike

我正在尝试编写用户输入出生月份和日期后出现的星座运势。

print("To figure out your horoscope, enter the following questions")
month = int(input("what month were you born(january,december,august: "))
days = int(input("what day were you born(2,4,12: "))
if month == 'december':

astro_sign = 'Sagittarius are nice people' if (day < 22) else 'Capricon are adventurous'
print(astro_sign)

但是,每次我执行代码时,它都会给我一个错误:

print(astro_sign)
NameError: name 'astro_sign' is not defined

目前,我只输入了 12 个月和低于 22 天的月份,稍后当一段代码起作用时,我将添加更多月份。谁能帮帮我吗?

最佳答案

那是因为您在条件 if month == '12': 中引入/创建了 astro_sign 变量。因此,每次您输入实际上不是“12”的内容时,您最终都会收到此错误。

简单地说,在条件之前创建您的 astro_sign,这样它至少在您不输入条件的情况下可用:

astro_sign = ''
if month == '12':
# rest of code here

此外,您永远不会使用当前代码实际输入该条件,因为您在这里将月份的输入转换为 int:

month = int(input("month: "))

但是,您的条件是根据单引号明确检查字符串:'12'

所以,而不是:

if month == '12':

你实际上应该这样做:

if month == 12:

删除单引号,这样您就可以将 int 与 int 进行比较。

关于python - 变量未定义错误,if语句不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44999737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com