🐍 Python Course 4: Arithmetic Operations

🎯 Learning Objectives

After completing this section, you will be able to:

📚 Table of Contents

1. Arithmetic Operations

We have already used some basic arithmetic operators in the previous exercises. Let's have a systematic look at all the available operators.

The following table contains the most common arithmetic operators, along with examples:

📊 Arithmetic Operators

Operator Purpose Example Result
+ Addition 2 + 4 6
- Subtraction 10 - 2.5 7.5
* Multiplication -2 * 123 -246
/ Division (float) 9 / 2 4.5
// Division (integer) 9 // 2 4
% Modulo 9 % 2 1
** Exponentiation 2 ** 3 8

Example Program

mean = (2 + 5 + 3) / 3 print(f"Mean: {mean}") # the ** operator raises to a power # the following calculates 2 to the power of 8 print(f"2 to the power of 8 is {2**8}")
Sample output: Mean: 3.3333333333333335 2 to the power of 8 is 256

2. Operands, Operators and Data Types

A calculation usually consists of operands and operators:

Operands and operators diagram showing 2 + 3 * 3 with labels
Operands and operators in a calculation

The data type of an operand usually determines the data type of the result: if two integers are added together, the result will also be an integer. If a floating point number is subtracted from another floating point number, the result will also be a floating point number.

In fact, if a single one of the operands in an expression is a floating point number, the result will also be a floating point number, regardless of the other operands.

height = 172.5 weight = 68.55 # the Body Mass Index, or BMI, is calculated by dividing body mass by height squared bmi = weight / height ** 2 print(f"The BMI is {bmi}")
Sample output: The BMI is 0.002305194638304155

Notice Python also has an integer division operator //. If the operands are integers, it will produce an integer result. The result is rounded down to the nearest integer:

x = 3 y = 2 print(f"/ operator {x/y}") print(f"// operator {x//y}")
Sample output: / operator 1.5 // operator 1

3. The Order of Operations

The order of operations is familiar from mathematics: first calculate the exponents, then multiplication and division, and finally addition and subtraction. The order can be changed with parentheses.

print(2 + 3 * 3) print((2 + 3) * 3)
Sample output: 11 15

With operators on the same level of precedence, the parentheses determine which operation is performed first:

Order of operations diagram
Parentheses determine operation order

4. Numbers as Input

Strings and integers are processed quite differently in Python programs. The following two programs should clarify this difference:

Program 1:

number1 = 100 number2 = "100" print(number1) print(number2)
Sample output: 100 100

Program 2:

number1 = 100 number2 = "100" print(number1 + number1) print(number2 + number2)
Sample output: 200 100100

So, when two numbers are added together, we get the sum. When two strings are "added" together, we get a new string with the two original strings concatenated together.

Strings and integers are not directly compatible with each other. For example, trying to execute the following would cause an error:

number1 = 100 number2 = "100" print(number1 + number2)
Error: TypeError: unsupported operand type(s) for +: 'int' and 'str'

Converting Data Types

If you try to make the following calculation:

result = "1" + "2" print(result)

Python would interpret it as string concatenation, and the result would thus be 12. If you actually want to perform addition on two numbers, and the operands are strings, they will have to be converted to integers with the int function:

result_str = "1" + "2" print(result_str) result_int = int("1") + int("2") print(result_int)
Sample output: 12 3

Similarly, strings can be converted into floating point numbers with the float function:

result = float("1.25") + float("2.75") print(result)
Sample output: 4.0

5. Using Variables

Let's have a look at a program which calculates the sum of three numbers given by the user:

number1 = int(input("First number: ")) number2 = int(input("Second number: ")) number3 = int(input("Third number: ")) sum = number1 + number2 + number3 print(f"The sum of the numbers: {sum}")
Sample output: First number: 5 Second number: 21 Third number: 7 The sum of the numbers: 33

The program uses four different variables, but two would easily suffice in this case:

sum = 0 number = int(input("First number: ")) sum = sum + number number = int(input("Second number: ")) sum = sum + number number = int(input("Third number: ")) sum = sum + number print(f"The sum of the numbers: {sum}")

All inputs from the user are read into the one and the same variable number. The value of the variable sum is increased by the value of the variable number each time the user inputs a new number.

Let's take a closer look at this command:

sum = sum + number

Here, the value of the variable sum and the value of the variable number are added together, and the result is stored back in the variable sum. For example, if before the command the value of sum is 3 and the value of number is 2, after the command is executed, the value of sum is 5.

Increasing the value of a variable is a very common operation. As such, there is a commonly used shorthand notation which achieves the same result as the explicit summing up above:

sum += number

This allows us to write the above program a little more concisely:

sum = 0 number = int(input("First number: ")) sum += number number = int(input("Second number: ")) sum += number number = int(input("Third number: ")) sum += number print(f"The sum of the numbers: {sum}")

In fact, we don't necessarily need the variable number at all. The inputs from the user can also be processed like this:

sum = 0 sum += int(input("First number: ")) sum += int(input("Second number: ")) sum += int(input("Third number: ")) print(f"The sum of the numbers: {sum}")

Of course, it will depend on the context how many variables are needed. If it is required to remember each value the user inputs, it will not be possible to "reuse" the same variable to read different values from the user. Consider the following:

number1 = int(input("First number: ")) number2 = int(input("Second number: ")) print(f"{number1} + {number2} = {number1 + number2}")

On the other hand, the above program does not have a named variable for storing the sum of the two values.

"Reusing" a variable only makes sense when there is a need to temporarily store things of a similar type and purpose, for example when summing numbers.

In the following example the variable data is used to first store the name of the user, and then their age. This is not at all sensible.

data = input("What is your name? ") print("Hi " + data + "!") data = int(input("What is your age? ")) # program continues...

A better idea is to use separate variables, with descriptive names:

name = input("What is your name? ") print("Hi " + name + "!") age = int(input("What is your age? ")) # program continues...

6. Programming Exercises

Complete the following exercises to practice arithmetic operations in Python!

📝 Exercise 1: Times Five (1 point)

Please write a program which asks the user for a number. The program then prints out the number multiplied by five.

Please type in a number: 3 3 times 5 is 15
# Write your code here
📝 Exercise 2: Name and Age (1 point)

Please write a program which asks for the user's name and year of birth, and prints out a message as follows:

What is your name? Frances Fictitious Which year were you born? 1990 Hi Frances Fictitious, you will be 34 years old at the end of the year 2024
# Write your code here
📝 Exercise 3: Greater Than or Equal To (1 point)

Please write a program which asks for two integer numbers. The program should print which one is greater. If they are equal, it should print a different message.

Please type in the first number: 5 Please type in another number: 3 The greater number was: 5 Please type in the first number: 5 Please type in another number: 8 The greater number was: 8 Please type in the first number: 5 Please type in another number: 5 The numbers are equal!
# Write your code here
📝 Exercise 4: Carnivore (1 point)

Please write a program which asks for the user's name and address. The program should also print out the given information, as follows:

First name: Paul Last name: Python Street address: Programmer street 10 City and postal code: Helsingborg 12345 Paul Python Programmer street 10 Helsingborg 12345
# Write your code here
📝 Exercise 5: Fix the Syntax (1 point)

The following program should work, but it contains errors. Please fix the program so that it works as intended.

# Fix this code number = input("Please type in a number: ") print("The number squared is" number * number)
Please type in a number: 5 The number squared is 25
📝 Exercise 6: Print a Box (1 point)

Please write a program which prints out a box:

***** * * * * *****
# Write your code here
📝 Exercise 7: Square Root (1 point)

Please write a program which asks the user for a number and calculates its square root. You will need the function sqrt from the math module.

Please type in a number: 9 The square root of 9 is 3.0
# Write your code here
📝 Exercise 8: Sum and Mean (1 point)

Please write a program which asks the user for four numbers. The program should then print out the sum and mean of the numbers.

Number 1: 2 Number 2: 1 Number 3: 6 Number 4: 7 The sum of the numbers is 16 and the mean is 4.0
# Write your code here

🎉 Summary

You've completed Arithmetic Operations! You now know how to:

Total points: 8/8