简体   繁体   中英

I am getting a NameError: name 'n' is not defined

This function asks the name

def printName():
   print("Enter your name: ")
   n=input()
printName()

The if statement checks if n is equal to Python

if n=="Python":
   print("Welcome")
else:
   print("Try again")

n is only defined inside the function. This should work:

def printName():
   print("Enter your name: ")
   n=input()
   if n=='Python':
     ...

Alternatively you can also do:

def printName():
       print("Enter your name: ")
       n=input()
       return n

n = printName()
# now you can use n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM