【问题标题】:Variable not defined error, and if statement doesn't execute变量未定义错误,并且 if 语句不执行
【发布时间】:2017-07-10 20:57:47
【问题描述】:

我正在尝试对用户输入出生月份和日期后的星座进行编码。

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:
  • 只有在月份为 12 时才定义 astro_sign。

标签: python python-3.x


【解决方案1】:

那是因为您在条件 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 进行比较。

【讨论】:

    【解决方案2】:
    print("Please enter your birthday")
    
    month = int(input("month: "))
    
    day = int(input("day: "))
    
    if month == '12':
    
          print('Sagittarius are nice people')
    
    if day < 22:
    
          print('Capricon are adventurous')
    

    看看这是否真的适合你(如果我错了,请告诉我)

    【讨论】:

    • month 被声明为整数,而不是字符串。这与 OP 的问题中看到的逻辑错误相同。
    猜你喜欢
    • 2017-03-21
    • 2020-08-31
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多