首页 > 解决方案 > How do I get the values in my dictionary that I have created in python, to be used, instead of the strings?

问题描述

Below is a shortened version of my code, without all the validation. I am writing a program that tells the user how strong their password is, by seeing their overall score at the end. If the password has 3 letters next to each other in a row, and those three letters are also next to each other on the 'qwerty' keyboard, then their overall score goes down by 5. I have created a dictionary to assign each letter on the keyboard a value, and then if 2 consecutive letters in the password have a difference of 1, it means there are 3 letters in a row on the keyboard. However, I keep getting a

ValueError: invalid literal for int() with base 10:

I don't really know how to use dictionaries, so any help is much appreciated!

password=str(input("Please enter a password with more than 4 digits, and it should only be letters:"))
score=0
keyboard={'Q':1,'q':1,'W':2,'w':2,'E':3,'e':3,'R':4,'r':4,'T':5,'t':5,'Y':6,'y':6,'U':7,'u':7,'I':8,'i':8,'O':9,'o':9,'P':10,'p':10,'A':12,'a':12,'S':13,'s':13,'D':14,'d':14,'F':15,'f':15,'G':16,'g':16,'H':17,'h':17,'J':18,'j':18,'K':19,'k':19,'L':20,'l':20,'Z':22,'z':22,'X':23,'x':23,'C':24,'c':24,'V':25,'v':25,'B':26,'b':26,'N':27,'n':27,'M':28,'m':28}
for n in range ((len(password))-2):
    if (int(password[n+1])-int(password[n])==1) and (int(password[n+2])-int(password[n+1]==1)):
        score=score-5
        print(score)

标签: python-3.xdictionaryvalueerror

解决方案


如果您的password输入仅为 letters,则以下行将引发错误。

int(password[n+1])

也会int(password[n])和你所有的其他int演员。原因是您将非数字字符转换为int. 这就是导致您看到的错误的原因。

相信,你的意图是做

int(keyboard[password[n+1]]) - int(keyboard[password[n]]) == 1

但是由于您的keyboard字典的值已经是int',因此int不需要 if 语句中的强制转换。

keyboard[password[n+1]] - keyboard[password[n]] == 1

推荐阅读