简体   繁体   中英

New to Python (and programming) can't see where I'm going wrong

I'm learning a bit of Python in my spare time. Trying to make a phonebook, found one on this site; Python assignment for a phonebook . Have used that as a template but left out the print_menu function. That's the only difference that I can see but when I add a number it gets stuck in that part. Just asking to enter name and number, not escaping the if loop. If anyone can tell me why I get stuck like this I would appreciate it.

phoneBook = {}

def main():
    action = input("What would you like to do? \n 1. Add \n 2. Delete \n 3. Print \n 4. Quit \n")
    while action != 4:
        if action == '1':
            name = input("Enter name: ")
            num = input("Enter number: ")
            phoneBook[name] = num
        elif action == '2':
            name = input("Delete who?")
            if name in phoneBook:
                del phoneBook[name]
            else:
                print("Name not found")
        elif action == '3':
            print("Telephone numbers: ")
            for x in phoneBook.keys():
                print("Name: ", x, "\tNumber: ", phoneBook[x])
        elif action == '4':
            print("Application closed.")

main()

input() returns a string, not an integer.

So

while action != 4:

should become:

while action != '4':

You have two problems here. As Padraic and Leistungsabfall mention, input returns a string, but you also are only getting the input one time. If you want to continue getting input, you're going to need to put that inside your loop:

action = None
while action != '4':
    action = input('What action would you like? ')
    # the rest of your code here

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