yandex
loader

please wait

  • Shreya Bansal Mar-13-2019 06:20:31 AM ( 1 week ago )

    So i'm trying to ask for an input and then validate if the password is correct. It will check if the input is blank, incorrect or correct. However, after the first initial blank input, if I enter a blank again the program breaks. How do I make it keep looping and validating correctly

    def getUserName():
        userName = ["Chan"]
        userNameInput = [""]
        userNameInput[0] = input("Username: ")
    
        while userNameInput != userName:
            if userNameInput[0] == "":
                print("Username can not be blank. Please try again.")
                userNameInput = input("Username: ")
            elif userNameInput[0] == userName[0]:
                print("Username is correct. Input password.")
            else:
                print("Username is not correct. Please try again.")
                userNameInput = input("Username: ")
  • Jignesh Patel Mar-13-2019 06:22:12 AM ( 1 week ago )

    Why do you need lists to store the username and username input instead of just typical strings?

    The reason the code fails with a string index out of range is that you set the userNameInput variable to a string instead of settings its first element to the string.

    However, it would be preferable to just use strings instead of lists in the first place.

    def getUserName():
        userName = "Chan"
        userNameInput = input("Username: ")
    
        while userNameInput != userName:
            if len(userNameInput) == 0:
                print("Username can not be blank. Please try again.")
                userNameInput = input("Username: ")
            elif userNameInput == userName:
                print("Username is correct. Input password.")
            else:
                print("Username is not correct. Please try again.")
                userNameInput = input("Username: ")

    Here is a solution using strings instead of lists that solves your issue.
  • Vikrant Srivastava Mar-13-2019 06:24:00 AM ( 1 week ago )

    The problem is that you are comparing the array index 0 however on the second time you set userNameInput it is being set to a string and not an array.

    The fix would look something like this:

    def getUserName():
    userName = ["Chan"]
    userNameInput = [""]
    userNameInput[0] = input("Username: ")
    
    while userNameInput != userName:
    
        if userNameInput[0] == "":
            print("Username can not be blank. Please try again.")
            userNameInput[0] = input("Username: ")
        elif userNameInput[0] == userName[0]:
            print("Username is correct. Input password.")
        else:
            print("Username is not correct. Please try again.")
            userNameInput[0] = input("Username: ")

Please login

Similar Discussion

Recommended For You