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

Python 在字典中使用for循环时出现语法错误,python,python-3.x,dictionary,for-loop,Python,Python 3.x,Dictionary,For Loop,我从下面的代码中得到这个错误 Error: **if names == inp1: ^ SyntaxError: invalid syntax** "^" points colon 我找不到问题。 代码: 您可以直接使用if-else而不使用for循环来访问字典。 python中的字典类似于其他语言中的哈希映射数据结构 inp1 = input("Enter your username: ") inp2 = int(input("Enter your p

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

Error:
**if names == inp1:
                  ^
SyntaxError: invalid syntax**  "^" points colon 
我找不到问题。 代码:


您可以直接使用if-else而不使用for循环来访问字典。 python中的字典类似于其他语言中的哈希映射数据结构

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")
链接:

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


前一行
str(输入(“输入您的用户名”)
在此处和下一行输入时关闭括号…后一行也是如此-在
inp1…
inp2…
上都有一些避免这些问题的建议:1)打开括号时,立即关闭它,然后在括号内插入代码;2) 在编辑器中启用括号匹配;3) 在编辑器中启用一个linter语法和逻辑错误除外,这不是使用字典的好方法。不要循环所有键以找到匹配的键。1那些
str
调用是多余的:
input
返回字符串。2如果dic.keys()中的inp1为
,而不是
您可以编写
如果dic中的inp1为:
我希望这将对您有所帮助
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")
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")
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")