40 Challenges 45 - 51: While Loop
Challenges 45 - 51
While Loop
Explanation
A while loop allows code to be repeated an unknown number of times
as long as a condition is being met. This may be 100 times, just the once or
even never. In a while loop the condition is checked before the code is run,
which means it could skip the loop altogether if the condition is not being
met to start with. It is important, therefore, to make sure the correct
conditions are in place to run the loop before it starts.
In Python the example for the flow chart above would look as follows:
It will keep repeating this code until the user enters anything other than “yes”.
Challenges 45 - 51: While Loop 41
Example Code
total = 0
while total < 100:
num = int(input(“Enter a number: ”))
total = total + num
print(“The total is”, total)
The above program will create a variable called total and store the
value as 0. It will ask the user to enter a number and will add it to
the total. It will keep repeating this as long as the total is still
below 100. When the total equals 100 or more, it will stop running
the loop and display the total.
Comparison Operators Logical Operators
Operator Description Operator Description
== Equal to and Both conditions must be met
!= Not equal to or Either condition must be met
> Greater than
Remember: text values must appear
< Less than in speech marks and numeric values
>= Greater than or equal to do not.
<= Less than or equal to