【发布时间】:2013-11-12 13:45:27
【问题描述】:
编写一个以名为 DB 的字典为中心的程序,其中包含作为键的协议名称和作为值的这些协议的文本描述。没有全局变量。
• 在 main 中是一个循环,询问用户输入“协议”
• 循环调用 TF 以查看协议(密钥)是否存在于 DB 中。 TF 返回 T 或 F。
• 如果 T 则 main 调用 PT 打印值并继续..
• 如果 F 则 main 调用 ADD 提示输入值并将 KV 对添加到 DB。
循环直到用户输入'end'然后打印数据库
这是我目前所拥有的:
#!/usr/bin/python3
#contains protocol names as keys, and text descriptions of protocols as values
DB= {'ICMP': 'internet control message protocol', 'RIP':'RIP Description',
'ipv4':'Internet protocol v4', 'ipv6':'IP version 6'}
def TF(x):
return x in DB
def PT(x):
print("The protocol you entered is: " , x)
return x
def ADD(x):
usr_input = input("Please enter a value to be added to the DB: ")
description = input("Please enter description for the key: ")
DB[usr_input] = description
for i in DB:
user_input = input("Please enter the protocol: ")
if (user_input == "end"):
break
TF(user_input)
if (TF(user_input) == True):
PT(user_input)
else:
ADD(user_input)
我得到了用户输入的提示,但是每当我在提示符下输入“ICMP”之类的操作时,它只会打印出相同的答案并继续无限循环,直到我按下 Control+D。我在这里做错了什么?即使我输入一个不在字典中的键,它也会做同样的事情。请帮忙。谢谢。
编辑:修复了无限循环问题并编辑了 PT(x) 以显示它正在被调用。现在还修复了问题,以便在 DB 中不存在键值时调用 ADD(x)。
持续存在的问题:即使我输入,例如“ICMP”作为输入,它只返回键本身,而不是与键关联的值?如何让值出现?
其次,现在如果用户输入不存在,则调用 ADD(x),但是,它不会附加到 DB 字典并将其打印出来。相反,我得到以下信息:
Please enter the protocol: ICMP
The protocol you entered is: ICMP
Please enter the protocol: icmp
Please enter a value to be added to the DB: here here
Please enter description for the key: herererere
Traceback (most recent call last):
File "D:/Sheridan/Part Time/Linux Architecture w. Network Scripting/Week 8 Code/practise_in_class.py", line 24, in <module>
for i in DB:
RuntimeError: dictionary changed size during iteration
【问题讨论】:
-
• 在 main 中有一个循环询问用户输入“协议”。 你的“main”块在哪里?您需要在
if __name__ == '__main__':块中编写代码的使用输入部分。而且,您需要运行无限循环,而不是在 DB 上运行循环。
标签: python for-loop dictionary main