PRIMEROS PASOS EN PYTHON

INTRODUCCION A PYTHON

Python es un lenguaje de programación de alto nivel, interpretado y multipropósito creado por Guido van Rossum en 1991. #CARACTERISTICAS DE PYTHON Su sintaxis clara y legible que prioriza la simplicidad.

# VERSION 
import sys
# INFORMACION COMPLETA
print(f"Python version: {sys.version}")
## Python version: 3.11.13 (main, Jul 11 2025, 22:36:59) [MSC v.1944 64 bit (AMD64)]

DIRECTORIO DE TRABAJO

import os 
# OBSERVAR DIRECTORIO
print(os.getcwd())
## C:\Users\magno\Downloads\MAGNO ITALO V.Q
# CAMBIAR DIRECTORIO
os.chdir("C:/Users/magno/Downloads/MAGNO ITALO V.Q")
print("Directorio cambiado:", os.getcwd())
## Directorio cambiado: C:\Users\magno\Downloads\MAGNO ITALO V.Q
# ASIGNAR EL DIRECTORIO AUTOMATICAMENTE DONDE SE ENCUENTRA EL DOCUMENTO GUARDADO.
try:
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    print("Directorio automático:", os.getcwd())
except NameError:
    print("__file__ no está disponible en este entorno")
## __file__ no está disponible en este entorno

Operaciones basicas

# Suma
print("9 + 7 =", 9 + 7)
## 9 + 7 = 16
# Resta  
print("85 - 41 =", 85 - 41)
## 85 - 41 = 44
# Multiplicación
print("8 * 5 =", 8 * 5)
## 8 * 5 = 40
# División
print("51 / 7 =", 51 / 7)
## 51 / 7 = 7.285714285714286
# Paréntesis modifica el orden
print("87 / (5 + 9) =", 87 / (5 + 9))
## 87 / (5 + 9) = 6.214285714285714
# Potenciación (con **)
print("6 ** 3 =", 6 ** 3)
## 6 ** 3 = 216
# Resto (módulo)
print("17 % 5 =", 17 % 5)
## 17 % 5 = 2
# División entera
print("17 // 5 =", 17 // 5)
## 17 // 5 = 3

Funciones basicas

import math

# Raíz cuadrada
print("sqrt(73) =", math.sqrt(73))
## sqrt(73) = 8.54400374531753
# Valor absoluto
print("abs(-73) =", abs(-73))
## abs(-73) = 73
# Función trigonométrica - seno(pi/2)
print("sin(pi/2) =", math.sin(math.pi/2))
## sin(pi/2) = 1.0
# Función trigonométrica - coseno(0)
print("cos(0) =", math.cos(0))
## cos(0) = 1.0
# Logaritmo natural
print("log(10) =", math.log(10))
## log(10) = 2.302585092994046
# Logaritmo base 10
print("log10(100) =", math.log10(100))
## log10(100) = 2.0
# Logaritmo base 4
print("log(10, base=4) =", math.log(10, 4))
## log(10, base=4) = 1.6609640474436813
# Exponencial
print("exp(1) =", math.exp(1))
## exp(1) = 2.718281828459045
# Redondeo
print("round(pi, 2) =", round(math.pi, 2))
## round(pi, 2) = 3.14

Notacion cientifica

# Número grande
print("2324511042900 =", 2324511042900)
## 2324511042900 = 2324511042900
# Número muy pequeño  
print("0.000000002581 =", 0.000000002581)
## 0.000000002581 = 2.581e-09
# Forzar notación científica
print("Notación científica de 123456:", format(123456, '.2e'))
## Notación científica de 123456: 1.23e+05
# Suprimir notación científica (mostrar completo)
print("Sin notación científica:", format(2324511042900, 'f'))
## Sin notación científica: 2324511042900.000000
# Restaurar notación científica automática
print("Notación automática:", 2324511042900)
## Notación automática: 2324511042900

Sistema de ayuda

import math
import inspect

# 1. Ayuda en funciones específicas
print("=== AYUDA DE math.sqrt ===")
## === AYUDA DE math.sqrt ===
help(math.sqrt)
## Help on built-in function sqrt in module math:
## 
## sqrt(x, /)
##     Return the square root of x.
# 2. Ayuda sobre operadores
print("\n=== AYUDA DEL OPERADOR ** ===")
## 
## === AYUDA DEL OPERADOR ** ===
help('**')
## The power operator
## ******************
## 
## The power operator binds more tightly than unary operators on its
## left; it binds less tightly than unary operators on its right.  The
## syntax is:
## 
##    power ::= (await_expr | primary) ["**" u_expr]
## 
## Thus, in an unparenthesized sequence of power and unary operators, the
## operators are evaluated from right to left (this does not constrain
## the evaluation order for the operands): "-1**2" results in "-1".
## 
## The power operator has the same semantics as the built-in "pow()"
## function, when called with two arguments: it yields its left argument
## raised to the power of its right argument.  The numeric arguments are
## first converted to a common type, and the result is of that type.
## 
## For int operands, the result has the same type as the operands unless
## the second argument is negative; in that case, all arguments are
## converted to float and a float result is delivered. For example,
## "10**2" returns "100", but "10**-2" returns "0.01".
## 
## Raising "0.0" to a negative power results in a "ZeroDivisionError".
## Raising a negative number to a fractional power results in a "complex"
## number. (In earlier versions it raised a "ValueError".)
## 
## This operation can be customized using the special "__pow__()" method.
## 
## Related help topics: EXPRESSIONS, OPERATORS
# 3. Argumentos de funciones
print("\n=== ARGUMENTOS DE FUNCIONES ===")
## 
## === ARGUMENTOS DE FUNCIONES ===
print("Argumentos de abs:", inspect.signature(abs))
## Argumentos de abs: (x, /)
print("Argumentos de round:", inspect.signature(round))
## Argumentos de round: (number, ndigits=None)
print("Argumentos de math.sqrt:", inspect.signature(math.sqrt))
## Argumentos de math.sqrt: (x, /)

Aplicaciones numéricas, aritmética y asignación

Asignacion

# Asignación tradicional
x = 20
print("x =", x)
## x = 20
# Método alternativo (igual)
y = 30  
print("y =", y)
## y = 30
# Asignación normal (no existe -> en Python)
z = 40
print("z =", z)
## z = 40
# Mostrar inmediatamente (en dos pasos)
w = 50
print("w =", w)
## w = 50

Palabras reservadas

True,False,None…

import numpy as np

# Palabras reservadas equivalentes
True    # TRUE
## True
False   # FALSE
## False
None    # NULL/NA  
np.inf  # INF (mejor que float('inf'))
## inf
np.nan  # NaN (mejor que float('nan'))
## nan
# Mostrar valores
print("True =", True)
## True = True
print("False =", False)
## False = False
print("None =", None)
## None = None
print("Infinito =", np.inf)
## Infinito = inf
print("NaN =", np.nan)
## NaN = nan

Gestión del workspace

# Listar todo lo que se tiene guardado
print("Variables en memoria:", list(globals().keys()))
## Variables en memoria: ['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'r', 'sys', 'os', 'math', 'inspect', 'x', 'y', 'z', 'w', 'np']
# Obtener información (estructura) de un objeto
x = "hola"
print("Tipo de x:", type(x))
## Tipo de x: <class 'str'>
print("Estructura de x:", dir(x))
## Estructura de x: ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

# Eliminar objetos específicos
y = 10
del y  # Equivalente a rm(y)

# Eliminar todo (cuidado con esto)
globals_copy = globals().copy()
for var in globals_copy:
    if not var.startswith('_'):  # No eliminar variables especiales
        del globals()[var]

Vectores y escalares

Escalar

# Asignar escalar (en Python es igual para escalares y vectores)
edad = 20

# Mostrar el valor
print(edad)
## 20

Vector

Es una secuencia de datos, que tiene un mismo tipo de dato

import math

# Creación de un vector (lista en Python)
vector = [21, 23, 25, 27, 29]
print("vector =", vector)
## vector = [21, 23, 25, 27, 29]
# Crear un vector de caracteres
color = ["rojo", "Azul", "verde"]
print("color =", color)
## color = ['rojo', 'Azul', 'verde']
# Crear un vector a partir de cálculos
vector3 = [74 + 5, math.sqrt(25), abs(-23), 84 / 7]
print("vector3 =", vector3)
## vector3 = [79, 5.0, 23, 12.0]
# Combinar vectores
v1 = [1, 2, 3]
v2 = [4, 5, 6]
v3 = v1 + v2  # ¡OJO! Esto concatena en Python
print("v3 =", v3)
## v3 = [1, 2, 3, 4, 5, 6]
# Clase/tipo de un vector
print("Clase de vector:", type(vector))
## Clase de vector: <class 'list'>
print("Clase de vector3:", type(vector3))
## Clase de vector3: <class 'list'>
print("Clase de color:", type(color))
## Clase de color: <class 'list'>
print("Clase de v3:", type(v3))
## Clase de v3: <class 'list'>
# Crear vector con número y texto (se convierte todo a texto)
vector4 = [40, "Hola", "vector"]
print("vector4 =", vector4)
## vector4 = [40, 'Hola', 'vector']
# Ver la clase/tipo del vector
print("Clase de vector4:", type(vector4))
## Clase de vector4: <class 'list'>
# Ver el tipo de cada elemento
print("Tipo de cada elemento:")
## Tipo de cada elemento:
for i, elemento in enumerate(vector4):
    print(f"Elemento {i}: {elemento} - Tipo: {type(elemento)}")
## Elemento 0: 40 - Tipo: <class 'int'>
## Elemento 1: Hola - Tipo: <class 'str'>
## Elemento 2: vector - Tipo: <class 'str'>
# Usando numpy
import numpy as np

# Con numpy sí se convierte todo al mismo tipo (como en R)
vector4_np = np.array([40, "Hola", "vector"])
print("vector4_np =", vector4_np)
## vector4_np = ['40' 'Hola' 'vector']
print("Clase de vector4_np:", type(vector4_np))
## Clase de vector4_np: <class 'numpy.ndarray'>
print("Tipo de datos:", vector4_np.dtype)  # Mostrará '<U5' (texto)
## Tipo de datos: <U21

Operador para secuencias

# Secuencias enteras
secuencia1 = list(range(1, 11))
print("1 al 10:", secuencia1)
## 1 al 10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Secuencia descendente  
secuencia2 = list(range(15, 9, -1))
print("15 al 10:", secuencia2)
## 15 al 10: [15, 14, 13, 12, 11, 10]
# Con negativos
secuencia3 = list(range(-5, 6))
print("-5 al 5:", secuencia3)
## -5 al 5: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
# Con decimales (necesitas numpy)
import numpy as np
secuencia4 = np.arange(1.5, 5.9, 1)  # 1.5, 2.5, 3.5, 4.5
print("1.5 a 5.8:", secuencia4)
## 1.5 a 5.8: [1.5 2.5 3.5 4.5 5.5]

Utilizando la función seq

import numpy as np

# 1. Por incremento específico (by)
secuencia1 = np.arange(0, 11, 2)  # 0, 2, 4, 6, 8, 10
print("by=2:", secuencia1)
## by=2: [ 0  2  4  6  8 10]
secuencia2 = np.arange(0, 10.1, 0.2)  # 0.0, 0.2, 0.4, ..., 10.0
print("by=0.2:", secuencia2[:5], "...", secuencia2[-5:])  # Muestra inicio y fin
## by=0.2: [0.  0.2 0.4 0.6 0.8] ... [ 9.2  9.4  9.6  9.8 10. ]
# 2. Por número de elemento (length.out)
secuencia3 = np.linspace(0, 10, 20)  # 20 elementos entre 0 y 10
print("length.out=20:", secuencia3)
## length.out=20: [ 0.          0.52631579  1.05263158  1.57894737  2.10526316  2.63157895
##   3.15789474  3.68421053  4.21052632  4.73684211  5.26315789  5.78947368
##   6.31578947  6.84210526  7.36842105  7.89473684  8.42105263  8.94736842
##   9.47368421 10.        ]
# 3. Secuencia descendente
secuencia4 = np.arange(10, -1, -1)  # 10, 9, 8, ..., 0
print("descendente:", secuencia4)
## descendente: [10  9  8  7  6  5  4  3  2  1  0]

Función de repetición

import numpy as np

# 1. Repetir un valor
resultado1 = np.repeat(20, 5)
print("rep(20, times=5):", resultado1)
## rep(20, times=5): [20 20 20 20 20]
# 2. Repetir un vector completo (each)
resultado2 = np.repeat([21, 23], 3)
print("rep([21,23], each=3):", resultado2)
## rep([21,23], each=3): [21 21 21 23 23 23]
# 3. Combinar times y each
vector = ["Rojo", "Azul"]
# Primero each: repetir cada elemento 2 veces
temp = np.repeat(vector, 2)
# Luego times: repetir toda la secuencia 3 veces
resultado3 = np.tile(temp, 3)
print('rep(["Rojo","Azul"], times=3, each=2):', resultado3)
## rep(["Rojo","Azul"], times=3, each=2): ['Rojo' 'Rojo' 'Azul' 'Azul' 'Rojo' 'Rojo' 'Azul' 'Azul' 'Rojo' 'Rojo'
##  'Azul' 'Azul']

Indexación

# Longitud de un vector
vector5 = [14, 15, 18, 19, 21]
print("Longitud del vector:", len(vector5))
## Longitud del vector: 5
# Extraer elementos (¡OJO! Python empieza en 0, no en 1)
print("Elemento posición 1 (índice 0):", vector5[0])     
## Elemento posición 1 (índice 0): 14
# R: posición 1
print("3er elemento (índice 2):", vector5[2])           
## 3er elemento (índice 2): 18
# R: posición 3

# Extraer secuencia de elementos
print("Elementos 2 al 4 (índices 1:3):", vector5[1:4])  
## Elementos 2 al 4 (índices 1:3): [15, 18, 19]
# R: 2:4

# Extraer elementos específicos
print("Elementos 1, 3 y 5 (índices 0,2,4):", [vector5[0], vector5[2], vector5[4]])
## Elementos 1, 3 y 5 (índices 0,2,4): [14, 18, 21]
# Extraer en orden inverso (excluir primer elemento)
print("Sin el primer elemento:", vector5[1:])           
## Sin el primer elemento: [15, 18, 19, 21]
# R: -1
# Lo mismo al anterior solo que se puede hacer de 2 maneras 
vector5 = [14, 15, 18, 19, 21]

print("Vector completo:", vector5)
## Vector completo: [14, 15, 18, 19, 21]
print("Longitud:", len(vector5))
## Longitud: 5
# Extracciones
print("\n=== EXTRACCIONES ===")
## 
## === EXTRACCIONES ===
print("Posición 1 (índice 0):", vector5[0])
## Posición 1 (índice 0): 14
print("Posición 3 (índice 2):", vector5[2])  
## Posición 3 (índice 2): 18
print("Posiciones 2-4 (índices 1-3):", vector5[1:4])
## Posiciones 2-4 (índices 1-3): [15, 18, 19]
print("Posiciones 1,3,5 (índices 0,2,4):", [vector5[0], vector5[2], vector5[4]])
## Posiciones 1,3,5 (índices 0,2,4): [14, 18, 21]
print("Sin primer elemento:", vector5[1:])
## Sin primer elemento: [15, 18, 19, 21]

Matrices y arreglos

import numpy as np

# 1. Matriz por columnas (como byrow=FALSE en R)
matriz_columnas = np.arange(1, 17).reshape(4, 4)
print("Por columnas:")
## Por columnas:
print(matriz_columnas)
## [[ 1  2  3  4]
##  [ 5  6  7  8]
##  [ 9 10 11 12]
##  [13 14 15 16]]
# 2. Matriz por filas (como byrow=TRUE en R)
matriz_filas = np.array([[1, 2, 3, 4],
                         [5, 6, 7, 8], 
                         [9, 10, 11, 12],
                         [13, 14, 15, 16]])
print("\nPor filas:")
## 
## Por filas:
print(matriz_filas)
## [[ 1  2  3  4]
##  [ 5  6  7  8]
##  [ 9 10 11 12]
##  [13 14 15 16]]
# 3. Asignar y mostrar
mi_matriz = matriz_filas
print("\nMi matriz:")
## 
## Mi matriz:
print(mi_matriz)
## [[ 1  2  3  4]
##  [ 5  6  7  8]
##  [ 9 10 11 12]
##  [13 14 15 16]]

Funciones basicas

Dimensiones

import numpy as np

# Crear una matriz de ejemplo (como antes)
mi_matriz = np.array([[1, 2, 3, 4],
                      [5, 6, 7, 8], 
                      [9, 10, 11, 12]])

# Obtener dimensiones
print("Matriz:")
## Matriz:
print(mi_matriz)
## [[ 1  2  3  4]
##  [ 5  6  7  8]
##  [ 9 10 11 12]]
print("\nNúmero de filas (nrow):", mi_matriz.shape[0])
## 
## Número de filas (nrow): 3
print("Número de columnas (ncol):", mi_matriz.shape[1])
## Número de columnas (ncol): 4
print("Dimensiones (shape):", mi_matriz.shape)
## Dimensiones (shape): (3, 4)
import numpy as np
# Indexación
# Crear matriz 4x5 (1 al 20 por filas)
matrix2 = np.array([[1, 2, 3, 4, 5],
                    [6, 7, 8, 9, 10],
                    [11, 12, 13, 14, 15], 
                    [16, 17, 18, 19, 20]])
print("Matriz:")
## Matriz:
print(matrix2)
## [[ 1  2  3  4  5]
##  [ 6  7  8  9 10]
##  [11 12 13 14 15]
##  [16 17 18 19 20]]
# Extrer el 7
print(f"\nElemento [2,2] en R = {matrix2[1, 1]} (índices [1,1] en Python)")
## 
## Elemento [2,2] en R = 7 (índices [1,1] en Python)
# Extrer el 7
print(f"Elemento [4,5] en R = {matrix2[3, 4]} (índices [3,4] en Python)")
## Elemento [4,5] en R = 20 (índices [3,4] en Python)

Broadcasting (operaciones)

import numpy as np

# Crear matriz de ejemplo
matriz2 = np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]])

print("Matriz original:")
## Matriz original:
print(matriz2)
## [[1 2 3]
##  [4 5 6]
##  [7 8 9]]
# Operaciones aritméticas elemento por elemento
print("\n=== OPERACIONES ===")
## 
## === OPERACIONES ===
print("Matriz + 10:")
## Matriz + 10:
print(matriz2 + 10)
## [[11 12 13]
##  [14 15 16]
##  [17 18 19]]
print("\nMatriz ** 2 (al cuadrado):")
## 
## Matriz ** 2 (al cuadrado):
print(matriz2 ** 2)
## [[ 1  4  9]
##  [16 25 36]
##  [49 64 81]]
print("\nMatriz * 2 (multiplicar por 2):")
## 
## Matriz * 2 (multiplicar por 2):
print(matriz2 * 2)
## [[ 2  4  6]
##  [ 8 10 12]
##  [14 16 18]]

Multiplicación matricial

import numpy as np

# Matriz 1: 4x3 (valores 1-12)
matrizi = np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9],
                    [10, 11, 12]])

# Matriz 2: 3x4 (valores 13-24)  
matrizz = np.array([[13, 14, 15, 16],
                    [17, 18, 19, 20],
                    [21, 22, 23, 24]])

print("matrizi (4x3):")
## matrizi (4x3):
print(matrizi)
## [[ 1  2  3]
##  [ 4  5  6]
##  [ 7  8  9]
##  [10 11 12]]
print("\nmatrizz (3x4):")
## 
## matrizz (3x4):
print(matrizz)
## [[13 14 15 16]
##  [17 18 19 20]
##  [21 22 23 24]]
# Multiplicación matricial (resultado será 4x4)
resultado = np.dot(matrizi, matrizz)
print("\nResultado (4x4):")
## 
## Resultado (4x4):
print(resultado)
## [[110 116 122 128]
##  [263 278 293 308]
##  [416 440 464 488]
##  [569 602 635 668]]

Data frame

import numpy as np
# Crear matriz sin pandas
matriz = np.arange(1, 17).reshape(4, 4)
print("Matriz:")
## Matriz:
print(matriz)
## [[ 1  2  3  4]
##  [ 5  6  7  8]
##  [ 9 10 11 12]
##  [13 14 15 16]]
# Versión con listas nativas (sin pandas)
datos = {
    'nombre': ['Maryorie', 'Jorge'],
    'edad': [20, 22]
}

print("Datos como diccionario:")
## Datos como diccionario:
print(datos)
## {'nombre': ['Maryorie', 'Jorge'], 'edad': [20, 22]}

##Fin