我制作了ATM功能程序,我需要帮助,因为我无法在我的程序中显示我的用户名(un)和密码(pw),错误是
NameError: name 'un' is not defined
我尝试在第一行中定义un,但在用户输入其信息后,该值不会更改。
#functions
def FWelcome():
print("WELCOME!")
print("Please Log-In to access ATM:")
return;
def FUsername():
while True:
un=input("\nEnter Username ( use only letters ):")
if un.isalpha():
break
else : #invalid
print ("Invalid Username. Use of symbols and/or numbers are not allowed.\n")
return;
def FPassword():
while True:
pw=input("Enter Password ( use only numbers ):")
if pw.isnumeric():
break
else : #invalid
print ("Invalid Password. Use of symbols and/or letters are not allowed.\n")
return;
#atm program
FWelcome()
#username
FUsername()
#password
FPassword()
print("\nHello! Your Username is ", un, " and your password is ",pw )
答案 0 :(得分:1)
您应该返回值:
def FUsername():
while True:
un=input("\nEnter Username ( use only letters ):")
if un.isalpha():
break
else : #invalid
print ("Invalid Username. Use of symbols and/or numbers are not allowed.\n")
return un
def FPassword():
while True:
pw=input("Enter Password ( use only numbers ):")
if pw.isnumeric():
break
else : #invalid
print ("Invalid Password. Use of symbols and/or letters are not allowed.\n")
return pw
#atm program
FWelcome()
#username
un = FUsername()
#password
pw = FPassword()
答案 1 :(得分:0)
un
在FUsername
内定义,因此无法全局访问。您必须将“print un
”语句放在函数内部或者使用默认虚拟值全局声明它,然后在FUsername
答案 2 :(得分:-1)
您在函数内部声明了un,但尝试在该函数之外访问它。解决这个问题的一种方法是返回值。另一种方法是使变量成为全局变量。
#Comment the 2 below lines out if you want to return the variables from the function.
un=input("\nEnter Username (use only letters ):")
pw=input("Enter Password ( use only numbers ):")
def FWelcome():
print("WELCOME!")
print("Please Log-In to access ATM:")
return;
def FUsername():
while True:
#Comment this out if you want to declare it globally
un=input("\nEnter Username ( use only letters ):")
if un.isalpha():
break
else : #invalid
print ("Invalid Username. Use of symbols and/or numbers are not allowed.\n")
return un
def FPassword():
while True:
#Comment this out if you want to declare it globally.
pw=input("Enter Password ( use only numbers ):")
if pw.isnumeric():
break
else : #invalid
print ("Invalid Password. Use of symbols and/or letters are not allowed.\n")
#Or return the variable un
return pw
#atm program
FWelcome()
#username
FUsername()
#password
FPassword()
print("\nHello! Your Username is ", un, " and your password is ",pw )