qr code

Python loops

Python loops

There are two different structures for iterations in Python, while statements and for statements.

while statements

Using a while statement, you repeat code as long as some condition is true.

while <condition>:
	#indented code that is repeated

In the repeated code, the value of the condition must change at some point in time, otherwise you get an infinite loop.

Example 1

The code prints all multiples of 15 that are less than 100.

a = 0
while a < 100:
    print(a)
    a = a + 15

Try to make a comment of the last row so you get an infinite loop. Run the program and click on stop to stop the execution.

Change the code so all multiples of 3 that are less than 50 are printed.

for statements

If you know how many times you want to repeat some code, you can use a for statement and the built-in function range(). The function range() creates an integer sequence that can be specified in various ways. If start, stop and step are integers, the function range() can be used in following ways:

  • range(stop), the sequence is all integers ≥ 0 and < stop
  • range(start, stop), the sequence is all integers ≥ start and < stopp
  • range(start, stop, step), the sequence starts with the number start and is increased by step as long as the number is < stop

To write a for statement you use some variable and following structure

for <variable> in <set_of_values>:
	#indented code that is repeated

where the set of values can be created by the function range().

Example 2

Try the code:

for i in range(10):
	print(i)

Change the sequence to the one created by range(4, 10).

Change the sequence to the one created by range(4, 10, 2).

Format tables

Since Python is often used for text-based programming, you can format text to display tables. We will show an example of integers and their squares.

Using the code

print("number  square")
print("---------------")
for number in range(-2, 3):
  print(f"{number}      {number**2}")

following table is printed

number  square
---------------
-2      4
-1      1
0      0
1      1
2      4

As you can see, the numbers in the second column are not beneath one another. If we had used range(-10, 11), the table would have been even uglier.

We can format strings so variable values are right aligned at some position. The position is written after colon, after the variable name inside the curly brackets.

The code

print("number  square")
print("---------------")
for number in range(-2, 3):
  print(f"{number:5} {number**2:8}")

prints following table

number  square
---------------
   -2        4
   -1        1
    0        0
    1        1
    2        4

Now all numbers are right aligned.

If we want to right align variable values, and show two decimals, we can write .2f after the position.

Using the code

print("number  square")
print("---------------")
for number in range(-2, 3):
  print(f"{number:5.2f} {number**2:8.2f}")

the table looks like this

number  square
---------------
-2.00     4.00
-1.00     1.00
 0.00     0.00
 1.00     1.00
 2.00     4.00

Tables like this, that can be created by Python in school, can also easily be created using spreadsheets, or by both using Python and spreadsheets.

Sums

If you want to find the sum of the numbers \(0, 1, 2, 3, 4, 5\), you can start by making a variable the_sum that has the value \(0\). Then you can add one number at the time in an iteration.

Using a while statement, following code works:

the_sum = 0;
number = 0;
while number < 6:
  the_sum = the_sum + number;
  number = number + 1;
print(the_sum)

Using a for statement, following code works:

the_sum = 0;
for number in range(6):
  the_sum = the_sum + number;
print(the_sum)

Since it's very common to increase a variable value by some number, there is a special assignment operator for doing so. There are assignment operators for all the arithmetic operators.

Assignment operators in Python
operator example code the same as
+= a += 1 a = a + 1
-= a -= 1 a = a - 1
*= a *= 2 a = a * 2
/= a /= 2 a = a / 2
%= a %= 2 a = a % 2
//= a //= 2 a = a // 1

If we want to add a number to the_sum, we can do it like this:

the_sum += number

Exercises

Exercise 1

Some for statements

Make a for statement that prints one number per row of following numbers:

  1. All non-negative integers less than or equal to \(10\).
  2. All integers greater than or equal to \(25\) and less than or equal to \(32\).
  3. The numbers \(-7, -5, -3, -1, 1, 3 \).

Exercise 2

Some while statements

Make a for statement that prints one number per row of following numbers:

  1. All non-negative integers less than or equal to \(10\).
  2. All integers greater than or equal to \(25\) and less than or equal to \(32\).
  3. The squares \(0, 1, 4, 9, 16, 25 \).

Exercise 3

Right-angled triangle of asterisks

The command print("*"*5) prints five asterisks.

Make a program that lets the user choose a number of asterisks. Then print a right-angled triangle of asterisks.

Running the program may look like this:

Number of asterisks: 4
*
**
***
****

Exercise 4

Isosceles triangle of asterisks

Make a program that lets the user choose an odd number of asterisks. Then print an isosceles triangle of asterisks. Each row should have an odd number of asterisks.

Running the program may look like this:

Number of asterisks: 7
    *
   ***
  *****
 *******

Make an integer variable for the number of blanks starting each row. What value should this variable have for each row?

Exercise 5

Print decimal digits

Make a program that lets the user enter a positive integer. The program should then print the digits of the integer, one digit per row, in reverse order.

Running the program may look like this:

Write a positive integer: 567
7
6
5

Exercise 6

Binary digits

There is a built-in function bin(<number>) that converts a number to a binary number and returns a string representing the binary number. The string has the prefix 0b.

  1. Make a program that lets the user enter a positive number and then shows the binary representation of the number (using the built-in function).
  2. Make a while statement that prints the binary digits of the number, one digit per row, in reverse order.

Running the program may look like this:

Write a positive integer: 28
The binary representation of the number is: 0b11100
0
0
1
1
1

Exercise 7

Arithmetic progression

In an arithmetic progression, the difference of any two successive numbers is constant.

  1. Make a program that prints the first \(n\) numbers of the arithmetic progression

    \[5, 8, 11, 14, \ldots\]

    You can print one number per row.

    Let the user enter the value of \(n\), then print the numbers. Try out the code for small positive values of \(n\).

  2. Add code that calculates the sum of the arithmetic progression. First print the numbers, then the sum.

Exercise 8

Geometric progression

In a geometric progression, the quotient when a number is divided by its preceding number is constant, for all numbers after the first number.

  1. Write a program that prints the \(n\) first numbers (as floating point numbers) in the geometric progression

    \[1, \frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \ldots\]

    Let the user enter the value of \(n\), then print the numbers. Try out the code for small positive values of \(n\).

  2. Change the code so the sum of the geometric progression is calculated. Print the sum instead of the numbers. Which is the smallest value of \(n\) that results in the sum 2.0?

geometric progression

Exercise 9

Table of squares

Make a program that lets the user enter a positive integer \(n\). Print a table of all non-negative numbers less than or equal to \(n\), a table that also displays the square of each number in a second column.

Running the program may look like this:

The largest integer: 4
----------------
  number square
----------------
    0      0
    1      1
    2      4
    3      9
    4     16

Exercise 10

Find the mean value

Make a program that calculates the mean value of \(n\) numbers that are given as input from the user. Start by asking for the total number of numbers.

Running the program may look like this:

How many numbers? 5
Write number 1: 0
Write number 2: 3
Write number 3: 4.5
Write number 4: 4.5
Write number 5: 7
The mean value is 3.8.

Exercise 11

Loan with interest

Make a program that lets the user enter the amount of the loan, and the annual interest rate. Then show how the loan increases during a period of ten years, using a table. Show the loan using two decimals.

Running the program may look like this:

The amount of the loan: 5000
Annual interest rate (per cent): 5
----------------
 year   loan
----------------
  0    5000.00 
  1    5250.00 
  2    5512.50 
  3    5788.12 
  4    6077.53 
  5    6381.41 
  6    6700.48 
  7    7035.50 
  8    7387.28 
  9    7756.64 

Exercise 12

Annuity loan

Make a program that lets the user enter following data:

  • the amount of the loan,
  • the annual interest rate,
  • annual mortgage (how much to pay back per year).

When finding the loan per year, you can use the built-in function max() that takes any number of arguments and returns the maximum argument. By taking the maximum of the loan and the number zero, you can see to it that the loan never gets negative.

Running the program may look like this:

The amount of the loan: 5000
Annual interest rate (per cent): 5
Annual mortgage: 900
----------------
 year   loan
----------------
  0    5000.00 
  1    4350.00 
  2    3667.50 
  3    2950.88 
  4    2198.42 
  5    1408.34 
  6     578.76 
  7       0.00 
  8       0.00 
  9       0.00 

Exercise 13

Prime number?

Make a program that lets the user enter the value of a positive integer \(n\). Find out if \(n\) is a prime number or not, then print the result.

One easy way to do it is to check if \(n\) is divisible by any of the integers smaller than \(n\) but larger than one, if not, \(n\) is a prime number. It suffices to check all integers larger than one but less than or equal to \(\sqrt n\). If the number \(37\) isn't divisible by any of the integers less than \(\sqrt{37} \), it cannot be divisible by a number larger than \(\sqrt{37}\).

You can use a Boolean variable is_prime that is assigned the value True when the program starts. If you find a divisor you assign is_prime the value False.

Exercise 14

Project Euler

At the web site Project Euler you can solve problems that require mathematical reasoning as well as computational thinking.

You can make an account and solve the problems one by one. For each problem you must make a program to find the correct answer. After providing the correct answer to a problem, you can participate in (or just read) an online discussion about the problem and its solution.

You can also start solving problems without making an account.

Solve Project Euler: Problem 1.