【问题标题】:Calling a Function from an 'If' statement从“If”语句调用函数
【发布时间】:2016-01-09 19:50:56
【问题描述】:

我正在使用 Python 3,并且在尝试从 if 语句调用函数时遇到错误,以下代码是完整代码的简化版本,但结果相同,我正在徘徊如何克服这个问题和允许程序运行 student() 函数

import sys

def logon():
    print("Welcome, please enter your account type")
    acctype = input()
    if acctype == 'teacher':
        sys.exit()
    elif acctype == 'student':
        student()

logon()


def student():
    print("Please enter your name") 
    name = input()

    print("Please enter your class number")
    classnumber = input()

输入单词student后出现问题,错误返回

NameError: name 'student' is not defined

【问题讨论】:

  • 以后,总是包含 full 回溯,而不仅仅是最后一行。这样我就能更快地看到确切的问题。

标签: python function python-3.x if-statement


【解决方案1】:

Python 从上到下运行代码。每个def 行都会创建一个函数对象并将其存储为全局名称。

logon() 行运行时,def logon(): ... 语句已经执行,函数存在。但是,def student(): ... 语句还没有到达,所以还没有这样的函数。所以当logon()函数试图调用student()函数时,你会得到一个NameError异常。

将调用函数的logon() 行移到下面def student(): ... 语句。

【讨论】:

  • 感谢您的回答,这对刚接触 Python 的学生特别有帮助!
猜你喜欢
  • 2016-06-28
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 2017-12-05
  • 2020-06-09
相关资源
最近更新 更多