Python: For Loops

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:

  1. 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.
  2. 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.
  3. 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: Count-Controlled Examples


Example: Count-controlled While loop


	i = 1    
	x = int(input("How high do you want to count to? "))
	while (i <= x):
	   print (i)
	   i += 1
	

Output:

  How high do you want to count to? 3
  1
  2
  3


Example: Count-controlled While True loop with incrementing and break


	i = 1
	x = int(input("How high do you want to count to? "))
	while (i <= x):
	   print (i)
	   i += 1
	   if i > 10:
		   print("Sorry, we only allow you to count to 10. The End.")
		   break
	

Output:

  How high do you want to count to? 3
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  Sorry, we only allow you to count to 10. The End.


Example: While loop incrementing by more than 1 in Python


	counter = 1
	max = 20
	while counter <= max:
	   print ("Counter =", counter)
	   counter += 4
	

Output:

  Counter = 1
  Counter = 5
  Counter = 9
  Counter = 13
  Counter = 17


Example: While loop with decrement in Python


	x = 5
	while x >= 0:
		print(x)
		x-=1
	

Output:

  5
  4
  3
  2
  1
  0


Example: While loop in a User-defined function

Loops can also be placed into a user-defined function.


	def counterLoop(x):
		while x >= 0:
			print(x)
			x-=1

	x = 5
	counterLoop(x)
	

Output:

  5
  4
  3
  2
  1
  0

Open in new window


Example: While Loop in Main that Call a Function x times


	def counterLoop(x):
		total = x * 10
		print("Total: ", total)

	# Main Program
	i = 1
	x = int(input("Please enter a number: "))
	while i <= x:
		counterLoop(i)
		i+=1
	

Output:

  Please enter a number: 3
  Total: 10
  Total: 20
  Total: 30


Example: While loop in Python - Incrementor vs. accumulator


	i=0
	total=0
	while i < 5:
		i = i + 1
		total = total + i
		print("Count: ", i, "Total: ", total)
	

Output:

  Count: 1 Total: 1
  Count: 2 Total: 3
  Count: 3 Total: 6
  Count: 4 Total: 10
  Count: 5 Total: 15


Example: Nested loops and If statement in Python


	i = 1
	max = 3
	while (i <= max):
	   i = i +1
	   print (i,"squared =", i*i)
	   for x in range(2,3):
		  result = x/i
		  print (x, "/", i, "= %.2f" % result)
		  if (result < 1):
			 print ("Result is less than 1.")
		  else:
			 print ("Result is greater than or equal to 1.")
	

Output:

  2 squared = 4
  2 / 2 = 1.00
  Result is greater than or equal to 1.
  3 squared = 9
  2 / 3 = 0.67
  Result is less than 1.
  4 squared = 16
  2 / 4 = 0.50
  Result is less than 1.


Example: While loop with sentinal value in Python

A sentinel value is a special value that signals when a loop should end. Therefore, this value should be a value that could not otherwise be valid input .


	while True:
	   weight = float(input("How much do you weight (-1 to quit)? "))
	   if weight == -1:
		   break
	   height = float(input("How tall are you in inches? "))
	   bmi = 703 * (weight / (height * height))
	   print ("Your BMI is: %.2f" % bmi)
	

Output:

  How much do you weight (-1 to quit)? 155
  How tall are you in inches? 70
  Your BMI is: 22.24
  How much do you weight (-1 to quit)? 180
  How tall are you in inches? 72
  Your BMI is: 24.41
  How much do you weight (-1 to quit)? -1

Example: Nested loops and If statement in Python


	i = 1
	max = 3
	while (i <= max):
	   i = i +1
	   print (i,"squared =", i*i)
	   for x in range(2,3):
		  result = x/i
		  print (x, "/", i, "= %.2f" % result)
		  if (result < 1):
			 print ("Result is less than 1.")
		  else:
			 print ("Result is greater than or equal to 1.")
	

Output:

  2 squared = 4
  2 / 2 = 1.00
  Result is greater than or equal to 1.
  3 squared = 9
  2 / 3 = 0.67
  Result is less than 1.
  4 squared = 16
  2 / 4 = 0.50
  Result is less than 1.


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")