2. Basic Concepts & Interpreter#
This section introduces you to using Python as a calculator through its interactive interpreter.
2.1. What is the Python Interpreter?#
The Python interpreter is a program that reads and executes Python code line by line. It operates in an interactive mode, meaning you can enter commands, and it will immediately show the result. This makes it ideal for experimenting with small pieces of code or performing quick calculations.
When you open the Python interpreter (which you can do by simply typing python or python3 in your terminal), you are greeted with a prompt that looks like this:
>>>
This >>>
prompt indicates that the interpreter is ready to accept an instruction which will be interpreted.
2.2. Basic Arithmetic Operations#
You can use the Python interpreter just like a calculator. Below are examples of basic arithmetic operations.
Addition
>>> 2 + 3
5
Remainder of the Euclidean division.
>>> 7 % 3
1
Python respects the standard mathematical order of operations (see glossary PEMDAS, Parentheses, Exponents, Multiplication and Division, Addition and Subtraction). For instance multiplication is performed before addition.
>>> 2 + 3 * 4
14
If you want to change the order, you can use parentheses:
>>> (2 + 3) * 4
20
The basic arithmetic operators are : +
, -
, *
, /
(division), //
(euclidean division), %
(remainder of euclidean division), **
(power).
2.3. Variable Assignment#
Variable assignment in Python is a fundamental concept that allows you to store and manage data. It involves creating variables and assigning values to them, which you can then use throughout your program.
In Python, you can assign values to variables using the assignment operator (=
). The variable name is on the left side of the operator, and the value is on the right side.
>>> x = 10 # Assigns the integer value 10 to the variable x
>>> pi = 3.14 # Assigns the float value 3.14 to the variable pi
After the assignment, you can use the variables in expressions.
z = 2*pi
If you use a variable before assigning a value, your program will produce an error.
>>> z = e**2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'e' is not defined
Warning
You need to learn to read and understand error messages, even if they seem cryptic. Here, it clearly indicates that ‘e’ is not defined.
Assignment is not a mathematical equality. In other programming languages, the operator used might be a left arrow, like x <- 10
. Assignment is an operation that occurs in two steps. First, the expression on the right side of the assignment is evaluated. Then, the result is stored in the variable on the left.
Thus, the following example is perfectly valid, even though it does not have mathematical meaning.
x = 1
x = x+10
After these two lines, the variable x
is storing the value 11
.
Tip
This type of operation (x = x+10
) is quite common in programming. Python has a condensed syntax for this: x += 10
.
The +=
operator is an Augmented Mathematical Assignment Operator. There are similar operators for all basic arithmetic operations: -
, *
, /
, etc.
Multi-assignement. It is possible to assign values to multiple variables on a single line. To do this, you need to place variables separated by commas on the left side of the assignment operator. On the right side of the operator, there must be as many expressions separated by commas. This is very useful, for example, for swapping the contents of two variables.
a, b, c = 10, 254.2, 2
a, b = b, a
In this last example, we see that a variable does not have a specific type. It can successively store values of different types. Here, a
first contains an integer (10
) and then a float (254.2
) and becareful, the behaviour of integer and float are quite different…
2.4. Data types#
Python supports a variety of data types, which can be broadly divided into built-in types (see Built-in) and user-defined types (the latter will be introduced later). Understanding these data types is crucial because Python is a dynamically-typed language, meaning that the type of a value determines how it behaves in different operations. For example, Python clearly distinguishes between different data types, as illustrated by the following examples:
>>> 8 + 2
10
In this case, the result of adding two integers (int
) is also an integer. However, when performing division between two integers:
>>> 8 / 2
4.0
The result is a floating-point number (float
), even though the mathematical result is an integer. This highlights that each value in Python has a specific type. The behavior of an operation can change depending on the types involved:
>>> 8 + 2
10
>>> 8. + 2
10.0
2.4.1. Basic data types#
Let’s start by introducing three fundamental data types in Python: int
, float
, and bool
.
2.4.2. int
, float
and bool
#
The int
type represents whole numbers without a fractional component (see Integer). In Python, integers can be arbitrarily large, limited only by the memory available.
>>> x = 4876587659
The float
type represents numbers with a decimal point (see Float). Unlike integers, floating-point numbers have limited precision, which means they can represent a wide range of values but not with exact accuracy in all cases.
>>> pi = 3.14
The bool
type represents truth values (see Boolean). There are only two boolean values: True
and False
. These values often result from comparisons or logical operations.
>>> is_sunny = True
>>> is_raining = False
2.4.3. Arithmetic and Logical Operations#
Python supports a range of arithmetic operators that work with int
and float
values, such as +
(addition), -
(subtraction), *
(multiplication), /
(division), //
(euclidean division), %
(modulus), and **
(exponentiation). The type of the result depends on the types of the operands involved:
>>> 3 + 1 # int + int -> int
4
>>> 3.0 + 1 # float + int -> float
4.0
For bool
values, Python provides three logical operators: and
, or
, and not
.
and
: ReturnsTrue
if both operands areTrue
; otherwise, it returnsFalse
.or
: ReturnsTrue
if at least one operand isTrue
; otherwise, it returnsFalse
.not
: Inverts the value of the operand;not True
becomesFalse
, andnot False
becomesTrue
.
>>> True and False
False
>>> True or False
True
>>> not True
False
2.4.4. Comparison Operators#
Comparison operators in Python include ==
(equals), !=
(not equals), <
(less than), >
(greater than), <=
(less than or equal to), and >=
(greater than or equal to). These operators compare int
and float
values, returning a bool
as the result:
>>> 3 > 5
False
>>> 10 == 10.0
True
Interestingly, comparison operators can also be applied to bool
values. In Python, False
is equivalent to 0
, and True
is equivalent to 1
, which allows direct comparison between bool
and int
or float
:
>>> True == 1
True
>>> False < True
True
2.4.5. Type Conversion#
Type conversion (see glossary Casting), also known as type casting, refers to converting a value from one data type to another. Python provides built-in functions for type conversion, allowing you to change the data type of a variable or an expression when needed.
There are two types of type conversion in Python:
Implicit Type Conversion: Automatically performed by Python.
Explicit Type Conversion: Performed manually by the programmer using built-in functions.
Implicit type conversion is done automatically by Python when it encounters mixed data types in an expression. Python converts the data types to prevent data loss and to ensure compatibility within the expression.
Example:
>>> a = 10 # int
>>> b = 2.5 # float
>>> result = a + b # int is implicitly converted to float
>>> type(result)
<class 'float'>
In this example, Python automatically converts the integer a
to a float
so it can be added to the float b
, resulting in a float
.
Explicit type conversion requires the use of Python’s built-in functions to manually convert one data type into another. Common functions include:
int(): Converts a value to an integer.
float(): Converts a value to a floating-point number.
bool(): Converts a value to a boolean.
>>> int(5.7) # Convert float to int (truncates the decimal part)
5
>>> float(5)
5.0
>>> bool(1)
True
2.4.6. Determining a Type#
To determine the type of a value or an expression, Python provides the type
function, which returns the type of the given object:
>>> type(4)
<class 'int'>
>>> type(2 + 1.0)
<class 'float'>
>>> type(2 == 4)
<class 'bool'>
Understanding these basic data types and their associated operations is fundamental to programming in Python, as they form the building blocks for more complex structures and algorithms.
2.4.7. String, a more complex data type#
Strings (see glossary String) are among the most commonly used data types in Python, serving as a fundamental way to represent and manipulate text. A string is essentially a sequence of characters, which can include letters, digits, symbols, and spaces. Strings are indispensable in various programming tasks, from user input and output to data processing and manipulation. While we will introduce the basics of strings now, we will explore them in greater depth later in the course.
In Python, strings can be created by enclosing characters within either single quotes ('...'
), double quotes ("..."
), or triple quotes ('''...'''
or """..."""
). The choice between single and double quotes is largely a matter of preference, although double quotes are often used when the string contains a single quote (‘). Triple quotes are particularly useful for creating multi-line strings, which can span several lines of code.
# Single and double quotes
>>> single_quote_str = 'Hello, World!'
>>> double_quote_str = "Hello, World!"
# Triple quotes for multi-line strings
>>> multi_line_str = """This is a
multi-line string that spans
across three lines."""
It is possible to prompt the user to enter a string from the keyboard using the input
function. The program will be paused until the user has entered a string and pressed Enter. The input string may be stored in a variable and later converted into an int
or a float
.
>>> s = input()
This is my first string
>>> s
'This is my first string'
Conversion into a float
>>> i = float(input())
10.5
>>> i
10.5
Or an int
>>> i = int(input())
10
>>> i
10
For now, we need to carefuly use this conversion, as we haven’t yet covered how to handle errors (see Error). For example, the string-to-integer conversions can cause issues. Once again, the interpreter is very clear about the problem: there is a value error, it doesn’t know how to convert 10.5
into an integer.
>>> i = int(input())
10.5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.5'
Just as it is often necessary to convert strings to numerical types, the reverse conversion—turning numbers, booleans, or other data types into strings—is also possible and frequently needed in Python. This can be achieved using the str
function, which takes any object and returns its string representation. The str
function is versatile and works with virtually any Python object, making it an essential tool for displaying data or combining different types of data into a single string.
>>> str(10)
'10'
>>> str(3.14)
'3.14'
>>> str(True)
'True'
We will delve deeper into what an “object” is later in the course and how the str
function works; but it’s worth noting that in Python, everything is an object—including integers, floats, booleans, and strings themselves. The str
function provides a way to obtain a human-readable string representation of these objects.
2.4.8. The Type of an Expression in Python#
In Python, every expression (see glossary Expression) has a type, which is determined by the data and operations within the expression.
2.4.8.1. Understanding Expression Types#
An expression in Python can be as simple as a single value or as complex as a combination of values, variables, and operators. The type of an expression is determined by the types of its components and the operations applied.
Examples of simple Expressions.
>>> 10 # An integer expression
10
>>> type(10)
<class 'int'>
>>> 3.14 # A float expression
3.14
>>> type(3.14)
<class 'float'>
>>> "Hello" # A string expression
"Hello"
>>> type("Hello")
<class 'str'>
Examples of complex expressions:
>>> 10 + 5 # An arithmetic expression, result is an int
15
>>> type(10 + 5)
<class 'int'>
>>> 10 + 3.5 # Mixed-type arithmetic, result is a float
13.5
>>> type(10 + 3.5)
<class 'float'>
2.4.8.2. The None Type in Python#
The NoneType
is a special type in Python that represents the absence of a value (see glossary None). The keyword None
is the sole value of this type, and it is often used to signify “nothing,” “no value here,” or “not applicable.”
Examples of None Type:
>>> result = None # Explicit assignment of None
>>> type(result)
<class 'NoneType'>
2.4.8.3. Assignment Operation Returns NoneType#
In Python, an assignment operation (=
) does not produce a value or result; instead, it binds a value to a variable. Since the purpose of assignment is to associate a variable with a value rather than to produce a new value, the operation itself does not return anything. Therefore, it implicitly returns None
.
Example:
>>> x = 10 # Assignment operation
>>> x # x now holds the value 10
10
>>> result = (x = 10) # This would cause a SyntaxError because assignment doesn't return a value
If you try to use an assignment operation in a place where a value is expected (such as inside a print function or as part of another expression), it would raise a SyntaxError because assignment is not a value-producing expression. This design choice prevents confusion between assignment and comparison operations (==).
>>> x = 10 # Assignment
>>> y = x # Valid assignment, y now holds the value of x
>>> z = (x == 10) # Valid: comparison operation, returns True
>>> z
True
2.4.8.4. Interpreter and NoneType#
When you enter an instruction in the interpreter, depending on the type of the expression, the interpreter may or may not display the result. If the type of the expression is NoneType
, the interpreter displays nothing. Otherwise, it displays the resulting value of the expression.
>>> 8 / 2 # Type of division is float, result is displayed
4.0
>>> x = 10 # Type of assignement is NoneType, result is not displayed
>>> y = None # Type of assignement is NoneType, result is not displayed
>>> y # y is None, result is not displayed
>>> x # x is an int, result is displayed
10
2.5. Conclusion#
While experimenting with the interpreter, we encountered the first types in Python :
NoneType
int
float
bool
str
We also covered arithmetic and comparison operators. We analyzed how these operators determine the type of an expression.
Later, we will revisit strings, which are a much more complex type than what we have seen so far…