修复Python错误NameError: Input Name Is Not Defined in Python

在Python 2.7和2.x版本中,raw_input()函数和input()是两个内置函数,用于接受用户的输入。但在Python 3.0的后期版本中,raw_input()被重命名为input(),现在仍在使用。

在Python中修复 NameError: input name is not defined 

在旧版本的Python中,input函数用于计算Python表达式,但如果您想读取字符串,则使用raw_input函数。但是现在,raw_input函数被重命名为input,所以它在Python的3.x版本中无法工作。

让我们通过一个例子来理解它。

我们使用Python 2.7版本来编写本主题。如果你在Python 3.x版本上使用它,这段代码将被执行而没有错误。

#Python 2.7 version
name = input("Hi! What is your good name? ")
print("Nice to meet you "+ name)

输出:

NameError: name 'Zeeshan' is not defined

上面的代码导致了一个名称错误,因为在旧版本的Python中,input不是用来读取字符串的,而是用来计算Python表达式的。为了修复这个名称错误,我们可以使用raw_input函数,因为它是为读取字符串而构建的。

让我们使用raw_input函数来修复名称错误。

name = raw_input("Hi! What is your good name? ")
print("Nice to meet you "+ name)

输出:

Hi! What is your good name? Nice to meet you Zeeshan

正如你所看到的,raw_input函数已经修复了Name Error,并顺利地执行了程序。