Python Basics
Control flow
When writing complex code, it almost never can be done in one unique sequence. Often some operations need to be repeated or executed conditionnaly. Control flow in python work like most languages, using a collection of statements introduced by specific key-word.
It is easier than it sounds and is best explained with example.
Tristan
contact-datartichaut@pm.me
Python pages list
int_age = 25
if int_age < 18:
print('You are not allowed to drink !')
It always begins with a if and always ends with a :.
if statements can use other clauses :
elif allows to do something else depending on a new condition.else allows to do something if none of the previous conditions were met.int_age = 25
if int_age < 18:
print('You are not allowed to drink !')
elif int_age >= 18:
print('Here is a beer !')
else:
print('Something went wrong.')
Even if the code seem to cover every possibility, it is considered good practice to have an
else statement just in case.
Beginner
The for statement.
The for statement allows a piece of code to be repeated.
This allows to go over a list of object and apply some code to each element.
In other languages, such as C, for loops are dependent on a variable, a
condition and a step to increment the variable with each loop, for example :
for (i = 1; i < 11; ++i){}
The variable i starts at 1, is incremented by 1 every step and the for statement stops when the
i < 11 is not true anymore.
With python, for loops go over a collection (or an iterable) of objects.
ToC
l1 = [1, 2, 3, 4, 5, 6]
for num in l1:
print(num)
The break and continue statements allow to control what happend inside each loop.
break ends its parent for statement.continue ends the current loop.l1 = [1, 2, 54, 3, 85, 2, 61, 3, 'A', 1, 58, 2]
for elt in l1:
# If we enconter anything other than a number then we stop
if not isinstance(elt, int):
break
# If the number is small enough, then we don't do anything
if elt < 50:
continue
print(f"Found a big number : {elt}")
We can see, no number under 50 was printed and 58 was not printed because
the 'A' triggered the break statement.
The break and continue statements are sometimes seen as bad practices
because in most cases they can be replaced with if statements and they are not as readable.
Intermediate
It is not very well known but for statements can have an else clause.
l1 = [1, 2, 3, 4, 5, 6]
for num in l1:
print(num)
else:
print('Got to the else clause')
It may seem strange that the whole list was iterated over but it is intended to work that way.
The else clause is always executed after the last iteration unless a
break clause is encountered.
It is often said that the else clause should have been called nobreak.
l1 = [1, 2, 54, 3, 85, 2, 61, 3, 'A', 1, 58, 2]
for elt in l1:
# If we enconter anything other than a number then we stop
if not isinstance(elt, int):
break
# If the number is small enough, then we don't do anything
if elt < 50:
continue
print(f"Found a big number : {elt}")
else:
print('Sorted every elements without encountering a problem.')
In this case, the break is triggered by the 'A' element and the
else clause is not reached.
Beginner
The while statement.
The while statement is another way to loop and repeat a piece of code. It differs from the
for statement because what stops the statement is a specific condition.
Put simply, while the condition is true, the statement goes on.
ToC
elt = 0
while elt < 11:
print(elt)
elt = elt + 3
while statements are a little trickier than for statements.
Some languages have while and do while statements, but not python.
Intermediate
Let's look at a slightly more complicated example.
l1 = [1, 2, 54, 3, 85, 2, 61, 3, 'A', 1, 58, 2]
enum_l1 = enumerate(l1)
while isinstance(elt := next(enum_l1)[1], int):
if elt > 50:
print(f"Found a big number : {elt}")
This does the same job as the for statement example, but is a bit simpler.
The := operator (also called walrus operator) can be used inside statements to assign a value
that we want to use later.
It is important in this example because I use an enumerate object and if I call
next a second time, inside the while statement, we would get the next element
and not the one we want to work with.
Beginner
The match statement.
The match statement can be compared to a sequence of if / elif
statements.
It can be comaprered to the switch case of other languages although ultimately it is not the same thing.
It can be very powerfull and allow to execute specific code for values that match a specific pattern.
Let's start with a simple example.
ToC
str_color = 'green'
match str_color:
case 'green':
print("Let's go !")
case 'orange':
print('Stop if possible.')
case 'red':
print('Stop !')
The match statement can handle more than plain string comparison in each case.
str_color: str = 'red'
match str_color:
case 'green':
print("Go !")
case 'orange' | 'red':
print("Stop !")
Intermediate
The match can also handle regular expression (hence the name of "matching").
import re
str_id = 'FR_16615'
match str_id:
case x if re.match(r'FR_\d*', x):
print('A french ID')
case x if re.match(r'EN_\d*', x):
print('A foreign ID')
case _:
print('Not recognized')
The match can also handle dictionnary for example.
dict_conf =\
{'fontsize': 12,
'console': 'debug'}
match dict_conf:
case {'console': 'debug'}:
print('Debug mode')
case {'console': 'prod'}:
print('Production mode')
The match is a big subject and need its own page to get into enough details.
Beginner
The pass statement.
The pass statement is a simple empty statement.
It allows for a placeholder or to create an empty class.
ToC
int_age = 52
if int_age < 18:
pass
elif int_age >= 18:
pass
else:
pass
I usually use pass to write out the structure of a piece of code like an if
statement, and then I fill in the blanks.