1

Beginner question! The else condition run even though the for statement is True and prints out the text message that declares that it hasn't found the key. Since the statement is True it also gives me the information I want, problem is that it runs else even though for is True.

input_namn = input("Ange ett namn: ")               
for key in rooms_with:                          
    if input_namn in rooms_with[key]:
        print (input_namn + "\ndelar rum med \n" + key)
else: 
    print ("\nPersonen du angav är inte en del av föreningen\n")

What have I done wrong?

1
  • what are the values in rooms_with ? Commented Jan 13, 2020 at 6:55

1 Answer 1

2

Your indentation is bad on the else clause.

Since it's on the same level as the for loop, the else belongs to the for loop and not the if statement.

Just indent the else clause on the same level as the if like below:

input_namn = input("Ange ett namn: ")
for key in rooms_with:
    if input_namn in rooms_with[key]:
        print (input_namn + "\ndelar rum med \n" + key)
    else: # This is indented correctly
        print ("\nPersonen du angav är inte en del av föreningen\n")

What happens when the else belongs to the for loop ?

Python documentation says:

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

Basically, at the end of the loop the else block is executed except if the loops was stopped by a break statement.

And since there was no break statement in your loop, your else branch was executed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.