2. Introduction to Python programming#

2.1. Variables#

2.1.1. What are variables?#

Variables are nothing more than placeholders for values. Each variable has a name (identifier), which we as programmers give it. Also, each variable is assigned a value using the = (assignment operator). Variables are saved in the main memory (RAM) of a computer for the duration of the program execution. What really happens is this: when we give a name to a variable we actually name the memory location that will hold the value for that variable. The name that we give to the variables is not relevant to the computer at all. In the end, when the program is being executed the name will be translated to a memory address. Fig. 2.1 illustrates the idea.

var_assign_illustration

Fig. 2.1 Variable Assignment#

Important

Note that the computer does not change the name of an address for a memory cell. It just maps x to the value of that particular address, so that it knows whenever we call x in the code it is going to read the contents at that location. E.g. in Fig. 2.1 , the address where 2 is saved would still be 0x6f66.. even after assigning 2 to that location. However, the computer would know that what we call x in reality it is 0x6f66.. .

Here is an example of assigning a value to a variable and then checking the variable’s value using the print() function:

x = 2 # assign value 2 to variable x
print('The value of x is', x) # print the value of variable x
The value of x is 2

We are free to name variables as we want, but it is a good practice to give them self-explanatory names, so that we can easily find out what is the purpose of each variable. In addition, there are some rules regarding the characters that an identifier can have. For example, they can contain letters, digits and underscores (_). However, an identifier must never start with a digit. Also, Python is a case-sensitive programming language. This means that two variables a and A are different. You cannot call a by calling A.

Note

When variable names contain more than one word, Python programmers use something that is called snake case as a stylistic norm. For example, myVariableName would be written as my_variable_name. Still, if you do not abide with this way of naming variables, the code will run without problems, as long as there are no other types of errors.

Attention

Another important rule is the indentation. As we have stated previously, Python is a space-sensitive programming language. It is advised to use 4 spaces per indentation level. We will use this throughout our code examples.

You can find more rules for good programming practices in the Style Guide Documentation for Python.

2.1.2. Types of variables#

The type of a variable determines what kind of values the variable is going to hold: integers, decimals, strings (sequences of characters), etc. However, we usually do not need to explicitly determine the type of a variable, since it is implicitly determined during runtime (i.e., when a program is executed). There are several built-in data types in Python. Here, we present the most used types — notice the special syntax (i.e., structure of characters) that differentiates these types. In the following chapters we are going to further explore many of these types and their syntax. We can check the type of a variable using the type() built-in function.

# numeric values
integer = 2 # integer
decimal = 2.5 # decimal or floating-point number

# boolean values
boolean = True

# sequence of characters
string = 'Welcome to Python Programming!' # string

#collection of values
list_of_values = [1,2,3,4] # list
tuples = ('a', 1) # tuple
dictionary = {'one':1, 'two':2, 'three':3} # dictionary
print('integer is of type', type(integer))
print('decimal is of type', type(decimal))
print('boolean is of type', type(boolean))
print('string is of type', type(string))
print('list_of_values is of type', type(list_of_values))
print('tuples is of type', type(tuples))
print('dictionary is of type', type(dictionary))
integer is of type <class 'int'>
decimal is of type <class 'float'>
boolean is of type <class 'bool'>
string is of type <class 'str'>
list_of_values is of type <class 'list'>
tuples is of type <class 'tuple'>
dictionary is of type <class 'dict'>

Table 2.1 summarizes the above mentioned data types and the values that they hold.

Table 2.1 Variable types in Python#

Variable Type

Python Class

Explanation

integer

int

numbers like ...,-2,-1,0,1,2,...

decimal

float

decimal values, rational numbers, etc.

boolean

bool

only values: True or False

string

str

words, sentences, any sequence of characters

list

list

mutable collection of variables or values

tuple

tuple

immutable collection of variables or values

dictionary

dict

collection of key-value pairs, where keys must be unique

2.2. Arithmetic operators#

Python supports most of the arithmetic operators. Below you can see code examples. Each operator can receive two operands (numbers).

2.2.1. Addition (+)#

The following piece of code adds values 5 and 7 and assigns the result to the sum_result variable.

sum_result = 5 + 7
print('5 + 7 =', sum_result)
5 + 7 = 12

2.2.2. Subtraction (-)#

The following piece of code subtracts value 5 from 7 and assigns the result to the difference variable.

difference = 7 - 5
print('7 - 5 =', difference)
7 - 5 = 2

2.2.3. Multiplication (*)#

The following piece of code multiplies values 5 and 7 and assigns the result to the product variable.

product = 5 * 7
print('5 * 7 =', product)
5 * 7 = 35

2.2.4. True division (/)#

The following piece of code divides values 7 by 5 and assigns the result to the quotient variable. The results will always be a floating-point number.

quotient_1 = 7 / 5
print('7 / 5 =', quotient_1)
7 / 5 = 1.4

2.2.5. Floor division (//)#

In contrast to the true division, floor division will divide two numbers and return an integer (whole number) which will be the result rounded down.

quotient_2 = 7 // 5
print('7 // 5 =', quotient_2)
7 // 5 = 1

2.2.6. Remainder (%)#

The following piece of code finds the remainder of 7 divided by 5 and assigns the result to the remainder variable. The result will always be an integer.

remainder = 7 % 5
print('7 % 5 =', remainder)
7 % 5 = 2

2.2.7. Exponentiation (**)#

The following piece of code raises 7 to the power of 5 and assigns the result to the power variable.

power = 7 ** 5
print('7 ^ 5 =', power)
7 ^ 5 = 16807

2.2.8. Use of parentheses#

In Python expressions, parentheses have the same function as in algebraic expressions. They will group together values whose operations should be computed first. Check the code example below to understand the role of the parentheses. The precedence of the operators is the same as in algebraic expressions.

2*(4+2)
12
2*4+2
10

2.2.9. Precedence rules#

If an expression contains multiple operators, then they are executed according to the following rules:

Important

  1. Expressions in parentheses are evaluated first.

  2. Exponentiation is evaluated next in a right to left fashion if there are multiple of them.

  3. Multiplication, division and remainder are evaluated next from left to right if there are many.

  4. Addition and subtraction are left for the very end, just like in algebraic expressions.

You can learn more about Python operator precedence in the official Python documentation.

In Fig. 2.2 you can find an example on how Python would evaluate an algebraic expression with many operators.

operator_precedence_illustration

Fig. 2.2 Operator Precedence Example#

Note

All operators produce a result that has the same type as their operands (inputs), except of the true division (/) that always produces a floating-point number. In case when the operands are of mixed-types, e.g. one is an integer and one a floating-point, the result will always be a floating point.

2.3. Comparison operators#

Python supports the algebraic comparison operators as well. As we will see in the next chapters, they are important in conditional statements. Here you can find a summary of the comparison operators:

Table 2.2 Comparison Operators#

Operator

Function

Example

==

Test for equality

x == y

!=

Test for inequality

x != y

>

Greater than

x > y

<

Less than

x < y

>=

Greater than or equal

x >= y

<=

Less than or equal

x <= y

2.4. Logical operators#

Logical operators take at most two boolean values and output a single boolean value. They are used to evaluate whether an expression is True or False. There are truth tables that indicate the results of each of the logical operators. The most used logical operators are: AND, OR and NOT.

2.4.1. Logical AND#

Here you can find the truth table of the logical AND. It evaluates to TRUE only if both operands are true.

Table 2.3 AND Truth Table#

Operand 1

Operand 2

Result

True

True

True

True

False

False

False

True

False

False

False

False

Let us see some examples in Python.

x = 3
y = 5
print('x > 0 is', (x > 0))
print('y > 0 is', (y > 0))
print('(x > 0) and (y > 0) is', (x > 0) and (y > 0))
x > 0 is True
y > 0 is True
(x > 0) and (y > 0) is True

As we can see from the code cell above, the left operand evaluates to True since x = 3 > 0 is true. The same for the right operand, since y = 5 > 0 is true. This situation corresponds to the first row of Table 2.3 and the results of the table correspond to what is printed in our case.

print('x < 0 is', (x < 0))
print('y < 0 is', (y < 0))
print('(x < 0) and (y < 0) is', (x < 0) and (y < 0))
x < 0 is False
y < 0 is False
(x < 0) and (y < 0) is False

In this case, both operands evaluate to False. So, we are in the last row of Table 2.3, the expected result is False, which is indeed what we got.

print('x > 0 is', (x > 0))
print('y < 0 is', (y < 0))
print('(x > 0) and (y < 0) is', (x > 0) and (y < 0))
x > 0 is True
y < 0 is False
(x > 0) and (y < 0) is False

The same will be in this case:

print('x < 0 is', (x < 0))
print('y > 0 is', (y > 0))
print('(x < 0) and (y > 0) is', (x < 0) and (y > 0))
x < 0 is False
y > 0 is True
(x < 0) and (y > 0) is False

2.4.2. Logical OR#

Here you can find the truth table of the logical OR. It evaluates to False only if both operands are False.

Table 2.4 OR Truth Table#

Operand 1

Operand 2

Result

True

True

True

True

False

True

False

True

True

False

False

False

Let us apply the same operations as in the AND case above and see the results.

print('x > 0 is', (x > 0))
print('y > 0 is', (y > 0))
print('(x > 0) or (y > 0) is', (x > 0) or (y > 0))
x > 0 is True
y > 0 is True
(x > 0) or (y > 0) is True

As we can see from the code cell above, the left operand evaluates to True since x = 3 > 0 is true. The same for the right operand, since y = 5 > 0 is true. This situation corresponds to the first row of Table 2.4 and the results there corresponds to what is printed in our case.

print('x < 0 is', (x < 0))
print('y < 0 is', (y < 0))
print('(x < 0) or (y < 0) is', (x < 0) or (y < 0))
x < 0 is False
y < 0 is False
(x < 0) or (y < 0) is False

In this case, both operands evaluate to False. So, we are in the last row of Table 2.4, the excepted result is False, which is indeed what we got.

print('x > 0 is', (x > 0))
print('y < 0 is', (y < 0))
print('(x > 0) or (y < 0) is', (x > 0) or (y < 0))
x > 0 is True
y < 0 is False
(x > 0) or (y < 0) is True

Here we see that it is sufficient for only one operand to be True in order for the result of the OR operator to be True. It is the same even below.

print('x < 0 is', (x < 0))
print('y > 0 is', (y > 0))
print('(x < 0) or (y > 0) is', (x < 0) or (y > 0))
x < 0 is False
y > 0 is True
(x < 0) or (y > 0) is True

2.4.3. Logical NOT#

The NOT operator is used to invert the value the operand. It receives only one operand. If the value it receives is True it will output False and if the value it receives is False, it will output True. Here is the truth table.

Table 2.5 NOT Truth Table#

Operand 1

Result

True

False

False

True

Here are some code examples that illustrate the NOT operator.

flag = True
print('Flag variable at the beginning is:',flag)
flag = not(flag)
print('Flag variable after modification is:', flag)
flag = not(flag)
print('Flag variable after the second modification is:', flag)
Flag variable at the beginning is: True
Flag variable after modification is: False
Flag variable after the second modification is: True