Python练习问题 - 运行功能时的名称错误



我正在进行Python课程,其中一个练习是编写一个将"医生"添加到名称中的函数。说明是:

定义函数make_doctor(),以参数名称获取可变full_name的用户输入使用full_name调用该函数作为参数打印返回值

我的代码是:

def make_doctor(name):
    full_name = input("Doctor ")
    return full_name
print(make_doctor(full_name))

但是,我不断遇到以下错误:

NameError                                 Traceback (most recent call last)
<ipython-input-25-da98f29e6ceb> in <module>()
      5     return full_name
      6 
----> 7 print(make_doctor(full_name))
NameError: name 'full_name' is not defined

你可以帮忙吗?

谢谢

您的代码有很多问题。

input不在功能之外。将输入传递给make_doctor以向其添加"医生",然后打印。

非常重要的侧面注意:如果python2和 input(),则使用 raw_input()。不要在Python 2中使用input(),其表达式评估器而不是字符串。

def make_doctor(name):
    return "Doctor {}".format(name)
name = raw_input("Enter your name here!!") # if python2
# name = input("Enter your name here!!") # if python3
print(make_doctor(name=name))

在您的代码中,变量full_name是函数make_doctor

的局部变量

尝试以下操作:

def make_doctor(name):
    return "Doctor "+name
full_name = input()
print(make_doctor(full_name))

最新更新