A loop is programming statement that cause a statement or set of statements to execute repeatedly. Most loops should have condition logic built into them that causes the loop to end. A loop that does not end is known as an "infinite loop". Looping statements are also sometimes referred to as repetition or iteration statements.
The two main types of loops are:
- Count-controlled loop, i.e. definite loop
- Repeats instructions a specific number of times
- Often performed with a for loop
- Condition-controlled loop, i.e. indefinite loop
- Repeats instructions while a condition is true
- Often performed with a while loop, do-while loop, or do-until loop
Python has both for and while loop.
Another way loops can be categorized is as a pre-test loop or post-test loop. Python only has pre-test loops, i.e. it doe snot have a do ... while loop.
Three important things are needed for a while loop to be coded and run properly. You will see this in these examples. They are:
- A counter: this is used to count how many times the loop has run. In this first example, "i" is the variable being used as the counter.
- A test condition: this is used to determine if the loop will run again. The condition must be true in order for the loop to run again. In this first example. "i < (less than) x) is the condition. So, if the user enters 5 as user input which gets stored in the variable x, then 1 is less than 5 and thus the code in the loop will run. Also note, with Python the code in the loop must be indented. This is a good things as it enforced good programming practice by making the code much more readable.
- Lastly, there must be a incrementer. i += 1 is the incrementer. It adds 1 to the variable i. So, after the loop has run once, i becomes 2 and the program returns back to the while (i <= x): test condition.
Python While Loops: Condition-Controlled Examples
Example: While True loop with incrementing and break
i = 1
while True:
print (i)
i += 1
if i > 5:
break
Output:
1
2
3
4
5
Example: While True loop with incrementing and break and user-defined function
def countNum(i):
print (i)
i += 1
return i
i = 1
while True:
i = countNum(i)
if i > 5:
break
Output:
1
2
3
4
5
Python has three loop control structures:
- break statement - terminates loop and transfers execution to statement immediately following loop.
- continue statement - causes loop to skip remainder of its body and retest condition prior to reiterating.
- pass statement - used when statement is required syntactically but you do not want any command or code to execute.
Example: While True loop in Python - break command
count = 0
while True:
print (count)
count += 1
if count >= 5:
break
Output:
1
2
3
4
Example: While loop with String Comparison Expression
choice = "Y"
while choice == "Y" or choice == "y":
f = float(input("Please enter F temperature: "))
c = (f - 32) * (5/9)
print(f, "F temperature is equal to %.0f" % c, "temperature.")
choice = input("Would you perform another conversion (y/n)? ")
Example: While loop with List
choice = "Y"
while choice in ("y", "Y", "yes","YES","Yes"):
f = float(input("Please enter F temperature: "))
c = (f - 32) * (5/9)
print(f, "F temperature is equal to %.0f" % c, "temperature.")
choice = input("Would you perform another conversion (y/n)? ")
Example: While loop with List in Python
choice = "Y"
valid = ("Y","y","n","N")
yes_list = ("Y","y","yes","Yes","YES")
while choice in yes_list:
weight = float(input("How much do you weight? "))
height = float(input("How tall are you in inches? "))
bmi = 703 * (weight / (height * height))
print ("Your BMI is: %.2f" % bmi)
choice = input("Would you like to make another BMI calculation (Y/N)? ")
while choice not in valid:
choice = input("Invalid choice. Enter a Y or N? ")
Example: While True loop for Menu in Python
menu_chosen=True
while menu_chosen:
print ("MAIN MENU")
print ("-----------------")
print ("1. Print pay check")
print ("2. Change benefits")
print ("3. Exit")
menu_chosen = int(input("Chose menu option: "))
if menu_chosen == 1:
print("Change benefits function call will go here.\n")
elif menu_chosen == 2:
print("Change benefits function call will go here.\n")
elif menu_chosen == 3:
print("\n Goodbye")
menu_chosen = None
else:
print("\n Not Valid Choice Try again \n")
Example: While True loop for Menu in Python
menu_chosen = True
def menu():
while menu_chosen:
print("MAIN MENU")
print("-----------------")
print("1. Print pay check")
print("2. Change benefits")
print("3. Exit")
choice = int(input("Chose menu option: "))
if choice not in range(1,4):
print("\n Not Valid Choice Try again \n")
else:
break
return choice
choice = menu()
print("You chose menu option", choice)
Output:
MAIN MENU
-----------------
1. Print pay check
2. Change benefits
3. Exit
Chose menu option: 4
Not Valid Choice Try again
MAIN MENU
-----------------
1. Print pay check
2. Change benefits
3. Exit
Chose menu option: 1
You chose menu option 1
Example: Alternate Method to Complete Previous Example
def menu():
menu_chosen = True
while menu_chosen:
print("MAIN MENU")
print("-----------------")
print("1. Print pay check")
print("2. Change benefits")
print("3. Exit")
choice = int(input("Chose menu option: "))
if choice not in range(1,4):
print("\n Not Valid Choice Try again \n")
else:
menu_chosen = None
return choice
choice = menu()
print("You chose menu option", choice)
Example: Endless loop in Python (not recommended)
x = 1
while True:
print ("To infinity... ", x)
x += 1
Output:
To infinity... 1
To infinity... 2
...
...
Example: Number Guessing Game using loop in Python
import random
n = 20
guess = 0
num = random.randrange(1,20)
while guess != num:
guess = int(input("Enter your guess (1-20): "))
if guess > num:
print("That's too large")
elif guess < num:
print("That's too small")
else:
print("Congratulations. You got it correct.")
Output:
Enter your guess (1-20): 4
That's too small
Enter your guess (1-20): 9
That's too small
Enter your guess (1-20): 15
That's too large
Enter your guess (1-20): 12
Congratulations. You got it!
Example: While True loop with function in Python
def calcAreaCircle(rad):
area = 3.14159 * (rad ** 2)
print("Area of circle is %.2f" % area)
while True:
rad = int(input("Enter a radius (or 0 to exit): "))
calcAreaCircle(rad)
againYN = input("Perform another calculation (y/n? ")
while againYN not in ["y","n","Y","N","Yes","No"]:
againYN = input("Invalid choice. Please enter y or n: ")
if againYN in ["n","N","No"]:
break
Output:
Enter a radius (or 0 to exit): 2
Area of circle is 12.57
Perform another calculation (y/n? pp
Invalid choice. Please enter y or n: y
Enter a radius (or 0 to exit): 3
Area of circle is 28.27
Perform another calculation (y/n? n
Example: While True loop with nested while loop for input validation
while True:
number = int(input("Please enter even number that is divisible by 7: "))
while (number % 7) != 0:
number = int(input("Number must be divisible by 7. Please re-enter: "))
print("Congratulations,", number, "divisible by 7")
break
Output:
Please enter even number that is divisible by 7: 1 {user input}
Number must be divisible by 7. Please re-enter: 14 {user input}
Congratulations, 14 divisible by 7
Example: Alternate Method of Performing Previous Program
number = int(input("Please enter even number that is divisible by 7: "))
while (number % 7) != 0:
number = int(input("Number must be divisible by 7. Please re-enter: "))
print("Congratulations,", number, "divisible by 7")
Example: Number Guessing Game using loop in Python
import random
n = 20
guess = 0
num = random.randrange(1,20)
while guess != num:
guess = int(input("Enter your guess (1-20): "))
if guess > num:
print("That's too large")
elif guess < num:
print("That's too small")
else:
print("Congratulations. You got it correct.")
Output:
Enter your guess (1-20): 4
That's too small
Enter your guess (1-20): 9
That's too small
Enter your guess (1-20): 15
That's too large
Enter your guess (1-20): 12
Congratulations. You got it!