Table of Contents

We are going to be looking at the While loop in python.

The while loop in python is a control flow statement that repeatedly executes a block of code as long as a specified condition is true.

 

Example 1 Basic While Loop

Here, we are using the while loop to print numberd from 1 to 9.

It keeps increasing x by 1 until it reaches 10.

				
					x = 1
while x < 10:
  print(x)
  x = x + 1
				
			

Example 2 Basic While Loop

This loop prints the current number (x) and running sum in each iteration.

It adds the next x to sum after printing, repeating until x is 10.

				
					x = 1
sum = 0
while x < 10:
  print('number: ' + str(x) + ', sum: ' + str(sum))
  x = x + 1
  sum +=x

				
			

Example 1 - if else state location

This line of code creates an infinite loop because i starts at 2 and keeps increasing, so the condition i > 1 is always true.

				
					i = 2

while i > 1:
  print('infinite')
  i = i + 1
				
			

Example 4 break and Continue

This while loop prints numbers from 1 to 4. When x reaches 5, the break statement exits the loop early.

				
					x = 1

while x < 10:
  if x == 5:
    break
  print(x)
  x = x + 1
				
			

This loop prints numbers from 1 to 9, but skips  5. when x is 5, “continue” skips the print() and goes to the next iteration

				
					x = 1

while x < 10:
  if x == 5:
    x = x + 1
    continue
  print(x)
  x = x + 1
				
			

Example 5 While Loops with inputs

Here, we keep asking the user for a number, square it, and print the result. It stop when the user enters ‘z’. Inputs are cast to integers before squaring.

				
					while True:
      x = input("Enter Number ")
      if x == 'z':
        break
      print (int(x) * int(x)) #need to cast as int
				
			

Example 5b variant While Loops with inputs

Here, we ask the user for a positive number less than 20. If the input is invalid, it keeps prompting until valid.

Then it prints the square of the number.

				
					x = input("Enter positive Number less than 20 ")

while int(x) < 0 or int(x) > 20:
  print("Wrong Number")
  x = input("Enter positive Number less than 20 ")

print (int(x) * int(x)) #need to cast as int
				
			

Example 6 lists

Here we loop through the list and add each positive number to sum, stopping if it reaches the end or encounters a non-positive number.

It prints the runnung total after each addition.

				
					list = [1, 3, 7, 11, 6, 8, 10]

sum = 0
x = 0
while x < len(list) and list[x] > 0:
  sum += list[x]
  x +=1
  print(sum)
				
			

Example 6b lists

This code iterates through the list, and for each element at a positive index, it adds the value to even_sum if thr index is even, or to odd_sum if the index is odd.

				
					list = [1, 3, 7, 11, 6, 8, 10]

even_sum = 0
odd_sum = 0
x = 0
while x < len(list) and list[x] > 0:
  if x % 2 == 0:
    even_sum += list[x]
  else:
    odd_sum += list[x]
  x +=1

				
			
				
					even_sum
				
			
				
					odd_sum
				
			

Example 7 multiple

Here we use a nested loop to print a multiplication table for numbers 2 through 8, each multiplied by 1 through 3.

				
					# Initialize variables
x = 2

# Outer while loop
while x <= 8:
    y = 1

    # Inner while loop
    while y <= 3:
        # Perform calculation using both x and y
        result = x * y

        # Print the result
        print(f"{x} * {y} = {result}")

        # Increment y
        y += 1

    # Increment x
    x += 1
				
			

Free Community

Join 1,000+ AI Automation Builders

Weekly tutorials, live calls & direct access to Ryan & Matt.

Join Free →

Keep Learning

Streamlit Async

Streamlit runs Python scripts top-to-bottom when ever a user interacts with widget.Streamlit is synchronous by default, meaning each function waits for the...

Streamlit Caching

Streamlit runs your script from top to bottom whenever you interact with the app.This execution model makes development super easy. But it...

Streamlit Tutorial

Streamlit can help businesses automate a ton of tasks in a short amount of time. It essentially is a quick UI you...

Gradient boosting classifier

Gradient Boosting is an ensemble technique that builds a strong model by combining multiple weak decision trees. While it may seem similar...