【问题标题】:Why is Python 2 input() giving me 'NameError: name "____" is not defined'? [closed]为什么 Python 2 input() 给我'NameError:名称“____”未定义'? [关闭]
【发布时间】:2018-09-02 15:44:28
【问题描述】:

我正在尝试编写一个函数来询问姓名、姓氏和出生年份。此外,它稍后会打印出姓名首字母和年龄。

首先,它不要求任何东西。

其次,不管我输入什么都会打印错误:

NameError: name "____"  is not defined.

我正在使用 Python 3。

代码如下:

def userinfo():
    name_ = input("Enter your first name: ")
    last_ = input("Enter your last name: ")
    year_ = input("Enter your year: ")
    initials_ = name_[0] + last_[0]
    age_ = (2018 - year_)
    _info = ("Your initials are ") + (initials_) + (" and you are ") + (str(age_)) + (" years old.")
    if (len(name_) > 0 and len(last_) > 0 and len(year_) > 0 and name_.isalpha() and last_.isalpha()):
        return (_info)
    else:
        return ("Error") 

【问题讨论】:

  • 这看起来不像完整的代码。请提供minimal reproducible example,以便我们诊断您的问题。谢谢。
  • 函数怎么调用?
  • 欢迎来到 Stack Overflow。为了帮助您,请提供一个完整的代码示例来重现您所询问的错误。到目前为止,您给出的代码不可能导致该错误。
  • 它不要求任何它大概是因为你刚刚定义了函数并没有调用它。为此,只需将userinfo() 放在函数定义外部函数。
  • 通过运行此代码,我尝试输入例如“Marina”,我得到了那个错误

标签: python input python-2.x


【解决方案1】:

这是一个经过修正的代码,有一些更正:

1) 将input 替换为raw_input(假设您使用的是python 2.***)。如果您使用的是版本3+,则将raw_input 替换为input

2) 在计算年龄时将year_ 替换为int(year_),因为用户输入的类型为str

def userinfo():
    name_ = raw_input("Enter your first name: ")
    last_ = raw_input("Enter your last name: ")
    year_ = raw_input("Enter your year: ")
    print (name_)
    initials_ = name_[0] + last_[0]
    age_ = (2018 - int(year_))  # Correction here
    _info = ("Your initials are ") + (initials_) + (" and you are ") + (str(age_)) + (" years old.")
    if (len(name_) > 0 and len(last_) > 0 and len(year_) > 0 and name_.isalpha() and last_.isalpha()):
        return (_info)
    else:
        return ("Error") 

userinfo()    

输出

Enter your first name: Donald
Enter your last name: Trump
Enter your year: 1950
Donald
'Your initials are DT and you are 68 years old.'

【讨论】:

    【解决方案2】:

    这似乎是从main() 的声明中抛出的。

    检查主函数是使用双下划线(__)还是三重下划线(___)。

    正确的语法是if __name__ == '__main__':

    希望这会有所帮助!干杯!

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2021-08-23
      • 2016-03-11
      • 2021-12-12
      • 2016-12-20
      • 2020-12-23
      • 2014-03-18
      • 2021-07-27
      相关资源
      最近更新 更多