Skip to main content

Introduction

Python is a powerful, versatile programming language that’s perfect for data science. This module covers the essential building blocks you’ll need to start writing Python code.

Variables and Data Types

Understanding Variables

Variables in Python are used to store data. Unlike some languages, Python uses dynamic typing, meaning you don’t need to declare the type explicitly.
EDAD_JUBILACION = 60
NOTA_MINIMA = 4.0

# Solicitar nombre y edad
nombre = "Ingrid"
edad_texto = "30"
edad = int(edad_texto)  # Conversión a int

# Años faltantes para jubilarse
faltan = EDAD_JUBILACION - edad
ya_jubilado = (faltan <= 0)
Best Practice: Use UPPERCASE for constants (values that shouldn’t change) and lowercase for regular variables.

Common Data Types

  • int: Integer numbers (e.g., 30, -5, 1000)
  • float: Decimal numbers (e.g., 4.0, 3.14, -2.5)
  • bool: Boolean values (True or False)
edad = 30  # int
promedio = 4.5  # float
aprueba = True  # bool
Strings are sequences of characters enclosed in quotes.
nombre = "Ingrid"
categoria = 'estudiante'
mensaje = """Este es un
texto multilínea"""
  • list: Ordered, mutable collection
  • dict: Key-value pairs
  • tuple: Ordered, immutable collection
inventario = [
    {"nombre": "laptop", "precio": 800, "stock": 5},
    {"nombre": "mouse", "precio": 25, "stock": 0},
    {"nombre": "teclado", "precio": 45, "stock": 10}
]

Control Flow

Conditional Statements

Control the flow of your program based on conditions using if, elif, and else.
# Simple conditional
if aprueba:
    print("Estado:", "Aprueba ✅")
else:
    print("Estado:", "Reprueba ❌")
Logical Operators: Use and, or, and not to combine multiple conditions. Use parentheses for clarity.

Input Validation

Always validate user input to prevent errors:
# Validar entrada numérica
edad_txt = input("Ingrese su edad: ")

if not edad_txt.isdigit():
    print("❌ Edad inválida. Debes ingresar un número entero (ej: 20).")
    raise SystemExit

edad = int(edad_txt)

Functions

Defining Functions

Functions help organize code into reusable blocks:
def calcular_imc(peso, altura):
    """Calcula el IMC usando la fórmula: peso / altura al cuadrado."""
    return peso / (altura ** 2)

# Uso
valor_imc = calcular_imc(75, 1.75)
print(f"Tu IMC es: {valor_imc:.2f}")
The if __name__ == "__main__": pattern ensures code only runs when the file is executed directly, not when imported as a module.

Functional Programming Concepts

Lambda Functions and Higher-Order Functions

Python supports functional programming with lambda functions, map(), filter(), and reduce():
from functools import reduce

# Lista de productos
inventario = [
    {"nombre": "laptop", "precio": 800, "stock": 5},
    {"nombre": "mouse", "precio": 25, "stock": 0},
    {"nombre": "teclado", "precio": 45, "stock": 10},
    {"nombre": "monitor", "precio": 150, "stock": 3}
]

def obtener_disponibles(lista):
    """Filtra productos que están en stock."""
    return list(filter(lambda producto: producto["stock"] > 0, lista))

def formatear_nombres(lista):
    """Formatea los nombres de los productos a mayúsculas."""
    return list(map(lambda producto: producto["nombre"].upper(), lista))

def calcular_valor_total(lista):
    """Calcula el valor total del inventario disponible."""
    return reduce(
        lambda total, producto: total + (producto["precio"] * producto["stock"]), 
        lista, 
        0
    )

# Uso
disponibles = obtener_disponibles(inventario)
nombres_formateados = formatear_nombres(disponibles)
valor_total = calcular_valor_total(disponibles)

print("Productos disponibles:", nombres_formateados)
print("Valor total del inventario:", valor_total)
Lambda functions are anonymous functions defined in a single line:
# Lambda function
cuadrado = lambda x: x ** 2

# Equivalent regular function
def cuadrado(x):
    return x ** 2
Use lambda for simple operations, especially with map(), filter(), and sorted().

Best Practices

Use Descriptive Names

Choose variable and function names that clearly describe their purpose.
# Good
edad_jubilacion = 60

# Avoid
x = 60

Add Docstrings

Document your functions with docstrings.
def calcular_imc(peso, altura):
    """Calcula el IMC usando la fórmula: 
    peso / altura al cuadrado."""
    return peso / (altura ** 2)

Handle Errors

Use try-except blocks to handle potential errors gracefully.
try:
    edad = int(input("Edad: "))
except ValueError:
    print("Por favor ingresa un número")

Validate Input

Always validate user input before processing.
if not edad_txt.isdigit():
    print("❌ Entrada inválida")
    return

Practice Exercises

Create a program that:
  1. Takes three grades as input
  2. Calculates the average
  3. Determines if the student passes (average >= 4.0)
  4. Prints a formatted result
Hint: Use float(input()) for input and conditional statements for evaluation.
Write a function that takes an age and returns the appropriate category:
  • 0-12: “niño/a”
  • 13-17: “adolescente”
  • 18-59: “adulto/a”
  • 60+: “adulto/a mayor”
Hint: Use if-elif-else statements.
Given a list of product dictionaries, write functions to:
  1. Filter products with stock > 0
  2. Convert product names to uppercase
  3. Calculate total inventory value
Hint: Use filter(), map(), and reduce().

Next Steps

Now that you understand Python basics, you’re ready to explore:

Object-Oriented Programming

Learn about classes, objects, and inheritance

Python Projects

Build real-world applications with Python

Build docs developers (and LLMs) love