In this section, we are going to give an introduction to Python. Once we have Python installed and configured, this section will serve as a fundamental reinforcement before we move on to building a framework in the next stage.
It is important to note that this section is a review and not an introduction to programming from scratch. Therefore, it is assumed that you have basic programming knowledge and, preferably, some familiarity with Python.
Python Interactive Console
Content Index
- Python Interactive Console
- Python Files (.py)
- Variables and Data Types
- Mathematical Operations
- String Handling
- Casting (Type Conversion)
- Lists
- Conditionals (if, elif, else)
- Loops (for and while)
- Functions
- Parameters
- Classes and Objects
- Inheritance
- Modules
- Create a module
- Import a module
- The if __name__ == "__main__": block
The first tool you can use is the interactive console. Once Python is installed and the environment variables are configured, you can open a terminal (CMD, PowerShell, or Terminal) and type python.
$ python
Python 3.14.7 (default, Mar 8 2026, 16:59:28)
[GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>The >>> symbol indicates that the console is ready to receive Python commands. It is an ideal tool for quick tests, experimenting with functions, or exploring the language.
For example, you can perform mathematical operations and see the result immediately:
>>> 10 + 5
15
>>> "Hello" + " " + "World"
'Hello World'To exit the interactive console, you can use the exit() or quit() functions.
>>> exit()Python Files (.py)
The most common way to write programs is through files. In Python, these files have the .py extension. Let's create a file called hello.py.
Inside hello.py, we will use the print() function to display a message in the terminal. This function is essential for debugging and displaying results.
The print() function allows you to print text to the terminal or CMD and is a tool that we will use extensively to quickly debug when developing the different functionalities of our application, so, following our example, we put:
# hello.py
print("Hello, world from a file!")To run this file, open a terminal in the directory where you saved it and run the following command:
$ python hello.pyYou will see the following output:
Hello, world from a file!Variables and Data Types
Python is a dynamically typed language, which means you don't need to declare the type of a variable. Python infers it automatically at the time of assignment.
- Text:
str(e.g. "Hello", 'Python') - Numeric:
int(e.g. 10, -5),float(e.g. 3.14, -0.5),complex(e.g. 1+2j) - Sequences:
list(e.g. [1, "a"]),tuple(e.g. (1, "a")),range - Mapping:
dict(e.g. {"key": "value"}) - Sets:
set(e.g. {1, 2, 3}),frozenset - Boolean:
bool(TrueorFalse) - Null:
NoneType(None)
You can use the type() function to check the type of a variable.
>>> name = "Andres"
>>> age = 30
>>> height = 1.75
>>> is_developer = True
>>> type(name)
<class 'str'>
>>> type(age)
<class 'int'>
>>> type(height)
<class 'float'>
>>> type(is_developer)
<class 'bool'>Python is not a language in which we must place the data type when declaring the variable, it is dynamically typed, which means that Python infers it at the time of initializing a value:
n = 5If not, as in JavaScript, the type is inferred based on the declared value; if it is an integer:
n = 5If it is a float:
n = 5.2Or a String:
t = 'text'A boolean:
b = TrueIn python, we have a function called type() with which we can ask for the data type:
>>> t = 'text'
>>> type(t)
<class 'str'>Or to measure the length:
>>> t = 'text'
>>> len(t)
4Mathematical Operations
Mathematical operations do not change at all if we compare them with other programming languages, regardless of whether the result to be operated on is stored in a variable, or is a fixed value or returned from a function or similar:
>>> a = 10
>>> b = 3
>>> a + b # Sum
13
>>> a - b # Subtraction
7
>>> a * b # Multiplication
30
>>> a / b # Division (always returns a float)
3.333...
>>> a // b # Integer division (discards the fractional part)
3
>>> a % b # Modulo (remainder of the division)
1
>>> a ** b # Exponentiation (10 to the power of 3)
1000String Handling
String concatenation is done with the + operator. However, a more modern and readable way is to use f-strings.
>>> name = "Andres"
>>> profession = "developer"
# Traditional way
>>> greeting = "Hello, I am " + name + " and I am a " + profession + "."
>>> print(greeting)
Hello, I am Andres and I am a developer.
# Using f-strings (recommended)
>>> modern_greeting = f"Hello, I am {name} and I am a {profession}."
>>> print(modern_greeting)
Hello, I am Andres and I am a developer.Casting (Type Conversion)
Sometimes you need to convert one data type to another. This is known as casting.
>>> number_in_string = "100"
>>> integer_number = int(number_in_string)
>>> integer_number + 50
150
>>> float_number = float("99.5")
>>> float_number
99.5
>>> str(123)
'123'
# A number other than 0 is True, 0 is False
>>> bool(5)
True
>>> bool(0)
False
>>> bool(-1)
TrueIf you try to perform an invalid conversion, Python will raise an error.
>>> int("hello")
ValueError: invalid literal for int() with base 10: 'hello'Lists
Lists are ordered and mutable collections of items. They can contain different data types.
Lists are nothing more than a collection of data, when you enter applications like X, WhatsApp or an email like Outlook or Gmail, and you see a list of emails or messages, structures like lists are used, therefore, lists are a very common structure in which we can define primitives as seen before or objects as we will see in the classes section:
>>> fruits = ["apple", "banana", "cherry"]
>>> print(fruits)
['apple', 'banana', 'cherry']
# Access an item (indexes start at 0)
>>> fruits[0]
'apple'
# Access the last item
>>> fruits[-1]
'cherry'
# Add an item to the end
>>> fruits.append("orange")
>>> fruits
['apple', 'banana', 'cherry', 'orange']
# Remove an item by its value
>>> fruits.remove("banana")
>>> fruits
['apple', 'cherry', 'orange']
# Length of the list
>>> len(fruits)
3
# Slicing (sublists)
>>> numbers = [0, 1, 2, 3, 4, 5]
>>> numbers[1:4] # Items from index 1 to 3
[1, 2, 3]Starting from this list:
>>> list = [1,2,3]
>>> list
[1, 2, 3]To operate with these lists, we also have operations to know their length:
>>> len(list)
3Or to add all the elements of the list:
>>> list = [1,2,3]
>>> sum(list)
6Add new elements to the end of the list:
>>> list.append(5)
>>> list
[1, 2, 3, 5]Or remove an element by value (not index):
>>> list.remove(1)
>>> list
[2, 3, 5]To get a value from the list, we place the index starting from zero:
>>> list = [1,2,3]
>>> list[1]
2If we place an index that does not exist, it will give an exception like the following:
>>> list = [1,2,3]
>>> list[3]
IndexError: list index out of rangeThere are many other operations that you can use on lists and that you can consult in the official documentation.
Conditionals (if, elif, else)
Conditionals allow you to execute blocks of code only if certain conditions are met.
age = 20
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")You can use the logical operators and, or, and not to create complex conditions.
has_ticket = True
is_vip = False
if has_ticket and is_vip:
print("Welcome to the VIP area.")
elif has_ticket or is_vip:
print("Welcome to the event.")
else:
print("You need a ticket to enter.")- > Returns True if the left operator is greater than the right operator
- < Returns True if the right operator is greater than the left operator
- >= Returns True if the left operator is greater than or equal to the right operator
- <= Returns True if the right operator is greater than or equal to the left operator
- == Returns True if both are equal
- != Returns True if both are not equal
True and false conditions and if the condition to be evaluated is true, then the block of code that governs the conditional is executed:
age=15
if age >= 18:
print("You're of age")We can make complex conditions by nesting several conditions with the and:
age=15
woman=False
if age >= 18 and woman:
print("You are a man of legal age")Where all the conditions must be met to execute the conditional block, or the or, to execute the conditional block as long as some of the conditions are met:
age=19
woman=False
if age >= 18 or woman:
print("Message 1")
age=15
if age >= 18 or woman:
print("Message 2")
age=15
woman=True
if age >= 18 or woman:
print("Message 3")We also have the else block that would be executed when the conditional condition is not met:
age=19
if age >= 18:
print("You're of age")
else:
print("You are a minor")And we can evaluate multiple conditions or nest multiple conditionals:
age=19
woman=False
age=19
if age >= 18:
print("You're of age")
elif woman:
print("You're a woman")
else:
print("You are a man")Loops (for and while)
The for loop is used to iterate over a sequence (like a list, tuple, string, or range).
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Iterate a number of times with range()
for i in range(5): # From 0 to 4
print(f"Number: {i}")A common configuration is to use the for loop together with the range() function, which allows you to create a range like the following:
for i in range(0,10):
print(i)
0 1 2 3 4 5 6 7 8 9And in this way, the variable i corresponds to an element of the range to be iterated.
The while loop executes as long as a condition is true.
counter = 0
while counter < 5:
print(f"The counter is {counter}")
counter += 1 # It is crucial to increment the counter to not create an infinite loopFunctions
Functions are reusable blocks of code. They are defined with the def keyword.
def greet(name: str):
"""This function greets the person passed as an argument."""
print(f"Hello, {name}. Welcome!")
# Call the function
greet("Ana")Functions can receive parameters and return values using return.
def add(a: int, b: int) -> int:
"""Returns the sum of two integers."""
return a + b
result = add(10, 5)
print(f"The result is: {result}") # Output: The result is: 15You can define default values for parameters.
def power(base: int, exponent: int = 2) -> int:
return base ** exponent
print(power(3)) # Uses the default exponent: 9
print(power(3, 3)) # Provides an exponent: 27As in the case of conditionals and loops, they allow you to create blocks of code, but, this time we can easily invoke it; the previous block of code becomes:
def sum():
a=5
b=6
print("Sum numbers")
c = a+b
print("res "+str(c))And to invoke it, we use the name of the function, in this example, sum():
sum()The advantage we have is that since everything is encapsulated (in a different scope than the global one), we can easily reuse the previous function as many times as we want by invoking said function, for example, if we want to invoke the body of the function 3 times, we invoke it 3 times:
sum()
sum()
sum()Parameters
With parameters, we can make truly reusable blocks of code, for example, we can create a function that receives an argument to print, for example, a name:
def yourName(name):
print(name)
yourName('andres')You can specify the type:
def yourName(name:str):
***Which is recommended to avoid working with incorrect data, or also that it receives several parameters, for example, to add them:
def sum(a:int, b:int, c:int):
print("res "+str(a+b+c))
sum(1,2,3)Or perform mathematical operations:
def operations(a:int, b:int, op:str):
if op == '+':
print("res "+str(a+b))
elif op == '-':
print("res "+str(a-b))
elif op == '*':
print("res "+str(a*b))
elif op == '/':
print("res "+str(a/b))
operations(1,2,'+')Also, we can define default values:
def operations(a:int, b:int, op:str='*'):
***And we can indicate the name of the parameters when invoking the function:
operations(b=2,a=5)With the advantage that we can place them in any order:
operations(a=5,b=2)These functions can also return a value, so that we can then use it wherever we want, for this, we can use the reserved word return:
def operations(a:int, b:int, op:str='*'):
if op == '+':
return a+b
elif op == '-':
return a-b
elif op == '*':
return a*b
else:
return a/b
n = operations(b=5,a=2)
print("res "+str(n))Also the return type, in this example, would be a float (due to the division):
def operations(a:int, b:int, op:str='*') -> float:
if op == '+':
return a+b
elif op == '-':
return a-b
elif op == '*':
return a*b
else:
return a/bTherefore, you can see a function as a piece of code designed to perform a task and, if necessary, return a value that is the product of the operation performed.
Later, when we want to return an HTML page to the user, functions are used that return said HTML pages, but we will see this later.
Classes and Objects
Python is an object-oriented language. Classes are like "blueprints" for creating objects. An object is an instance of a class.
class Car:
# The __init__ constructor method is called when an object is created
def __init__(self, brand: str, model: str, year: int):
self.brand = brand
self.model = model
self.year = year
self.started = False
def description(self) -> str:
return f"Car: {self.brand} {self.model} of {self.year}"
def start(self):
if not self.started:
self.started = True
print("The car has been started.")
else:
print("The car was already started.")
# Create instances (objects) of the Car class
my_car = Car("Toyota", "Corolla", 2022)
another_car = Car("Ford", "Mustang", 1969)
# Access attributes and call methods
print(my_car.description())
my_car.start()
my_car.start()You can see that the reserved word class is present, and this is because in Python everything is an object that is nothing more than an instance of a class:
class MyClass:
passClasses are nothing more than a blueprint in which we can create all kinds of objects that represent the real world, such as its primitives, integers, floats, text strings or for example, we can create a class that represents a car:
class Car:
passOr an animal:
class Animal:
passAs you can see, in both cases the reserved word class is used to mark that code as a class.
An empty class is not very useful to us, for it to be functional, we can define variables and functions within the classes, when we define variables and functions within a class, these are called attributes and methods respectively:
class Car:
brand='MyBrand'
model='MyModel'
price=50.2
def getCompleteDescription(self):
return f"{self.brand} - {self.model} - {self.price}"The reserved word self refers to the instance of the class with which you can access its attributes and methods.
For the previous code, we can create an instance, which is nothing more than a variable that we can manipulate at will, for example, create an instance for some type of car that we are going to manipulate in an application:
>>> car = Car()And with this, access its methods and properties:
>>> print(car.brand)
>>> print(car.getCompleteDescription())
MyBrand
MyBrand - MyModel - 50.2Methods and properties are the way we have to customize the class, for example, to change the brand:
car = Car()
car.brand='OtherBrand'
print(car.brand)
print(car.getCompleteDescription())Or use the class's constructor method, which would be the __init__() method in which the arguments are supplied:
class Car:
# brand='MyBrand'
# model='MyModel'
# price=50.2
def __init__(self,brand,model,price):
self.brand=brand
self.model=model
self.price=price
def getCompleteDescription(self):
return f"{self.brand} - {self.model} - {self.price}"
car = Car('OtherBrand','OtherModel',100)
# car.brand='OtherBrand'
print(car.brand)
print(car.getCompleteDescription())By using the class constructor, it is not necessary to define the arguments from the class, they are created automatically from the constructor.
Inheritance
Inheritance allows one class (child) to inherit attributes and methods from another class (parent).
class Animal:
def __init__(self, name: str):
self.name = name
def speak(self):
# This method will be overridden by the child classes
raise NotImplementedError("The child class must implement this method")
class Dog(Animal):
def speak(self):
return f"{self.name} says: Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says: Meow!"
my_dog = Dog("Fido")
my_cat = Cat("Misi")
print(my_dog.speak())
print(my_cat.speak())In the previous example, we have an Animal class that has common characteristics for an animal, then, we create two classes Dog and Bird to represent dogs and birds, which are animals and therefore, inherit from the Animal class and with this its attributes and methods, which are overwritten and we can even implement custom methods and attributes such as other() that are not part of the Animal class.
The use of classes and inheritance is fundamental in frameworks since there are predefined classes by the framework to define models, controllers/views, among other types and that can then be customized while preserving the default behavior.
Modules
Modules are .py files that contain reusable code (functions, classes, variables). You can import them into other files to use their functionality.
Modules in Python are a crucial part of the programming language and what differentiate it from other programming languages and what allows Python to be a modular programming language in which the frameworks implemented in said language are taken advantage of.
Modules allow code to be easily reused between other files that correspond to the project.
A module in Python is nothing more than a file with a .py extension that can contain a set of functions, variables or classes that we can then use from other files that import said module.
Modules can use other modules, which facilitates code reuse and application modularization.
Create a module
Imagine you have a file my_math.py:
# my_math.py
PI = 3.14159
def add(a, b):
return a + b
def subtract(a, b):
return a - bImport a module
Using import, we can import all the content of the module defined above.
You can use this module in another file, for example main.py:
# main.py
import my_math
sum_result = my_math.add(5, 3)
print(f"The sum is: {sum_result}")
print(f"The value of PI is: {my_math.PI}")
# You can also import only specific parts
from my_math import subtract
subtraction_result = subtract(10, 4)
print(f"The subtraction is: {subtraction_result}")The if __name__ == "__main__": block
It is good practice to place the code that should only be executed when the file is the main program (and not when it is imported) inside this block.
# my_math.py
PI = 3.14159
def add(a, b):
return a + b
# This block is only executed if you run "python my_math.py"
if __name__ == "__main__":
print("This is the math module.")
print("Testing the add function...")
result = add(10, 20)
print(f"10 + 20 = {result}")And in this way, we can reuse the mathematical operations module from anywhere in the application.
Modules are a fundamental part of frameworks, which, being organized in various folders according to the layers defined to represent each of the components of the MVC or MTV, the handling of routes, among others, the way to unite all these layers is through modules that we are going to import in specific parts of the framework
Modules are also used in frameworks to import the different features of the framework and associated packages and to be able to use them.