这是我的第一个Python程序。我实现了一个字典,如下所示。在这里,我试图根据用户输入检索值* (键或值) *。
例如:如果用户输入“1”,那么我需要从dictioanry中检索“Sachin Tendulkar”。如果用户输入“Sachin Tendulkar”,那么我需要从dictioanry中检索“1”。
streetno={"1":"Sachin Tendulkar","2":"Sehawag","3":"Dravid","4":"Dhoni","5":"Kohli"}
while True:
inp=input('Enter M/N:')
if inp=="M" or inp=="m":
key=raw_input( "Enter the main number :")
result=streetno.get(key)
else:
key=raw_inp("Enter the street name : ")
result=streetno.get(key)
我认为逻辑没有错。但我无法执行它。我收到以下错误。
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Enter M/N:m
Traceback (most recent call last):
File "C:\Users\kiran\Desktop\Cricketpur.py", line 3, in <module>
inp=input('Enter M/N:')
File "<string>", line 1, in <module>
NameError: name 'm' is not defined
>>>
答案 0 :(得分:5)
问题在于这一行:
inp=input('Enter M/N:')
您使用input
代替raw_input
,而您实际上不应该这样做,因为它会执行用户输入作为Python代码的所有内容。只需在这里使用raw_input
就可以了。
但是,您的其余代码也会被破坏,并且不应该像预期的那样工作。我试图修复它:
streetno = { "1" : "Sachin Tendulkar",
"2" : "Sehawag",
"3" : "Dravid",
"4" : "Dhoni",
"5" : "Kohli"}
# we create a "reversed" dictionary here that maps
# names to numbers
streetname = dict((y,x) for x,y in streetno.items())
while True:
inp = raw_input('Enter M/N:')
if inp == "M" or inp == "m":
key = raw_input("Enter the main number:")
# you don't need .get here, a simple [] is probably what you want
result = streetno[key]
else:
key = raw_input("Enter the street name: ")
# we need to use our reversed map here!
result = streetname[key]
# do something with the result (change that to whatever you want
# to do with it)
print result
答案 1 :(得分:2)
如果你想要输入一个使用raw_input的字符,而不是输入(接受表达式并尝试评估它),而不是raw_inp(不存在)。
此外,你的'while True'表达永远不会结束。
你没有正确缩进你的'else'条款。
答案 2 :(得分:2)
问题似乎是您使用input
作为第一个问题(您正在使用raw_input
进行其他问题)
作为旁注,您可能想要查看python的内置模块cmd
以获取此类程序。它专门用于创建这样的命令行程序:
答案 3 :(得分:1)
由于您使用的是Python 2.7,input()
的行为与eval(raw_input())
相似,这意味着它正在评估输入内容。将其更改为raw_input()
。此外,raw_inp
不是一项功能,因此您也需要将其更改为raw_input()
。
还有一些缩进问题;你应该确保一切都正确缩进。看来你的循环也不会结束。