问题
a=str(input("Enter num To Start FunctionOne"))
if(a == '1'):
one()
elif (a == '2'):
tow()
def one():
print('Good')
def tow():
print('Very Good')
Error
Enter numper To Start FunctionOne1
Traceback (most recent call last):
File "C:/Users/Hacker/Desktop/complex program.py", line 3, in <module>
one()
NameError: name 'one' is not defined
回答1:
You need to define the functions before calling them:
def one():
print('Good')
def tow():
print('Very Good')
a=str(input("Enter num To Start FunctionOne"))
if(a == '1'):
one()
elif (a == '2'):
tow()
If you call a function but the function is defined below it then it won't work because Python doesn't know yet what that function call is supposed to do.
回答2:
Define your functions before using them
Python is an interpreted language, so the interpreter moves line by line, you are trying to call the function - one()
before it has been defined, in the later parts of the program. You should move the function definitions before calling part -
def one():
print('Good')
def tow():
print('Very Good')
a=str(input("Enter num To Start FunctionOne"))
if(a == '1'):
one()
elif (a == '2'):
tow()
回答3:
Don't put any instructions in the script other than function definitions. Then call the main function in a clause at the bottom. This lets the interpreter see everything defined before trying to call it:
def main():
a = input("Enter num To Start FunctionOne")
if a == '1':
one()
elif a == '2':
two()
def one():
print('Good')
def two():
print('Very Good')
if __name__ == '__main__':
main()
回答4:
Python reads the script line by line, so when it reaches the one() function call, it throws the error because is not defined yet.
来源:https://stackoverflow.com/questions/30947140/nameerror-name-one-is-not-defined-python-3-4-error