我遇到了從函數返回兩個變量的問題,儘管我已經將變量設置爲全局變量。我正在製作的程序旨在模擬添加用戶並登錄到該用戶或更改所述用戶密碼的過程。從函數返回變量python
check = False
global uname
global pword
uname = 0
pword = 0
while check == False:
def user(uname, pword):
set_uname = input("Enter username: ")
set_pword = input("Enter password: ")
print("Username and Password set")
return(set_uname, set_pword)
def login(uname, pword):
correct = False
while correct == False:
enter_uname = input("Enter username: ")
enter_pword = input("Enter password: ")
if enter_uname == uname and enter_pword == pword:
print("Login successful")
elif enter_uname != uname or enter_pword != pword:
print("Incorrect username or password")
correct = False
def cpword(pword):
done = False
while done == False:
check_pword = input("Enter current password: ")
if check_pword == pword:
new_pword = input("Enter new password: ")
if new_pword == pword:
print("New password cannot be old password")
done = False
elif new_pword != pword:
print("Password successfully changed")
pword = new_pword
done = True
return(pword)
elif check_pword != pword:
print("Incorrect password")
done = False
print("Enter User")
user(uname, pword)
uname = set_uname
pword = set_pword
print("Login = 1")
print("Change Password = 2")
choice = int(input("Enter function: "))
if choice == 1:
login(uname, pword)
elif choice == 2:
cpword(pword)
pword = pword
我不斷收到錯誤:
Traceback (most recent call last): File "C:\Users\tay.swain\Documents\Login.py", line 54, in uname = set_uname NameError: name 'set_uname' is not defined
一旦我設定的用戶,當我運行出現這個錯誤的登錄功能。我正在嘗試返回
return(set_uname, set_pword)
來自用戶功能。我知道如何從函數返回變量,但我無法在此代碼中使用它。
「我將變量設置爲全局」< - 您的程序沒有說'set_uname'和'set_pword'是全局的。 – khelwood
已經工作了,我已經設法返回像以前那樣的變量,而沒有將變量設置爲全局變量 –
爲什麼您確實希望'set_uname'在全局範圍內?而你腳本*頂部的'global'指令是完全多餘的*,你已經在全局範圍內*。另外,'user'函數返回一對值,但是當你不把任何調用的結果分配給任何東西....'user(uname,pword)'時,你只需放棄它們。 –