在字典中使用for循环时出现语法错误

时间:2018-01-25 09:00:05

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

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

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")

3 个答案:

答案 0 :(得分:0)

您可以直接使用if-else而不使用for-loop进行字典访问。 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")

link:https://repl.it/repls/AutomaticHospitableJay

答案 1 :(得分:0)

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")

答案 2 :(得分:0)

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")