蟒蛇。如何添加.lower()。

时间:2016-11-14 21:26:47

标签: python case-sensitive

user1 = "aqa code" 
pass1 = "uzair123"
username = input("Enter username: ")
password = input("Enter password: ")
while username !=  user1:
    print("Access denied: username is incorrect try again ")
    username = input("Enter username again: ")
    if username == user1:
        print("access granted")
        while password != pass1:
            print("Password is still incorrect")
            password=input("Enter password again: ")
            if password == pass1:
                print("Access granted")
while password != pass1:
    print("Access denied,Password is incorrect")
    password=input("Enter password again: ")
    if password == pass1:
        print("Access granted")

如何在用户名/ user1中添加.lower(),以便在输入答案时变为不区分大小写?请帮忙。

2 个答案:

答案 0 :(得分:0)

您可以在返回输入功能时调用.lower

username = input("Enter username: ").lower()
password = input("Enter password: ").lower()

答案 1 :(得分:0)

添加.lower()确实是您正在寻找的解决方案,但您可能希望尝试简化一下流程,因此每当您想要修改输入语句时,编辑的位置就会减少。为此,我建议为每个循环创建一个最初为false的变量,并且只在每个循环中获取一次用户输入:

loop_condition = False  #initialize loop condition
while not loop_condition:  #loop until we say so
    value = input("please enter a value: ")  #human input
    value = value.lower() #convert to lower case for comparison
    if value == "password":  #test
        print("success")
        loop_condition = True  #loop will terminate when we hit our `while` again
    else:
        print("fail")
print("rest of program goes here")

在这里,您可以看到我们只调用input()一次,并且只需要在一个地方将其转换为小写。简单永远是你的朋友。

注意:如果您使用的是python 2.7,请使用raw_input()