我正在创建一个基本登录名,以验证输入的密码和该密码的确认是否匹配。
def login():
username = input("Please enter a username:")
password = input("Please enter a password:")
confirmPass = input("Please confirm your password:")
login()
if password == confirmPass:
print("You have signed up")
我收到未定义名称密码的错误。
答案 0 :(得分:1)
函数login
中的变量限于函数login
的作用域。
您可以将支票移到该功能内:
def login():
username = input("Please enter a username:")
password = input("Please enter a password:")
confirmPass = input("Please confirm your password:")
if password == confirmPass:
print("You have signed up")
login()
其他可能性:
login
返回一个布尔值并检查返回值答案 1 :(得分:1)
您接近了,只需从函数中返回password, confirm_pass
中的值即可。同样,snake_case
不是camelCase
https://www.python.org/dev/peps/pep-0008/
def login():
username = input("Please enter a username:")
password = input("Please enter a password:")
confirm_pass = input("Please confirm your password:")
return password, confirm_pass
password, confirm_pass = login()
if password == confirm_pass:
print("You have signed up")
答案 2 :(得分:1)
我认为这就是你想要的,我添加了一个额外的和平(如果你想要复制):
name = input("enter a username: ")
password = input("enter a password")
repass = input("retype your passsword: ")
if password == repass:
print("signed in.")
else:
print("passwords do not match..")
#extra copy if you want...
name1 = input("enter a username: ")
password1 = input("enter a password: ")
if password1 == repass:
if name1 == name:
print ("logged in.")
else:
print("incorrect username")
else:
print("incorrect password.")
答案 3 :(得分:0)
我宁愿从函数中返回值-但是如果您想使用模块级全局变量,只需在调用username
之前定义password
和login()
。
类似的东西:
def login():
username = input("Please enter a username:")
password = input("Please enter a password:")
confirmPass = input("Please confirm your password:")
username = ""
password = ""
login()
if password == confirmPass:
print("You have signed up")
我相信,这应该可以按您预期的方式工作。
答案 4 :(得分:0)
如果不确定,最好不要在函数内声明任何变量。尝试以下代码:
username = input("Please enter a username:")
password = input("Please enter a password:")
confirmPass = input("Please confirm your password:")
def match_password(password,confirmPass):
if password == confirmPass:
print("You have signed up")
else:
print("Passwords do not match")
match_password(password,confirmPass)
所有变量都是根据函数外部的输入声明的,以验证密码。