当我运行该程序时,即使我已经输入一次,它也会多次询问我的输入。
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
要求用户输入一个名称,该名称是值的关键,并返回
for i in Peeps:
if i == input("Type in a name: "):
print("The amount", [i], "owes is:", "$" + str(Peeps[i]))
break
else:
print("Sorry that name does not exist, please enter a new name.")
答案 0 :(得分:2)
您需要先询问用户输入,而不是直接将用户输入与密钥进行比较。
答案 1 :(得分:1)
你不想这样做。请看一下以下内容:
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
name = input("Type in a name: ")
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
您不必遍历dict
并单独检查每个值的用户输入(另外,您强制用户更新\连续输入他的输入)。
只需接收一次即可处理。
如果您想保持循环运行以允许多个查询,请使用while
,如下所示:
Peeps = {"Juan": 244, "Jayne": 433, "Susan": 751}
name = input("Type in a name or leave blank to exit: ")
while name:
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
name = input("Type in a name or leave blank to exit: ")