Last answered:

13 Dec 2021

Posted on:

13 Dec 2021

0

I do not get how the While Loop is working.

I have been listening to Giles explanation a couple of times but still I do not get how the While Loop is working. Could someone please shed some light here?

1 answers ( 0 marked as helpful)
Posted on:

13 Dec 2021

0

First of all, keep in mind that "while loop" evaluates expressions in Boolean context. So, it checks whether an expression
is True or False. If True, then it executes the statement (here: print('You must ...") and user_input = input("Which ... ")). The execution continues until it returns False.

In this loop, what we need is to check if the user inputs are alphabets, so we don't want numbers or any other characters as input. That is basically the whole point of the while loop here: "not user_input.isalpha()" checks if the user input is alphabet or not, if not, then it returns True, and then it asks the user to enter a string. If it returns False, then the whole while loop is ignored (means the user has already entered a string) and we go to the next block of codes.

The confusing part is the "united kingdom" and "united states". The point is that if you run this code: "united
states".isalpha() it returns False. The reason why is the space character between united and states (or kingdom). So, we adjust the "not user_input.isalpha()" as such that it ignores to check "united
kingdom".

Remember the Boolean context, and the logical operator "and" in the code. So, if user enters "united kingdom", the
part: "united_kingdom not in user_input" returns False and because of the 'and' operator the whole while loop breaks. we do the same for "united states" with a nested if loop. if True (if user has entered "united states") we ask the loop to break.

Submit an answer