Search code examples
pythonwhile-loopbreakcontinue

Stuck on Automate The Boring Stuff Chapter 2- Continue Statement


I'm currently on Chapter 2 of Automate the Boring Stuff and am stuck on Continue Statement. The example given is if the name inputted is 'Joe' and the password is 'swordfish', the program would print 'Access granted'. However, I'm not sure why mine keeps printing 'Who are you?' when the condition for name = 'Joe' and password = 'swordfish' have already been fulfilled. Can anyone advise why I'm still stuck in the while-loop?

*while True:
    print('Who are you?')
    name = input()
    name = Joe
    if name != 'Joe':           #if name equal to 'Joe', print('Hello, Joe. What is the password? (It is a fish.)')
        continue                #if name not equal to 'Joe', continue executing while-loop
    print('Hello, Joe. What is the password? (It is a fish.)')
    password = swordfish
    if password == 'swordfish':    #if password equal to 'swordfish', exit the while-loop
        break                      #if password not equal to 'swordfish', execute the while-loop
print('Access granted.')*

Solution

  • You are telling the function to continue after the if statement. So effectively if name != 'Joe' you want your function to continue, but if it is not, it's going to keep right on executing anyway.

    There are other problems here that are going to cause you grief. You aren't actually using the variables defined by your input() and you aren't asking for user input() for the password.

    To further simplify your code you can get rid of the continue statement altogether and just determine if name == 'Joe'. If it does, you can then ask for the password. Otherwise, the loop can continue. Here's a simplified solution:

    while True:
        name = input('Who are you?')
        if name == 'Joe':
            password = input('Hello, Joe. What is the password? (It is a fish.)')  
            if password == 'swordfish':
                print('Access granted.')
                break