Python中的错误

Kir*_*hat 0 python

这是我的第一个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)
Run Code Online (Sandbox Code Playgroud)

我认为逻辑没有错.但我无法执行它.我收到以下错误.

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
>>> 
Run Code Online (Sandbox Code Playgroud)

Nik*_* B. 5

问题在于这一行:

inp=input('Enter M/N:')
Run Code Online (Sandbox Code Playgroud)

您使用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
Run Code Online (Sandbox Code Playgroud)