简体   繁体   中英

python match variable to dict key and return value

I'm a python noob, trying to take a variable, match this to a dictionary key and then return the value of the matching key. If it doesn't match any, continue loop. The goal is to create a crude user database so that user input can choose the corresponding class instance of the same name.

I'm getting a syntax error: if name == account_list[]: SyntaxError: invalid syntax (pointing to the 2nd []). Is there a syntax to make this work, or am I off base here? Thanks in advance for the help.

class BankAccount():
     balance = 0.0
     account_owner = ""
     def welcome(self):
          print("Welcome, " + self.account_owner.name + "!")

account_list = {
"Matty": mattyAccount
"Hannah": hannahAccount
..etc
}
name = input("Enter Username:\n")
while name != account_list[]:
     print("Not recognized.")
else:
     account_list[name].welcome()

Use the in keyword in python.

if name in account_list:
    account_list[name].welcome()
else
    print("Not recognized")

If you want to loop until the user is entering a valid name:

while(True):
    name = input("Enter Username:\n")
    if name in account_list:
        account_list[name].welcome()
        break # Will exit the while loop.
    else
        print("Not recognized... Try again...")

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