我在业余时间学习了一些Python。试图制作一个电话簿,在这个网站上找到一个; Python assignment for a phonebook。已将其用作模板但省略了print_menu函数。这是我能看到的唯一区别,但是当我添加一个数字时,它会卡在那个部分。只是要求输入名称和号码,而不是转义if循环。如果有人能告诉我为什么我会这样被卡住,我会很感激。
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()
答案 0 :(得分:6)
input()
返回一个字符串,而不是整数。
所以
while action != 4:
应该成为:
while action != '4':
答案 1 :(得分:6)
这里有两个问题。正如Padraic和Leistungsabfall所提到的那样,input
返回一个字符串,但你也只获得一次输入。如果你想继续获得输入,你需要把它放在你的循环中:
action = None
while action != '4':
action = input('What action would you like? ')
# the rest of your code here