While loops
As we progress in our coding journey, we arrive at the need of repetition. Suppose that we wanted to print the string "Hello, world!" four times to the screen, we could easily do it as follows:
print("Hello, world!")print("Hello, world!")print("Hello, world!")print("Hello, world!")Now what if we wanted to print it ten times, a hundred times, or maybe the number of times is given by the user, we can’t simply hard code it, this is a great place to introduce loops. Loops are a fundamental part of any programming language, whether it has a designated keyword while or not, loops help us in repeating a certain block of code, until a condition stops being fulfilled. In python the syntax for a while loop is:
while condition: #loop body hereThe condition is checked, as long as it is True, the body will be executed. Here’s example of a while loop in action:
i = 0while i < 5: print(i, end=" ") i = i + 1Here we have multiple important parts to keep in mind, first the condition is i < 5, which is True for some values of i, we need to make it False at some point so that the loop could terminate, to do so we will increment it by 1 after each loop iteration. The output of the following code is: 0 1 2 3 4. Now let’s say that we want to print "Hello" n times, where n is given by the user:
n = int(input("Please enter a number: "))i = 0
while i < n: print("Hello") i = i + 1Note
Loop iteration means one pass in the loop, i.e. go from over the loop’s body one time. If
nis5then we will have5iterations. The variable that we use inside the loop’s condition and inside the loop’s body is sometimes namedi, which stands for iteration.
Flags
When talking about loops, we must talk about flags. A flag is a simple variable, often being a boolean, in which it acts as an indicator or signal to represent a condition or state in the program. Think of it as a literal flag, when some condition is met, we might raise it up or down. It could be used to:
- Signify that something has happened.
- Signify that we need to stop looping.
Flags are an essential concept for any developer to know. A great example would be to write a program which keeps asking the user to provide a positive integer, until the user provides a negative one, and when that happens, we exit the loop, and print the sum of the positive numbers entered.
running = Truetotal = 0while running: num = int(input("Please enter a positive number: ")) if num < 0: # <-- The user has entered a negative number running = False # so we change the state to exit else: total += numprint("The sum of the positive numbers is:", total)Another example would be to check if a number is prime, to do so, we may suppose that it is prime, then we check all the numbers from 2 upto that number and if there is any divisor, we flip the state to not prime.
n = int(input("Please enter a number to check for prime: "))is_prime = True
if n > 1: i = 2 while is_prime and i < n: if n % i == 0: is_prime = False i += 1
if is_prime: print(n, "is prime") else: print(n, "is not prime")else: # anything less than 2 is not a prime print(n, "is not a prime number");If the above code is too messy, maybe we could just remove the check for positive input, and assume the user enters a positive number:
n = int(input("Please enter a number to check for prime: "))is_prime = Truei = 2while is_prime and i < n: if n % i == 0: is_prime = False i += 1
# Now we check our flagif is_prime: print(n, "is prime")else: print(n, "is not prime")It doesn’t have to be purely about loops, we could use it with if statements too:
has_permission = False
username = input("Please enter your username")password = input("Please enter your password")
if username == "admin" and password == "some_secret_password": has_permission = True
if has_permission: print("You have permission to execute this action")else: print("You do not have permission to do this action")Infinite loops
A loop that runs forever, or at least without a bound/condition is said to be an infinite loop. Sometimes we want infinite loops, but most of the times, they are just made by mistake as a bug.
Funny
Bug means a flaw or a glitch in some system. The first ever bug in computers was discovered in 1947, where a moth was discovered to be stuck in the relays of the Mark II computer at Harvard, being the first ever recorded incident of a bug taking place. This incident gave the literal twist and helped popularize it in computing.
An example of an infinite loop would be:
while True: print("Hello")This code will print the string "Hello" to the screen forever (or until your PC turns off). This isn’t something entirely useful. Practically, we use it to keep checking until some condition or event has occurred. Let’s say that we want to copy files to the USB, but wait the user didn’t plug-in the usb, so we keep checking until this even happen, and so we can copy the files:
while check_for_usb(): wait_some_time() # Wait so that we don't exhuast the system by always checking copy_files()There are more practical examples, like a web server, which waits for web requests to take place, then process them, and repeats this cycle.
while True: check_for_requests() process_pending_tasks()Or maybe a game. In a game we check if there is any user input, update the game (if necessary), and finally redraw the screen.
while True: #if the mouse moves, or a keypress/release takes place handle_input() update_game_state() redraw_game_canvas()Nested loops
As we have seen, loops help us repeat code blocks, but what if we want to repeat a repeated code! Meet nested loops. A nested loop is essentially a loop inside a loop, in other words, while the outer loop runs, the inner loop executes, and once the inner code completely finishes execution (the inner loop completed along with anything else), we count it as one full iteration for the outer loop. We might visualize it as follows:
Outer Loop -> starts its first iteration | -> Inner Loop -> runs fullyOuter Loop → starts its second iteration | -> Inner Loop -> runs fully againA basic example would be:
i = 1while i <= 2: j = 1 while j <= 3: print("i =", i, "j =", j) j += 1 i += 1Execution steps:
iis set to1i <= 2-> Outer loop starts with its first iterationjis set to1
j <= 3-> Inner loop starts with its first iteration
- print
i = 1 j = 1
- print
jbecomes2
j <= 3-> Inner loop starts with its second iteration
- print
i = 1 j = 2
- print
jbecomes3
j <= 3-> Inner loop starts with its third iteration
- print
i = 1 j = 3
- print
jbecomes4
j <= 3isFalseso the inner loop finishes
ibecomes2i <= 2-> Outer loop starts with its second iterationjis set to1
j <= 3-> Inner loop starts with its first iteration
- print
i = 2 j = 1
- print
jbecomes2
j <= 3-> Inner loop starts with its second iteration
- print
i = 2 j = 2
- print
jbecomes3
j <= 3-> Inner loop starts with its third iteration
- print
i = 2 j = 3
- print
jbecomes4
j <= 3isFalseso the inner loop finishes
ibecomes2i < 2isFalseso the outer loop finishes
Wow, that was too much right? Let’s print out the following pattern:
************But with a catch, the width (number of starts on each row), and height (number of stars on each column) is given by the user:
width = int(input("What is the width of your pattern? "))height = int(input("What is the height of your pattern? "))
i = 0while i < height: j = 0 while j < width: print("*", end="") j += 1 print() i += 1Note
The order of the loops (height before width) matters, as it generates a different grid formation.
We have seen in the previous section how to check if a number is prime or not, what if we wanted to print all the numbers inside the range [2,1000], how can we do that? We could use the code previous made as our starting point:
- First we loop over the range from
2to1000 - For each number, we label it as prime
- Instead of reading the number from the user, we use this loop’s iterator
n = 2 # <-- keeping it as `n` to make the two code snippets more similarwhile n < 1000: # add the code that was previously used to check if a number is prime or not # remove the input as we wont be reading from the user n = n + 1Doing all of that would yield:
n = 2 # <-- keeping it as `n` to make the two code snippets more similarwhile n < 1000: # Primality test is_prime = True i = 2 while is_prime and i < n: if n % i == 0: is_prime = False i += 1
# Now we check our flag if is_prime: print(n, "is prime") else: print(n, "is not prime")
n = n + 1Exercises
Below are exercises to practice while loops. Try solving them on your own before checking the solutions.
Exercise 1: Print numbers from 1 to 100
Write a program that prints all numbers from 1 to 100, each on a new line.
Print Numbers 1-100
i = 1while i <= 100: print(i) i += 1Exercise 2: Sum all even integers from 1 to 100
Write a program that calculates and prints the sum of all even integers from 1 to 100.
Sum Even Numbers 1-100
total = 0i = 1while i <= 100: if i % 2 == 0: total += i i += 1print(total)Exercise 3: Keep reading until negative number
Write a program that keeps reading positive integers from the user until they enter a negative number. When a negative number is entered, print the sum of all positive numbers entered.
Sum Until Negative
total = 0isPositive = Truewhile isPositive: num = int(input()) if num >= 0: total += num else: isPositive = Falseprint(total)Exercise 4: Factorial of a number
Write a program that reads a positive integer n and calculates and prints its factorial. Factorial of n (denoted as n!) is the product of all positive integers from 1 to n.
Example:
Factorial
n = int(input())factorial = 1i = 1while i <= n: factorial *= i i += 1print(factorial)Exercise 5: Power function pow(x, y)
Write a program that reads two positive integers x and y and calculates x raised to the power of y (x^y) without using the ** operator or pow() function.
Example: If x = 2 and y = 3, output should be 8.
Power Function
x = int(input())y = int(input())result = 1i = 1while i <= y: result *= x i += 1print(result)Note: This solution assumes y >= 0. For y = 0, the result is 1 by definition.
Exercise 6: Find largest number from user input
Write a program that keeps reading positive integers from the user until they enter 0. When 0 is entered, print the largest number among all entered numbers.
Find Largest Number
num = int(input())largest = numwhile num != 0: if num > largest: largest = num num = int(input())print(largest)Exercise 7: Print multiplication table
Write a program that reads a positive integer n from the user and prints the multiplication table for n from 1 to 10.
Example: If n = 5, the output should be:
5 x 1 = 55 x 2 = 105 x 3 = 15...5 x 10 = 50Multiplication Table
n = int(input())i = 1while i <= 10: print(n, 'x', i, '=', n * i) i += 1Exercise 8: Generate triangle pattern
Write a program that reads a positive integer n from the user and prints a triangle pattern with n rows. Each row should have a number of asterisks equal to its row number.
Example: If n = 4, the output should be:
**********Triangle Pattern
n = int(input())i = 1while i <= n: j = 1 while j <= i: print('*', end='') j += 1 print() i += 1Exercise 9: Find GCD (Greatest Common Divisor)
Write a program that reads two positive integers a and b and calculates their Greatest Common Divisor (GCD) using the Euclidean algorithm.
Example: GCD of 48 and 18 is 6.
GCD Calculator
a = int(input())b = int(input())while b != 0: temp = b b = a % b a = tempprint(a)This uses the Euclidean algorithm: repeatedly replace the larger number with the remainder of dividing it by the smaller number, until the remainder is 0. The GCD is the last non-zero remainder.
Exercise 10: Perfect number
Write a program that reads a positive integer n and checks if it is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself).
Example: 6 is perfect because 6 = 1 + 2 + 3.
If the number is perfect, print "Perfect", otherwise print "Not Perfect".
Perfect Number
n = int(input())sum_divisors = 0i = 1while i < n: if n % i == 0: sum_divisors += i i += 1if sum_divisors == n: print('Perfect')else: print('Not Perfect')Exercise 11: Count the digits in a number
Write a program that reads a positive integer and counts the number of digits in it.
Count Digits
num = int(input())count = 0if num != 0: while num > 0: count += 1 num //= 10else: count = 1print(count)Exercise 12: Reverse a number
Write a program that reads a positive integer and prints its reverse.
Example: If input is 1234, output should be 4321.
Reverse Number
num = int(input())reversed_num = 0while num > 0: digit = num % 10 reversed_num = reversed_num * 10 + digit num //= 10print(reversed_num)Exercise 13: Armstrong number (3 digits)
Write a program that reads a 3-digit positive integer and checks if it is an Armstrong number. An Armstrong number (for 3 digits) is one where the sum of the cubes of its digits equals the number itself.
Example: 153 is an Armstrong number because .
If the number is Armstrong, print "Armstrong", otherwise print "Not Armstrong".
Armstrong Number
num = int(input())original = numsum_cubes = 0while num > 0: digit = num % 10 sum_cubes += digit * digit * digit num //= 10if sum_cubes == original: print('Armstrong')else: print('Not Armstrong')