Português
🐍 Python for beginners and beyond

Python Programming Tutorial

From broad concepts to specific topics, all in one place.

1. What programming is and why Python

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:

2. Installation and your first program

Download Python from the official python.org website and install it. To verify the installation, open a terminal and run:

python --version

The traditional first program prints a message:

# Save as hello.py and run: python hello.py
print("Hello, world!")
💡 Tip: print() displays text in the terminal. Everything after # is a comment and is ignored by Python.

3. Variables and data types

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)
TypeDescriptionExample
intInteger42
floatDecimal number3.14
strText string"Hello"
boolLogical valueTrue / False

4. Operators and expressions

# 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)          # False

5. Conditional statements

Conditionals 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")

6. Loops

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

7. Collections: lists, tuples, dictionaries and sets

# 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}
CollectionOrdered?Mutable?Duplicates?
ListYesYesYes
TupleYesNoYes
DictionaryYes (3.7+)YesUnique keys
SetNoYesNo

8. Functions

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))         # 10

9. Modules and packages

Modules 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)

10. File handling

# 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)
💡 The with block closes the file automatically when the block ends, even if an error occurs.

11. Exception handling

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.")

12. Object-oriented programming (OOP)

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())

13. Specific and advanced topics

List comprehensions

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]

Generators and iterators

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)

Decorators

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")

Type hints

def average(numbers: list[float]) -> float:
    return sum(numbers) / len(numbers)

print(average([8.0, 9.5, 7.0]))

Virtual environments and project organization

# 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.txt

14. Next steps

Once you have the fundamentals, explore the area that matches your goals:

🚀 The best way to learn is by practicing. Build small projects, read other people's code and consult the official Python documentation.
← Back to Tech