Python · Variables and types
Numbers
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — Numeric Variables - Numbers
Variables can hold different types of data. In this lesson, we will focus on the easiest ones: numbers!
Python has two main types of numeric variables: - integers (int) : Whole numbers like 1, 0, 42, -42, -3 - floating point numbers (float) : Decimal numbers like 3.14, -0.001, 2.71828 Here is how to create them:
level = 1 print(level) weight = 3.5 print(weight)
Those two types have different cases of application (but both are needed). Integers are used for whole numbers, like counting levels or lives, while floating point numbers are used for values that require precision, like weight or speed.
Exercise 2 — Int or Float ?
Match each number of the left with its type on the right (int or float)
Items to match
• 4.000
• 4
• 4.2
• 0
Definitions
• float
• int
• float
• int
Exercise 3 — Mathematical Operations
Python supports all basic math operations between: - Addition :
+
- Subtraction :
-
- Multiplication :
*
- Division :
/
(always returns a float) - Integer division :
//
(always returns an int) - Power :
**
- Modulo :
%
(remainder of a division)
Here are some more explanations for the younger ones on this app :)
Integer division : //
Divides the number and returns the whole part of the result. For example,
5 // 2
, the result is supposed to be
2.5
but we make the part after the comma disappear. So we round down to
2
.
Modulo (Remainder) : %
Gives the remainder of a division. For example,
5 % 2
. We can fit
2
into
5
two times, because
2 * 2 = 4
. The remainder is
1
because
5 - 4 = 1
. Result of
5 % 2
is
1
.
Power : **
Raises a number to the power of another. For example,
2 ** 2
means
2
raised to the power of
2
, which is
2 * 2 = 4
. So the result is
4
.
2 ** 3
means
2
raised to the power of
3
, which is
2 * 2 * 2 = 8
. So the result is
8
.
Exercise 4 — Practice with numbers!
Match each calculation of the left with its result on the right.
Items to match
• 9/2
• 9//2
• 9%2
• 9**2
Definitions
• 4.5
• 4
• 1
• 81
Exercise 5 — More practice with numbers!
Chose the right symbol to use in the following calculations.
18 ____ 2 = 20 18 ____ 2 = 9 18 ____ 2 = 0 18 ____ 2 = 16
Options: + / % // * - **
Hint : Remember: - ```/``` is division (always return a float) - ```//``` is integer division (always returns an int) - ```%``` is modulo (always returns an int) - ```**``` is power.
Exercise 6 — Create numeric variables
Create 2 variables: - an integer variable named
age
with your age as value - a floating point variable named
height
with your height (in meters) as value Then, print both variables.
Starter code
# Code here
Back to the course