In the first part we saw Python’s **data types**. In this second chapter we cover **operators**, **flow control** (if, for, while) and **functions**.
Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.
📚 **This post is part of the _Complete Python Guide_ series**, divided into three chapters that are read in order:
> * Part 1: Data types
* 👉 **Part 2: Operators, control flow, and functions**
* Part 3: Classes, objects, and advanced topics
3. Operators
3.1. Arithmetic operators
Operator addition +
InputPython3 + 5Copied
8
Subtraction operator -
InputPython3 - 5Copied
-2
Multiplication operator *
InputPython3 * 5Copied
15
Division operator /
InputPython3 / 5Copied
0.6
Modulo operator %. Returns the remainder of a division
InputPython25 % 2Copied
1
Exponent operator **
InputPython5 ** 2Copied
25
Integer division operator //
InputPython25 // 2Copied
12
3.2. Comparison operators
Operator is ==
InputPython1 == 1Copied
True
Operator is different !=
InputPython1 != 2Copied
True
Operator is greater than >
InputPython3 > 2Copied
True
Operator is less than <
InputPython2 < 3Copied
True
Operator is greater than or equal to >=
InputPython3 >= 3Copied
True
Operator is less than or equal to <=
InputPython3 <= 3Copied
True
3.3. Logical Operators
Operator and
InputPythonTrue and TrueCopied
True
Operator or
InputPythonTrue or FalseCopied
True
Operator not
InputPythonnot FalseCopied
True
3.4. Identity operators
is operator
InputPython5.3 is 5.3Copied
True
Operator is not
InputPython5.3 is not 5Copied
True
3.5. Membership operators
in operator
InputPythonx = ["apple", "banana"]"banana" in xCopied
True
not in operator
InputPythonx = ["apple", "banana"]"orange" not in xCopied
True
3.6. Bitwise operators
AND operator &
InputPythona = 60 # 60 = 0011 1100b = 13 # 13 = 0000 1101c = a & b; # 12 = 0000 1100cCopied
12
OR operator |
InputPythona = 60 # 60 = 0011 1100b = 13 # 13 = 0000 1101c = a | b; # 61 = 0011 1101cCopied
61
XOR operator ^
InputPythona = 60 # 60 = 0011 1100b = 13 # 13 = 0000 1101c = a ^ b; # 49 = 0011 0001cCopied
49
NOT operator ~
InputPythona = 60 # 60 = 0011 1100c = ~a; # -61 = 1100 0011cCopied
-61
Left shift operator <<
InputPythona = 60 # 60 = 0011 1100c = a << 2; # 240 = 1111 0000cCopied
240
Right shift operator >>
InputPythona = 60 # 60 = 0011 1100c = a >> 2; # 15 = 0000 1111cCopied
15
3.7. Assignment operators
Operator =
InputPythona = 5aCopied
5
Operator +=. x += y is equivalent to x = x + y
InputPythona += 5aCopied
10
Operator -=. x -= y is equivalent to x = x - y
InputPythona -= 5aCopied
5
Operator *=. x *= y is equivalent to x = x * y
InputPythona *= 3aCopied
15
Operator /=. x /= y is equivalent to x = x / y
InputPythona /= 3aCopied
5.0
Operator %=. x %= y is equivalent to x = x % y
InputPythona = 25a %= 2aCopied
1
Operator //=. x //= y is equivalent to x = x // y
InputPythona = 25a //= 2aCopied
12
Operator **=. x **= y is equivalent to x = x ** y
InputPythona = 5a **= 2aCopied
25
Operator &=. x &= y is equivalent to x = x & y
InputPythona = 60 # 60 = 0011 1100b = 13 # 13 = 0000 1101a &= b; # 12 = 0000 1100aCopied
12
Operator |=. x |= y is equivalent to x = x | y
InputPythona = 60 # 60 = 0011 1100b = 13 # 13 = 0000 1101a |= b; # 61 = 0011 1101aCopied
61
Operator ^=. x ^= y is equivalent to x = x ^ y
InputPythona = 60 # 60 = 0011 1100b = 13 # 13 = 0000 1101a ^= b; # 49 = 0011 0001aCopied
49
Operator >>=. x >>= y is equivalent to x = x >> y
InputPythona = 60 # 60 = 0011 1100a <<= 2; # 240 = 1111 0000aCopied
240
Operator <<=. x <<= y is equivalent to x = x << y
InputPythona = 60 # 60 = 0011 1100a >>= 2; # 15 = 0000 1111aCopied
15
4. Flow Control
To be able to use flow control tools, it is necessary to add the statement, a colon : and on a new line write the code with indentation.
Unlike other languages, Python needs indentation (adding whitespace) to define the code within a control flow tool
4.1. Si
Using if, we can create conditionals
InputPythonif len('MaximoFN') == 8:print('MaximoFN tiene 8 caracteres')Copied
MaximoFN tiene 8 caracteres
If we want to create more than one condition, we can use elif
InputPythonif len('MaximoFN') < 8:print('MaximoFN tiene menos de 8 caracteres')elif len('MaximoFN') == 8:print('MaximoFN tiene 8 caracteres')Copied
MaximoFN tiene 8 caracteres
If what we want is for something to run in case none of the indicated conditions are met, we can use else
InputPythonif len('MaximoFN') < 8:print('MaximoFN tiene menos de 8 caracteres')elif len('MaximoFN') > 8:print('MaximoFN tiene más de 8 caracteres')else:print('MaximoFN tiene 8 caracteres')Copied
MaximoFN tiene 8 caracteres
If we want to write everything on a single line
InputPythonif len('MaximoFN') == 8: print('MaximoFN tiene 8 caracteres')Copied
MaximoFN tiene 8 caracteres
Likewise, if we want to write everything on one line, but with several conditions
InputPythonprint('MaximoFN tiene menos de 8 caracteres') if len('MaximoFN') < 8 else print('MaximoFN tiene más de 8 caracteres') if len('MaximoFN') > 8 else print('MaximoFN tiene 8 caracteres')Copied
MaximoFN tiene 8 caracteres
If, for example, we want to create the structure of the if but do not want, for now, to code one of the conditions, we can use pass
InputPythonif len('MaximoFN') < 8:print('MaximoFN tiene menos de 8 caracteres')elif len('MaximoFN') > 8:passelse:print('MaximoFN tiene 8 caracteres')Copied
MaximoFN tiene 8 caracteres
4.2. Mientras
The while loop runs while the condition is True
InputPythoni = 0string = 'MaximoFN'while len(string) > i:print(string[i], end='')i += 1Copied
MaximoFN
If we want the loop to stop for some condition, we use break
InputPythoni = 0string = 'MaximoFN'while len(string) > i:if string[i] == 'F':breakprint(string[i], end='')i += 1Copied
Maximo
If we want one of the iterations not to execute for some reason, we use continue
InputPythoni = 0string = 'Maximo FN'while len(string) > i:if string[i] == ' ':i += 1continueprint(string[i], end='')i += 1Copied
MaximoFN
Using else, you can execute a block of code if the while condition is not True
InputPythoni = 0string = 'MaximoFN'while len(string) > i:print(string[i], end='')i += 1else:print(" Se ha terminado el while")Copied
MaximoFNSe ha terminado el while
4.3. Para
The for loop is used to execute code while iterating over a sequence; this sequence can be any iterable element in Python (string, list, tuple, range, dictionary, set)
InputPythonstring = 'MaximoFN'for x in string:print(x, end='')Copied
MaximoFN
InputPythonlista = ['M', 'a', 'x', 'i', 'm', 'o', 'F', 'N']for x in lista:print(x, end='')Copied
MaximoFN
InputPythontupla = ('M', 'a', 'x', 'i', 'm', 'o', 'F', 'N')for x in tupla:print(x, end='')Copied
MaximoFN
InputPythonstring = 'MaximoFN'for i in range(len(string)):print(string[i], end='')Copied
MaximoFN
InputPythondiccionario = {"letra1": "M","letra2": "a","letra3": "x","letra4": "i","letra5": "m","letra6": "o","letra7": "F","letra8": "N",}for x in diccionario.values():print(x, end='')Copied
MaximoFN
You can also iterate over sets, but since they are unordered elements, we won't have control over the execution order
InputPythonset_ = {'M', 'a', 'x', 'i', 'm', 'o', 'F', 'N'}for x in set_:print(x, end='')Copied
NximoaMF
If we want the loop to stop for some condition, we use break
InputPythonstring = 'MaximoFN'for x in string:if x == 'F':breakprint(x, end='')Copied
Maximo
If we want one of the iterations not to run for some reason, we use continue
InputPythonstring = 'Maximo FN'for x in string:if x == ' ':continueprint(x, end='')Copied
MaximoFN
Using else, you can execute a block of code if the condition of the while is not True
InputPythonstring = 'MaximoFN'for x in string:print(x, end='')else:print(" Se ha terminado el for")Copied
MaximoFNSe ha terminado el for
If, for example, we want to create the structure of the for loop but do not want to code its body yet, we can use pass
InputPythonstring = 'MaximoFN'for x in string:passprint('Interior del for no codificado')Copied
Interior del for no codificado
5. Functions
A function is a portion of code that can be executed as many times as you want. It can be passed arguments and can return data as a result
To define a function, start with the reserved word def, followed by the function name, parentheses (), a colon :, and then on a new line, indented, the function code.
InputPythondef funcion():print('MaximoFN')Copied
To call the function, it is only necessary to write its name
InputPythonfuncion()Copied
MaximoFN
Functions can be passed as many arguments as desired, within the parentheses and separated by commas
InputPythondef funcion(string1, string2):print(string1 + ' ' + string2)funcion("Hola", "MaximoFN")Copied
Hola MaximoFN
When the function is called, the same number of arguments that were declared must be passed to it; if more or fewer are passed, an error would occur.
If we do not know the arguments that the function will receive, we can use *args, that is, by placing a * before the arguments, we indicate that the number of arguments is flexible.
By doing this, a tuple is passed to it (remember that it is immutable) with the arguments
InputPythondef funcion(*argumentos):numero_argumentos = len(argumentos)for i in range(numero_argumentos):print(argumentos[i], end=' ')funcion("funcion", "con", "varios", "argumentos", "sin", "especificar", "cuantos")Copied
funcion con varios argumentos sin especificar cuantos
In case we do not know the order of a function's arguments, we can specify the argument we want to pass by indicating its name.
InputPythondef funcion(argumento1, argumento2, argumento3):print(argumento1 + ' '+ argumento2 + ' ' + argumento3)funcion(argumento3 = "MaximoFN", argumento1 = "Blog", argumento2 = "de")Copied
Blog de MaximoFN
In case you want to pass the arguments by name, but if you do not know how many arguments will be passed, you can use **kwargs. In this case, a dictionary with the arguments will be passed to it.
InputPythondef funcion(**kargumentos):print("Autor del blog: " + kargumentos["autor"])funcion(blog = "Blog", pertenencia = "de", autor = "MaximoFN")Copied
Autor del blog: MaximoFN
If we want any argument to have a default value, we can indicate it between the parentheses of the function. In this way, if when calling the function that argument is not passed, it will have the default value in the function.
InputPythondef funcion(argumento1, argumento2, argumento3 = "MaximoFN"):print(argumento1 + ' '+ argumento2 + ' ' + argumento3)funcion("Blog", "de")Copied
Blog de MaximoFN
Any type of data can be passed as an argument. For example, if a list is passed as an argument, within the function, that argument will be treated as a list
InputPythondef funcion(argumento):longitud_lista = len(argumento)for i in range(longitud_lista):print(argumento[i], end=' ')funcion(["Blog", "de", "MaximoFN"])Copied
Blog de MaximoFN
Functions can return data, this is done using the reserved word return
InputPythondef funcion(argumento):longitud_lista = len(argumento)string = ""for i in range(longitud_lista):string = string + argumento[i] + ' 'return stringprint(funcion(["Blog", "de", "MaximoFN"]))Copied
Blog de MaximoFN
They can return more than one piece of data
InputPythondef funcion(argumento):longitud_lista = len(argumento)string0 = argumento[0]string1 = argumento[1]string2 = argumento[2]return string0, string1, string2dato0, dato1, dato2 = funcion(["Blog", "de", "MaximoFN"])print(dato0 + ' ' + dato1 + ' ' + dato2)Copied
Blog de MaximoFN
If one of the returned data items is not of interest to us, we can skip it using _
InputPythondef funcion(argumento):longitud_lista = len(argumento)string0 = argumento[0]string1 = argumento[1]string2 = argumento[2]return string0, string1, string2_, _, dato_de_interes = funcion(["Blog", "de", "MaximoFN"])print(dato_de_interes)Copied
MaximoFN
If, for example, we want to create the structure of the function, but for now we don't want to code the inside, we can use pass
InputPythondef funcion():passfuncion()Copied
A function can call itself; this is called recursion or recursive function behavior.
For example, we can use this property to calculate the factorial of a number
InputPythondef factorial(n):if n == 0 or n == 1:return 1else:return n * factorial(n-1)factorial(5)Copied
120
5.1. Funciones integradas
There are a series of functions already defined in Python that can be used, such as the abs() function, which returns the absolute value
InputPythonabs(-5)Copied
5
Below is a list of these functions
InputPythonimport builtinsdir(builtins)Copied
['ArithmeticError','AssertionError','AttributeError','BaseException','BlockingIOError','BrokenPipeError','BufferError','BytesWarning','ChildProcessError','ConnectionAbortedError','ConnectionError','ConnectionRefusedError','ConnectionResetError','DeprecationWarning','EOFError','Ellipsis','EnvironmentError','Exception','False','FileExistsError',...'slice','sorted','staticmethod','str','sum','super','tuple','type','vars','zip']
5.2. Function documentation
An explanation of a function we create can be added through a comment at the start of the function; in this way, when we call the built-in function help(), it will show that explanation.
InputPythondef funcion():"Esta es la explicación de la función"Nonehelp(funcion)Copied
Help on function funcion in module __main__:funcion()Esta es la explicación de la función
Another option to view the function's explanation is to use the function's __doc__ method
InputPythonfuncion.__doc__Copied
'Esta es la explicación de la función'
5.3. Decorators
Decorators are a Python feature that allows new capabilities to be added to a function
A decorator function is created that takes another function as a parameter. Then the decorator function adds the new feature to the function it receives.
InputPythondef decorador(parametro_funcion):"""Agrega barritas arriba y abajo de la funcion"""def envoltorio():"""Aplica las barritas al texto"""print("==================")parametro_funcion()print("==================")return envoltoriodef funcion():print("MaximoFN")funcion_envoltorio = decorador(funcion)print('Función sin decoradores: ')funcion()print(' Función con decoradores: ')funcion_envoltorio()Copied
Función sin decoradores:MaximoFNFunción con decoradores:==================MaximoFN==================
But a more powerful way to use decorators is by using @ and the decorator’s name before the function.
That is, first the decorator is defined and, then, a function is called with the defined decorator
InputPythondef decorador2(parametro_funcion2):"""Agrega barritas arriba y abajo de la funcion"""def envoltorio2():"""Aplica las barritas al texto"""print("==================")parametro_funcion2()print("==================")return envoltorio2@decorador2def funcion2():print("MaximoFN")print('Función con decoradores: ')funcion2()Copied
Función con decoradores:==================MaximoFN==================
5.4. *args and **kwargs
*args and **kwargs are optional arguments that can be used when defining a function in Python. The syntax is as follows:
def my_function(arg1, arg2, *args, **kwargs):
# function code here5.4.1. *args
*args is used to pass a variable number of arguments to a function. By using *args, you can send a variable amount of arguments to the function without having to specify the exact number of arguments the function needs. The arguments are received in the function as a tuple.
InputPythondef saludo(saludo, *nombres):for nombre in nombres:print(f"{saludo}, {nombre}")saludo("Hola", "Alicia", "Roberto", "Carlos")Copied
Hola, AliciaHola, RobertoHola, Carlos
5.4.2. **kwargs
**kwargs is used in the same way, but to send a variable number of keyword arguments (keyword arguments) to a function. By using **kwargs, you can send a variable amount of arguments to the function and specify the value of each argument using its name. The arguments are received in the function as a dictionary.
InputPythondef saludo(saludo, **personas):for key, value in personas.items():print(f"{saludo} {key}, tu edad es {value} años")saludo("Hola", Juan=22, Maria=32, Pedro=25)Copied
Hola Juan, tu edad es 22 añosHola Maria, tu edad es 32 añosHola Pedro, tu edad es 25 años
6. Additional functions
6.1. *Lambda* functions
A *lambda* function is a small anonymous function.
A *lambda* function can take any number of arguments, but it can only have one expression.
*Lambda* functions are defined as follows:
lambda arguments : expressionInputPythonx = lambda a : a + 10print(x(5))Copied
15
InputPythonx = lambda a, b, c : a + b + cprint(x(5, 6, 2))Copied
13
The power of *lambda* is best shown when it is used as an anonymous function within another function.
InputPythondef myfunc(n):return lambda a : a * nmydoubler = myfunc(2)mytripler = myfunc(3)print(f"mydoubler: {mydoubler(11)}")print(f"mytripler: {mytripler(11)}")Copied
mydoubler: 22mytripler: 33
6.2. Function map
The map function allows you to apply a function to each element of an iterable structure
InputPythonlista = [1, 2, 3]def funcion_mas_1(valor):return valor + 1lista_modificada = list(map(funcion_mas_1, lista))lista_modificadaCopied
[2, 3, 4]
This is equivalent to using list comprehension
InputPythonlista_modificada = [funcion_mas_1(x) for x in lista]lista_modificadaCopied
[2, 3, 4]
6.3. Function filter
The filter function allows selecting the elements of an iterable structure that meet a condition
InputPythonlista = [1, 2, 3, 4, 5, 6, 7]def esPar(valor):return valor % 2 == 0lista_filtrada = list(filter(esPar, lista))lista_filtradaCopied
[2, 4, 6]
This is equivalent to using list comprehension
InputPythonlista_filtrada = [x for x in lista if esPar(x)]lista_filtradaCopied
[2, 4, 6]
6.4. reduce Function
The reduce function allows performing cumulative tasks on iterable structures
InputPythonfrom functools import reducelista = [1, 22, 33]def acumular(valor, acumulador):print(f'valor = {valor}, acumulador = {acumulador}, acumulacion = {valor + acumulador}')return valor + acumuladoracumulacion = reduce(acumular, lista)print(f' acumulacion = {acumulacion}')Copied
valor = 1, acumulador = 22, acumulacion = 23valor = 23, acumulador = 33, acumulacion = 56acumulacion = 56
6.5. Function zip
With the zip function, several iterable structures can be combined into one, that is, it allows grouping several elements from the *Ax* structures into a single *B* structure. The *B* structure is made up of tuples of the elements of the *Ax* structures
InputPythonnombres = ["Manolo", "Andres", "Fernando"]altura = [181, 178, 180]my_zip = list(zip(nombres, altura))my_zipCopied
[('Manolo', 181), ('Andres', 178), ('Fernando', 180)]
6.5. Generators
Suppose we want to iterate over a sequence of numbers, but in a special way that no kind of loop offers us. We can solve this with generators. To do this, the generator function does not have to return the value with return, but with yield so that it knows it has to keep iterating
InputPythondef iterador_custom(N):for i in range (N):if i % 3 == 0:yield igenerador = iterador_custom(20)for i in generador:print(i)Copied
0369121518
We just made an iterator for numbers that are multiples of 3
6.6. Funciones de orden superior
We can create functions that receive other functions as parameters, so that the function that receives another function as a parameter is called a higher-order function. Let’s look at an example
InputPythondef increment(x):return x + 1def hof(f, x):return 2*f(x)print(hof(increment, 3))Copied
8
---
➡️ **Continue in Part 3: classes, objects, and advanced topics**, where you will make the leap to object-oriented programming and modules.