Python在此代码上抛出SyntaxError

时间:2013-05-21 13:09:23

标签: python dictionary

while 1:
    dic = {} #empty dictionary which will be used for storing all the data
    dic[raw_input("Enter the value you want to store: ")]  = input("Enter the access key of a value: ")
    ans = raw_input("Exit:e ; Store another variable : s; Acces a variable: a")
    if ans=="e":
        break; #exit the main loop
    elif ans == "s":
        continue;
    elif ans=="a":
        pass;

请帮忙

2 个答案:

答案 0 :(得分:4)

您使用input()代替raw_input();这将输入解释为Python表达式。抛出一个SyntaxError异常很容易:

>>> input("Enter a sentence: ")
Enter a sentence: The Quick Brown Fox
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    The Quick Brown Fox
            ^
SyntaxError: invalid syntax

改为使用raw_input()

dic[raw_input("Enter the value you want to store: ")]  = raw_input("Enter the access key of a value: ")

你可能想要解决这两个问题:

dic[raw_input("Enter the access key of a value: ")] = raw_input("Enter the value you want to store: ")

Python将首先要求。如果您需要先请求密钥,请先将其存储在单独的变量中:

key = raw_input("Enter the access key of a value: ")
dic[key] = raw_input("Enter the value you want to store: ")

答案 1 :(得分:0)

你的线条错误,你需要:

dic[raw_input("Enter the access key of a value: ")]  =  input("Enter the value you want to store: ")

 dic[raw_input("Enter the value you want to store: ")]  = input("Enter the access key of a value: ")

完整的代码将是:

while 1:
    dic = {} #empty dictionary which will be used for storing all the data
    dic[raw_input("Enter the access key of a value: ")]  =  input("Enter the value you want to store: ")
    ans = raw_input("Exit:e ; Store another variable : s; Acces a variable: a")
    if ans=="e":
        break; #exit the main loop
    elif ans == "s":
        continue;
    elif ans=="a":
        pass;