Roberts Krūmiņš
Roberts Krūmiņš

Reputation: 35

python while with if/else statement

It's for my school work. I need to fix this code. Can someone maybe help me? I would really appreciate that. I can't manage to fix the "else" part. :)

CorrectUsername = "Username"
CorrectPassword = "Password"

loop = 'true'
while (loop == 'true'):
username = raw_input("Please enter your username: ")
if (username == CorrectUsername):
password = raw_input("Please enter your password: ")
if (password == CorrectPassword):
print "Logged in successfully as " + username
loop = 'false'
else:
print "Password incorrect!"
else:
print "Username incorrect!"

This is what I've done so far

CorrectUsername = "Username"
CorrectPassword = "Password"

loop = "true"
while (loop == 'true'):
    username = input("Please enter your username: ")
    if (username == CorrectUsername):
        password = input("Please enter your password: ")
        if (password == CorrectPassword):
            print("Logged successfully as " + str(username))
            loop = "false"
    else:
        print("Password incorrect!")
        else:
            print("Username incorrect")

Upvotes: 0

Views: 59

Answers (1)

azro
azro

Reputation: 54168

You have to indent the else properly it's matching if. Also use boolean values True/False, better than strings

CorrectUsername = "Username"
CorrectPassword = "Password"

loop = True
while loop:
    username = input("Please enter your username: ")
    if username == CorrectUsername:
        password = input("Please enter your password: ")
        if password == CorrectPassword:
            print("Logged successfully as " + str(username))
            loop = False
        else:
            print("Password incorrect!")
    else:
        print("Username incorrect")

Upvotes: 1

Related Questions