【问题标题】:Syntax error when using for loop in dictionary [closed]在字典中使用for循环时出现语法错误[关闭]
【发布时间】:2018-01-25 09:00:04
【问题描述】:

我从下面的代码中得到这个错误。

Error:
**if names == inp1:
                  ^
SyntaxError: invalid syntax**  "^" points colon 

我找不到问题。 代码:

dic = {"John" : 12345,
   "Blake" : 456789,
   "Scarlett" : 124578,
   "Jake" : 852147,
   "Robert" : 963247895,
   "Jessica" : 4125036 }

for names in dic:
    inp1 = str(input("Enter your username: ")
    if names == inp1:
        inp2 = int(input("Enter your password: ")
        for pin in dic[names]:
            if inp2 == pin:
                print("*Access Granted*")
            else:
                print("*Access Denied")
    else:
        print("Wrong username")

【问题讨论】:

  • 上一行括号不均匀
  • str(input("Enter your username: ") 右括号在这里和下一个输入。
  • ...也是后者——在inp1... 和inp2... 行上
  • 一些避免这些问题的建议: 1)当你打开一个括号时,立即关闭它,然后在括号内插入代码; 2)在您的编辑器中启用括号匹配; 3) 在编辑器中启用 linter
  • 撇开语法和逻辑错误不谈,这不是使用字典的好方法。不要遍历所有键以找到匹配的键。

标签: python python-3.x dictionary for-loop


【解决方案1】:

您可以直接使用 if-else 而不使用 for 循环进行字典访问。 python中的字典类似于其他语言中的Hash-map数据结构。

inp1 = input("Enter your username: ")
inp2 = int(input("Enter your password: "))

if inp1 in dic:
  if inp2 == dic[inp1]:
    print("*Access Granted*")
  else:
    print("*Access Denied")
else:
  print("Wrong username")

链接:https://repl.it/repls/AutomaticHospitableJay

【讨论】:

  • 1 那些str 调用是多余的:input 返回一个字符串。 2 你可以写if inp1 in dic:而不是if inp1 in dic.keys():
【解决方案2】:

U 左括号在循环中 你更正的代码:-

dic = {"John" : 12345,
   "Blake" : 456789,
   "Scarlett" : 124578,
   "Jake" : 852147,
   "Robert" : 963247895,
   "Jessica" : 4125036 }

for names in dic:
    inp1 = str(input("Enter your username: "))
    if names == inp1:
        inp2 = int(input("Enter your password: "))
        for pin in dic[names]:
            if inp2 == pin:
                print("*Access Granted*")
            else:
                print("*Access Denied")
    else:
        print("Wrong username")

【讨论】:

  • 希望对你有帮助
【解决方案3】:
closing bracket is missing in input statement and second loop is not required.Also str() parsing is not required. By defalut input returns type is string     
dic = {"John" : 12345,
       "Blake" : 456789,
       "Scarlett" : 124578,
       "Jake" : 852147,
       "Robert" : 963247895,
       "Jessica" : 4125036 }

    for names in dic:
        inp1 = str(input("Enter your username: "))
        if names == inp1:
            inp2 = int(input("Enter your password: "))
            if inp2 == dic[names]:
                print("*Access Granted*")
            else:
                print("*Access Denied")
        else:
            print("Wrong username")

【讨论】:

    猜你喜欢
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    相关资源
    最近更新 更多