Python While loop

We continue with our tutorials by modifying a bit our previous example in order to use loops. Lets request the number until the user input a correct number.

requestInput = True
oddNumbersArray = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59]

while requestInput:
    inputNumber = input("Input a number between 1 and 60 ")
    try:
        intNumber = int(inputNumber)
        if intNumber <= 60 and intNumber >= 1:
            requestInput = False
        else:    
            print("Number is out of bounds")
    except Exception as e:
        print(e)

if intNumber in oddNumbersArray:
    print("Number is odd ", intNumber)
else:
    print("Number is even")

Line 1 Define a boolean variable requestInput with True value for using with the while loop
Line 2 Create a List of odd numbers
Line 3 Creating the loop using while with the boolean requestInput True, everything inside the while will be in loop until the boolean variable becomes False
Line 4 Request a number
Line 5 Use try catch exception just in case somebody type something different than a number
Line 6 Convert the input string to a int
Line 7 Verify if the number is between bounds
Line 8 If it is we setup the variable requestInput to False so the loop ends
Line 9 If it is not, we print the message “Number is out of bounds”
Line 10 Catch the exception as variable e. (in case there is an exception)
Line 11 We print the exception message. (in case there is an exception)
Line 12 Verify if number is in the List
Line 13 If the number is in the list we print “Number is odd” with the number
Line 14 If the number is not on the list we print a message “Number is even”

That is how we use the while loop, next tutorial will be about For loop, see you on the next tutorial!