我正在尝试编写用户输入出生月份和日期后出现的星座运势。
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 进行比较。
