From broad concepts to specific topics, all in one place.
Programming means writing instructions that a computer executes to solve a problem. Those instructions are written in a programming language, which acts as an interface between human reasoning and machine execution.
Python is a high-level, interpreted, general-purpose language known for readable, clear syntax. It is widely used in web development, data science, automation, artificial intelligence and many other fields. Its main advantages include:
Download Python from the official python.org website and install it. To verify the installation, open a terminal and run:
python --versionThe traditional first program prints a message:
# Save as hello.py and run: python hello.py
print("Hello, world!")print() displays text in the terminal. Everything after # is a comment and is ignored by Python.A variable is a name that points to a value stored in memory. Python does not require you to declare the type in advance; it is inferred automatically.
name = "Maria" # str (text)
age = 30 # int (integer)
height = 1.65 # float (decimal number)
student = True # bool (true/false)
print(name, age, height, student)| Type | Description | Example |
|---|---|---|
int | Integer | 42 |
float | Decimal number | 3.14 |
str | Text string | "Hello" |
bool | Logical value | True / False |
# Arithmetic
addition = 10 + 3 # 13
division = 10 / 3 # 3.333...
floor_div = 10 // 3 # 3
remainder = 10 % 3 # 1
power = 2 ** 8 # 256
# Comparisons (return bool)
print(10 > 3) # True
print(5 == 5) # True
print(7 != 2) # True
# Logical operators
print(True and False) # False
print(True or False) # True
print(not True) # FalseConditionals execute different blocks depending on a condition. In Python, indentation defines the blocks.
age = 18
if age < 12:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")Loops repeat instructions. The main forms are for and while.
# for: iterate over a sequence
for i in range(1, 6):
print("Number:", i)
# while: repeat while the condition is true
counter = 0
while counter < 3:
print("Counting", counter)
counter += 1
# break stops; continue skips to the next iteration
for n in range(10):
if n == 5:
break
if n % 2 == 0:
continue
print(n) # prints 1, 3# List: ordered and mutable
fruits = ["apple", "banana", "grape"]
fruits.append("orange")
print(fruits[0])
# Tuple: ordered and immutable
point = (10, 20)
# Dictionary: key-value pairs
person = {"name": "Ana", "age": 25}
print(person["name"])
# Set: unique, unordered elements
numbers = {1, 2, 2, 3}
print(numbers) # {1, 2, 3}| Collection | Ordered? | Mutable? | Duplicates? |
|---|---|---|---|
| List | Yes | Yes | Yes |
| Tuple | Yes | No | Yes |
| Dictionary | Yes (3.7+) | Yes | Unique keys |
| Set | No | Yes | No |
Functions group reusable code. Use def to define one and return to return a result.
def greeting(name, message="Hello"):
return f"{message}, {name}!"
print(greeting("Carlos"))
print(greeting("Ana", "Welcome"))
# Variable number of arguments
def add(*numbers):
return sum(numbers)
print(add(1, 2, 3, 4)) # 10
# Lambda (anonymous) function
double = lambda x: x * 2
print(double(5)) # 10Modules organize and reuse code. Python's standard library already includes many ready-to-use modules.
import math
print(math.sqrt(16))
from datetime import date
print(date.today())
# Install external packages in the terminal:
# pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code)# Write a file
with open("data.txt", "w", encoding="utf-8") as file:
file.write("First line\n")
file.write("Second line\n")
# Read a file
with open("data.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)with block closes the file automatically when the block ends, even if an error occurs.Exceptions are errors that occur during execution. Handle them with try/except.
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)
except ValueError:
print("That is not a valid number!")
except ZeroDivisionError:
print("Division by zero is not allowed!")
finally:
print("Operation completed.")OOP organizes code around classes (templates) and objects (instances), combining attributes (data) and methods (behavior).
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
return "Generic sound"
class Dog(Animal):
def make_sound(self):
return "Woof!"
rex = Dog("Rex")
print(rex.name)
print(rex.make_sound())squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
evens = [x for x in range(20) if x % 2 == 0]def counter(maximum):
n = 0
while n < maximum:
yield n # produce values on demand, saving memory
n += 1
for value in counter(3):
print(value)def log_call(function):
def inner(*args, **kwargs):
print(f"Calling {function.__name__}")
return function(*args, **kwargs)
return inner
@log_call
def greet(name):
print(f"Hello, {name}")
greet("Maria")def average(numbers: list[float]) -> float:
return sum(numbers) / len(numbers)
print(average([8.0, 9.5, 7.0]))# Create an isolated virtual environment
python -m venv venv
# Activate on Linux/macOS
source venv/bin/activate
# Activate on Windows
venv\Scripts\activate
# Install and record dependencies
pip install requests
pip freeze > requirements.txtOnce you have the fundamentals, explore the area that matches your goals: