0% encontró este documento útil (0 votos)
17 vistas28 páginas

Estructuras y Lazos en Python

tema de clases semana 2
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
17 vistas28 páginas

Estructuras y Lazos en Python

tema de clases semana 2
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd

27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

Estructuras de control y lazos de


repetición

Autor: Luis A. Muñoz - 2024

Ideas clave:
Los bloques de código de Python se inician con el caracter ":" y se limitan con el Tab
(sangría de 4 espacios)
Se pueden anidar bloques, aunque se prefiere utilizar conectores lógicos (and, or,
not) para reducir la lógica a una sola instrucción
El operador "is" evalua si dos objetos son lo mismo. El operador "==" evalua si dos
objetos son equivalentes
El operador "in" verifica si un objeto esta incluido en un contenedor (por ejemplo,
una lista)
Las instruccones for y while gestionan los iteradores
Los contenedores principales de Python (listas, tuplas, diccionarios...) son iterables.

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 1/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

La combinación de un lazo while con un control para romper el lazo con "break"
permite implementar un lazo "do... while"
La instrucción "else" puede incluirse en un lazo for o while para especificar las
instrucciones a realizar luego que el lazo de repetición se haya finalizado
correctamente

Informacion:

https://www.w3schools.com/python/python_conditions.asp
https://www.w3schools.com/python/python_while_loops.asp
https://www.w3schools.com/python/python_for_loops.asp

Estructura de control: if... elif... else


En programación, una estructura de control permite controlar el flujo de un programa en
función del resultado de una condición. Esta se realiza combinando la instrucción if
con operaciones lógicas y de relación.

La instrucción if realiza una operación que retornará True o False . Si el resultado


es True , se ejecutará el bloque definido luego de los :

Pruebe modificando el valor de num y observe los resultados del código en la celda
siguiente. (Recuerde, ejecute una celda de código presionando Ctrl + ENTER)

In [1]: num = 10
# Operador de relación
if num > 5:
print(f"* {num} es mayor que 5")

# Operador aritmetico (%) y logico (==)


if num % 2 == 0:
print(f"* {num} es par")

* 10 es mayor que 5
* 10 es par

Note que es mandatorio que exista un orden al momento de definir un bloque. Se


deben de respetar las sangrías (espacios de 4 caracteres) al momento de definir el
código. Ejecute la siguiente celda y observe la excepción generada ( IdentationError ).
Luego, corriga la celda para que se ejecute correctamente.

In [2]: num = 25

if num % 5 == 0:
if 0 <= num <= 10:
print("{} esta en el rango 0 a 25")
print(f"{num} es multiplo de 5")
print("Fin de programa")

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 2/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

Cell In[2], line 4


if 0 <= num <= 10:
^
IndentationError: expected an indented block after 'if' statement on line 3

Se puede incluir la instrucción else para considerar la opción de lo contario en la


estructura de control:

In [5]: num = 10

if num < 5:
print(f"* {num} es menor que 5")
else:
print(f"* {num} es mayor que 5")

print(f"* {num} es ", end='')


if num % 2 == 0:
print(f"par")
else:
print(f"impar")

* 10 es mayor que 5
* 10 es par

Así también, se puede incluir la instrucción elif para considerar otras posibles
condiciones a evaluar. Considere el código de la siguiente celda. Pruebe con varios
números y siga la lógica del script:

In [9]: num = 7

print("Propiedades del numero {num}:")

print(f"* {num} es un número ", end='')


if num < 0:
print("negativo")
else:
print("positivo")

print(f"* {num} es un numero ", end='')


if num % 2 == 0:
print("par")
else:
print("impar ", end='')
if num % 3 == 0:
print("multiplo de 3")
elif num % 5 == 0:
print("multiplo de 5")
elif num % 7 == 0:
print("multiplo de 7")

Propiedades del numero {num}:


* 7 es un número positivo
* 7 es un numero impar multiplo de 7

if anidados versus if planos

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 3/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

Una estructura de control anidada consiste en una cascada de operaciones, una dentro
de la otra. En el bloque if externo se considera una decision que, segun la condición,
ingresa a un bloque interno. De ser preferible, esta practica se debe evitar para mantener
el codigo simple, utilizando expresiones lógicas como conectores entre condiciones. Por
ejemplo, considere la evaluación de si un año es bisiesto:

"Año bisiesto es el divisible entre 4, salvo que sea año secular -último de cada siglo,
terminado en «00»-, en cuyo caso también ha de ser divisible entre 400". (Wikipedia)

Esto se puede expresar de la siguiente forma:

In [ ]: anio = int(input("Ingrese un año: "))

# Si el año es multiplo de 4 puede ser bisiesto


if anio % 4 == 0:
# Dependera de si termina en "00"
if anio % 100 == 0:
# Aunque si es multiplo de "400" es año es bisiesto
if anio % 400 == 0:
# Es bisiesto
print("El bisiesto")
else:
# Si termina en "00" y no es multiplo de "400" no es bisiesto
print("No es bisiesto")
else:
# Si es multiplo de 4 y no termina en "00" no es bisiesto
print("Es bisiesto")
else:
# Si no es mutiplo de "4" no es bisiesto sin mayores evaluaciones
print("No es bisiesto")

Compare el código anterior con el siguiente:

In [ ]: anio = int(input("Ingrese un año: "))

# Un año es bisiesto si es multiplo de "4" y no termina en "00"


# a menos que sea multiplo de "400"
if anio % 4 == 0 and (anio % 100 != 0 or anio % 400 == 0):
print("Es bisiesto")
else:
print("No es bisiesto")

Plano es mejor que anidado...

Palabras reservadas in e is
La palabra reservada in se utiliza en Python para verificar si un elemento es parte de un
conjunto de datos, por ejemplo una tupla o una lista. Considere el siguiente uso de in
con una tupla:

In [ ]: lista = ["alicia", "ernesto", "gustavo", "rosa", "andrea", "emilio"]


print("lista:", lista)
print()

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 4/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

print("* Esta 'alicia' en la lista:", "alicia" in lista)


print("* Esta 'raul' en la lista:", "raul" in lista)
print()

print("* Esta 'Gustavo' en la lista:", "Gustavo" in lista)


print("* Esta 'gustavo' en la lista:", "gustavo" in lista)
print()

print("* No esta 'alicia' en la lista:", "alicia" not in lista)


print("* No esta 'amalia' en la lista:", "amalia" not in lista)

Por ejemplo, se puede utilizar in para resolver lo siguiente:

In [ ]: num = int(input("Ingrese un numero entre 1 y 10"))

if num in [0, 2, 4, 6, 8, 10]:


print(f"{num} es par")
else:
print(f"{num} es impar")

Otra palabra reservada útil es is . Permite evaluar si un objeto es otro. Por ejemplo:

In [ ]: (3 * 6) is 18

Pero debe se utilizado con precaución: is no verifica si un objeto es igual a otro. Por
ejemplo:

In [11]: [1, 2, 3] is [1, 2, 3]

Out[11]: False

El operador == verifica si un objeto es igual a otro:

In [12]: [1, 2, 3] == [1, 2, 3]

Out[12]: True

Función range
La función range genera un rango de datos enteros. Formalmente hablando, genera
una construccion conocida como generador, es decir algo que genera valores en línea
que puede ser iterado por un lazo de repetición (al respecto, más adelante). Tiene la
siguiente sintaxis: range(start, end, step) :

range(10) genera un rango de 10 valores entre 0 y 9: 0, 1, 2, 3, 4, 5, 6,


7, 8, 9
range(1, 10) genera un rango de valores entre 1 y 9: 1, 2, 3, 4, 5, 6, 7,
8, 9
range(1, 10, 2) genera un rango de valores entre 1 y 9 en pasos de 2: 1, 3,
5, 7, 9

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 5/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

range(1, 10, 2) genera un rango de valores entre 1 y 9 en pasos de 2: 1, 3,


5, 7, 9
range(10, 1, -2) genera un rango de valores entre 10 y 1 en pasos de -2 (es
decir, en forma descendente): 10, 8, 6, 4, 2

Note que se genera un rango de datos hasta el segundo argumento menos 1. Esto se
repite en muchas operaciones de Python donde se generan rangos. Asi, range(1, 20)
genera un rango entre 1 y 20-1, es decir, entre 1 y 19.

Se puede combinar con la instrucción in para verificar si un valor se encuentra dentro


del rango. Considere los siguientes ejemplos:

In [ ]: print("5 in range(1, 10):", 5 in range(1, 10))


print("10 in range(1, 10):", 10 in range(1, 10))
print("4 in range(1, 10, 2):", 2 in range(1, 10, 2))
print("0 in range(1, 10):", 5 in range(10))
print("7 in range(1, 10):", 5 in range(1, 10))

Podemos resolver el problema que verifica si un numero es par o impar utilizando


range() :

In [ ]: num = int(input("Ingrese un numero entero positivo:"))

if num < 0:
print("El numero ingresado debe ser positivo")
else:
if num in range(0, num+1, 2):
print(f"{num} es par")
else:
print("{num} es impar")

Lazo de control con for


El lazo de control for permite iterar una secuencia iterable como una tupla o una lista.
La instrucción for se conoce como un iterador: esto es, una construcción que toma un
iterable y extrae los elementos que lo conforman uno a uno. Considere el código de la
siguiente celda:

In [13]: number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in number_list:


print(number)

1
2
3
4
5
6
7
8
9

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 6/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

Como se observa, la instrucción for va extrayendo los datos de la lista number_list ,


un iterable. Esta forma de operar de un lazo for permite tener un código legible ya
que la lectura del código es clara ("para cada valor de la secuencia 1, 2, 3, 4...").

Se puede combinar con la función range() para obtener un código más reducido:

In [14]: print("Secuencia de numeros pares:")


for num in range(2, 21, 2):
print(f"* {num}")

Secuencia de numeros pares:


* 2
* 4
* 6
* 8
* 10
* 12
* 14
* 16
* 18
* 20

Lazo de repetición while

El lazo de control while permite establecer un lazo de control mientras una condición
se mantenga como verdadera. Por ejemplo:

In [ ]: num = 5

while num > 0:


print(num)
num -= 1

¿Qué sucederá si se elimina la línea num -= 1 ? En el caso de Jupyter Notebook, el


indicador de la celda mostrará [*] y el programa entrada en un "bucle infinito" ya que
la condición siempre será verdadera (el número nunca será menor o igual a 0). En caso

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 7/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

esto suceda, se debe de detener el "kernel", es decir, el núcleo de ejcución de Python.


Para esto, seleccionar en el Menu Kernel > Restart Kernel... y seleccionar
Restart .

Cuando se ejecute esta secuencia en un terminal, debe de detener la ejecución con la


combinación de teclas Ctrl + C

try...except y estructuras de control


El bloque try...except permite probar una secuencia de instrucciones y en caso de
un error en la ejecución de alguna de las instrucciones que forman parte del bloque, se
generará una excepción (un error) que puede ser capturada por el bloque
try...except para ejecutar alguna acción.

Considere el siguiente código:

In [17]: edad = input("Ingrese su edad:")

# Verificamos que su edad es un valor entero con isinstance(var, type)


if isinstance(edad, int):
edad = int(edad)
if edad < 18:
print("En menor de edad")
else:
print("Es mayor de edad")
else:
print("Debe de ingresar un valor entero")

Debe de ingresar un valor entero

Se puede lograr lo mismo utilizando un bloque try...except:

In [19]: try:
edad = int(input("Ingrese su edad:"))

if edad < 18:


print("En menor de edad")
else:

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 8/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

print("Es mayor de edad")

except ValueError:
print("Debe de ingresar un valor entero")

En menor de edad

Si se ingresa un valor como 12.5 como edad, al convertír este str en un int se
producirá una excepción del tipo ValueError :

In [ ]: int('12.5')

Este evento detiene la ejecución del bloque de código y se captura el tipo de excepción
para ejecutar las acciones según el tipo de excepción. Si se utiliza la instrucción except
sin especificar el tipo de excepción se esta definiendo un caso de error genérico, lo que
no se recomienda. En lugar de esto se recomienda utilizar la siguiente construcción:

try:
edad = int(edad)
except Exception as e:
print(e)

In [6]: two_numbers = False


try:
n1, n2 = input("Ingrese dos numeros: ").split()
two_numbers = True
except Exception as e:
print(e) # Esto muestra el mensaje de la excepcion generada

if two_numbers:
try:
# Intenta ejecutar todo el bloque
# y si algo sale mal, salta a except
n1 = int(n1); n2 = int(n2)

print(f"{n1} + {n2} = {n1 + n2:.2f}")


print(f"{n1} - {n2} = {n1 - n2:.2f}")
print(f"{n1} x {n2} = {n1 * n2:.2f}")
print(f"{n1} / {n2} = {n1 / n2:.2f}")
print(f"{n1} ** {n2} = {n1 ** n2:.2f}")
print(f"{n1} % {n2} = {n1 % n2}")

except ValueError:
print("Los numeros ingresados deben ser enteros")

except ZeroDivisionError:
print("No se puede realizar la division: Division por cero!!!")

not enough values to unpack (expected 2, got 1)

break y continue
Las instrucciones break y continue permiten alterar la ejecución de un lazo.

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 9/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

break detiene la ejecución de un lazo de forma inmediata. Considere el siguiente


código:

In [7]: # Este script imprime los valores numéricos de un rango hasta que alcance a algu
for num in range(1, 20):
if num % 7 == 0:
print(f"{num} es multiplo de 7")
break
else:
print(f"{num} no es multiplo de 7")

1 no es multiplo de 7
2 no es multiplo de 7
3 no es multiplo de 7
4 no es multiplo de 7
5 no es multiplo de 7
6 no es multiplo de 7
7 es multiplo de 7

continue detiene la iteración del ciclo de repetición para continuar con la siguiente
iteración en caso de existír. Considere el siguiente código:

In [11]: # Este script imprime todos los valores numéricos de un rango a excepción de los
for num in range(1, 20):
if num % 7 == 0:
print("---- SIGUIENTE ITERACION ---")
continue
else:
print(f"{num} no es multiplo de 7")

1 no es multiplo de 7
2 no es multiplo de 7
3 no es multiplo de 7
4 no es multiplo de 7
5 no es multiplo de 7
6 no es multiplo de 7
---- SIGUIENTE ITERACION ---
8 no es multiplo de 7
9 no es multiplo de 7
10 no es multiplo de 7
11 no es multiplo de 7
12 no es multiplo de 7
13 no es multiplo de 7
---- SIGUIENTE ITERACION ---
15 no es multiplo de 7
16 no es multiplo de 7
17 no es multiplo de 7
18 no es multiplo de 7
19 no es multiplo de 7

Su uso es restringido para casos en donde su presencia ayuda a hacer un código más
legible o cuando no se tiene una mejor solución.

Un caso típico es la contrucción de un lazo "do...while" en donde se evalúa una variable


despues de haberla ingresado. El siguiente script pide un valor entre 1 y 10. Si se ingresa
un valor fuera de este rango el script continua pidiendo un valor hasta que este en el
rango esperado:

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 10/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

In [15]: while True:


try:
num = int(input("Ingrese un numero entre 1 y 10: "))
except ValueError:
print("Debe de ingresar un número entero")
continue

if num < 1 or num > 10:


print("Debe de ingresar un numero entre 1 y 10")
else:
if num % 2 == 0:
print("{} es par".format(num))
else:
print("{} es impar".format(num))

break

Debe de ingresar un número entero


5 es impar

Este tipo de construcciones suele ser confuso pues contiene un while True que indica
que es un lazo infinito cuando no lo se ya que se interrumpirá en algún momento y para
saber bajo que condición es necesario leer el código. Es mejor utilizar una variable tipo
bandera que indique la condición. Esto hace el código más legíble:

In [14]: num_valido = False


while not num_valido:
try:
num = int(input("Ingrese un numero entre 1 y 10: "))
except ValueError:
print("Debe de ingresar un número entero")
continue

if num < 1 or num > 10:


print("Debe de ingresar un numero entre 1 y 10")
else:
num_valido = True
if num % 2 == 0:
print("{} es par".format(num))
else:
print("{} es impar".format(num))

Debe de ingresar un número entero


Debe de ingresar un numero entre 1 y 10
Debe de ingresar un numero entre 1 y 10
8 es par

Uso de else en un lazo de control


Considere el siguiente código:

In [ ]: num_primos = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 53, 57, 59]

print("Para todos los numeros impares entre 1 y 59, los numeros primos son:")
for num in range(1, 60, 2):
if num in num_primos:

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 11/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

print( " *", num)


print("Los demas numeros no son primos")

La última línea print("Los demas numeros no son primos") esta fuera del bloque
if y del bloque for , por lo que es una instrucción que se ejecutará al finalizar ambos
bloques. Sin embargo, algun programador puede considerar que esta línea deberia estar
dentro del alguno de los bloques. Para evitar esta falta de claridad, se puede incluír la
instrucción else para un lazo de control:

In [ ]: num_primos = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 53, 57, 59]

print("Para todos los numeros impares entre 1 y 59, los numeros primos son:")
for num in range(1, 60, 2):
if num in num_primos:
print( " *", num)
else:
print("Los demas numeros no son primos")

En el código anterior, la instrucción else es parte del bloque for (NO del bloque
if ). En Python else puede ser parte de un lazo e indica lo que sucederá cuando el
lazo concluya normalmente. Por ejemplo:

In [ ]: for i in range(1, 6):


print(i)
else:
print("Fin del lazo")

In [ ]: i = 6
while i > 0:
print(i)
i -= 1
else:
print("Fin del lazo")

Recuerde: el uso de else permite especificar las instrucciones a ejecutar cuando el lazo
acabe normalmente. Considere el siguente caso:

In [ ]: for num in range(1, 11):


if num % 7 != 0:
print(num)
else:
break
else:
print("Fin del lazo")

print("La lazo fue interrumpido por un 'break'")

No ejecutar nada: pass


La instrucción pass sirve para especificar que no se quiere realizar nada. Esto tiene
utilidad al momento de escribir un código en desarrollo. Por ejemplo, considere el
siguiente ejemplo:

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 12/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

In [ ]: num = 82

if num < 0:
# TODO: Se colocara un mensaje de error
pass
elif num > 100:
# TODO: Se colocara un mensaje de error
pass
elif num % 2 == 0:
print("{} es par".format(num))
else:
print("{} es impar".format(num))

Si retira las instrucciones pass del codigo anterior este dejará de funcionar. ¿Entiende
por qué? La instrucción pass por lo tanto permite ir construyendo los bloques de
decisión e ir resolviendo cada una de las condiciones poco a poco.

Directorio de recursos e importación de librerias:


generación de números aleatorios
Las funciones incluidas en Python son limitadas. Para realizar otras operaciones será
necesario importar librerías hacia el interprete utilizando la instrucción import . Por
ejemplo, podemos importar la librería random para acceder a las funciones que
retornan valores aleatorios:

In [16]: import random

Si la instrucción anterior no ha generado error, la librería random debe de estar agregada


al directorio de recursos de Python. Verifique la acción anterior confirmando su presencia
en el directorio con la instrucción dir() :

In [17]: dir()

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 13/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

Out[17]: ['In',
'Out',
'_',
'__',
'___',
'__builtin__',
'__builtins__',
'__doc__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'_dh',
'_i',
'_i1',
'_i10',
'_i11',
'_i12',
'_i13',
'_i14',
'_i15',
'_i16',
'_i17',
'_i2',
'_i3',
'_i4',
'_i5',
'_i6',
'_i7',
'_i8',
'_i9',
'_ih',
'_ii',
'_iii',
'_oh',
'exit',
'get_ipython',
'num',
'num_valido',
'open',
'quit',
'random',
'two_numbers']

¿Ubica la palabra "random" en la lista anterior? Se encuentra al final de la lista.


¿Encuentra también las palabras num y edad ? El directorio de Python guarda un
registro de todas las variables y objetos que se han ido creando en Python. ¿Que
funciones ahora estan disponibles en la librería Python? Verifiquemos el directorio en
random :

In [18]: dir(random)

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 14/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

Out[18]: ['BPF',
'LOG4',
'NV_MAGICCONST',
'RECIP_BPF',
'Random',
'SG_MAGICCONST',
'SystemRandom',
'TWOPI',
'_ONE',
'_Sequence',
'_Set',
'__all__',
'__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'_accumulate',
'_acos',
'_bisect',
'_ceil',
'_cos',
'_e',
'_exp',
'_floor',
'_index',
'_inst',
'_isfinite',
'_log',
'_os',
'_pi',
'_random',
'_repeat',
'_sha512',
'_sin',
'_sqrt',
'_test',
'_test_generator',
'_urandom',
'_warn',
'betavariate',
'choice',
'choices',
'expovariate',
'gammavariate',
'gauss',
'getrandbits',
'getstate',
'lognormvariate',
'normalvariate',
'paretovariate',
'randbytes',
'randint',
'random',
'randrange',
'sample',
'seed',

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 15/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

'setstate',
'shuffle',
'triangular',
'uniform',
'vonmisesvariate',
'weibullvariate']

La instrucción anterior muestra una lista de todas las funciones disponibles como parte
de las librería random . Aquellas funciones cuyo nombre inicia con los caracteres __ e
_ no estan disponibles para nosotros (son privadas y protegidas, respectivamente).
¿Encuentra en el listado la función random ? Esta en la función random() incluida en la
librería random . ¿Cómo ejecutar la función radom() de la librería random ?

In [ ]: random.random()

¿Como se puede obtener ayuda sobre la


instrucción anterior?
La siguiente línea imprime la ayuda de la librería random (Puede hacer click derecho
sobre la celda de salida y habilitar "Enable Scrolling for Outputs" para un mejor
resultado).

In [19]: help(random)

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 16/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

Help on module random:

NAME
random - Random variable generators.

MODULE REFERENCE
https://docs.python.org/3.10/library/random.html

The following documentation is automatically generated from the Python


source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.

DESCRIPTION
bytes
-----
uniform bytes (values between 0 and 255)

integers
--------
uniform within range

sequences
---------
pick random element
pick random sample
pick weighted random sample
generate random permutation

distributions on the real line:


------------------------------
uniform
triangular
normal (Gaussian)
lognormal
negative exponential
gamma
beta
pareto
Weibull

distributions on the circle (angles 0 to 2pi)


---------------------------------------------
circular uniform
von Mises

General notes on the underlying Mersenne Twister core generator:

* The period is 2**19937-1.


* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python step,
and is, therefore, threadsafe.

CLASSES
_random.Random(builtins.object)
Random
SystemRandom

class Random(_random.Random)

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 17/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

| Random(x=None)
|
| Random number generator base class used by bound module functions.
|
| Used to instantiate instances of Random to get generators that don't
| share state.
|
| Class Random can also be subclassed if you want to use a different basic
| generator of your own devising: in that case, override the following
| methods: random(), seed(), getstate(), and setstate().
| Optionally, implement a getrandbits() method so that randrange()
| can cover arbitrarily large ranges.
|
| Method resolution order:
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| __getstate__(self)
| # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
| # longer called; we leave it here because it has been here since rand
om was
| # rewritten back in 2001 and why risk breaking something.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|
| lambd is 1.0 divided by the desired mean. It should be
| nonzero. (The parameter would be called "lambda", but that is
| a reserved word in Python.) Returned values range from 0 to
| positive infinity if lambd is positive, and from negative
| infinity to 0 if lambd is negative.
|

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 18/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

| gammavariate(self, alpha, beta)


| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha - 1) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu, sigma)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| getstate(self)
| Return internal state; can be passed to setstate() later.
|
| lognormvariate(self, mu, sigma)
| Log normal distribution.
|
| If you take the natural logarithm of this distribution, you'll get a
| normal distribution with mean mu and standard deviation sigma.
| mu can have any value, and sigma must be greater than zero.
|
| normalvariate(self, mu, sigma)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randbytes(self, n)
| Generate n random bytes.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(start, stop[, step]).
|
| This fixes the problem with randint() which includes the
| endpoint; in Python this is usually not what you want.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence or set.
|
| Returns a new list containing elements from the population while
| leaving the original population unchanged. The resulting list is
| in selection order so that all sub-slices will also be valid random
| samples. This allows raffle winners (the sample) to be partitioned
| into grand prize and second place winners (the subslices).
|
| Members of the population need not be hashable or unique. If the
| population contains repeats, then each occurrence is a possible

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 19/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

| selection in the sample.


|
| Repeated elements can be specified one at a time or with the optional
| counts parameter. For example:
|
| sample(['red', 'blue'], counts=[4, 2], k=5)
|
| is equivalent to:
|
| sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
| To choose a sample from a range of integers, use range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| seed(self, a=None, version=2)
| Initialize internal state from a seed.
|
| The only supported seed types are None, int, float,
| str, bytes, and bytearray.
|
| None or no argument seeds from current time or from an operating
| system specific randomness source if available.
|
| If *a* is an int, all bits are used.
|
| For version 2 (the default), all of the bits are used if *a* is a st
r,
| bytes, or bytearray. For version 1 (provided for reproducing random
| sequences from older versions of Python), the algorithm for str and
| bytes generates a narrower range of seeds.
|
| setstate(self, state)
| Restore internal state from object returned by getstate().
|
| shuffle(self, x, random=None)
| Shuffle list x in place, and return None.
|
| Optional argument random is a 0-argument function returning a
| random float in [0.0, 1.0); if it is the default None, the
| standard random.random will be used.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on roundi
ng.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| mu is the mean angle, expressed in radians between 0 and 2*pi, and

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 20/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

| kappa is the concentration parameter, which must be greater than or


| equal to zero. If kappa is equal to zero, this distribution reduces
| to a uniform random angle over the range 0 to 2*pi.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __init_subclass__(**kwargs) from builtins.type
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Methods inherited from _random.Random:
|
| getrandbits(self, k, /)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| random(self, /)
| random() -> x in the interval [0, 1).
|
| ----------------------------------------------------------------------
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signatur
e.

class SystemRandom(Random)
| SystemRandom(x=None)
|
| Alternate random number generator using sources provided
| by the operating system (such as /dev/urandom on Unix or
| CryptGenRandom on Windows).
|
| Not available on all systems (see os.urandom() for details).
|
| Method resolution order:

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 21/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

| SystemRandom
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| getrandbits(self, k)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| getstate = _notimplemented(self, *args, **kwds)
|
| randbytes(self, n)
| Generate n random bytes.
|
| random(self)
| Get the next random number in the range [0.0, 1.0).
|
| seed(self, *args, **kwds)
| Stub method. Not used for a system random number generator.
|
| setstate = _notimplemented(self, *args, **kwds)
|
| ----------------------------------------------------------------------
| Methods inherited from Random:
|
| __getstate__(self)
| # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
| # longer called; we leave it here because it has been here since rand
om was
| # rewritten back in 2001 and why risk breaking something.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 22/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

| lambd is 1.0 divided by the desired mean. It should be


| nonzero. (The parameter would be called "lambda", but that is
| a reserved word in Python.) Returned values range from 0 to
| positive infinity if lambd is positive, and from negative
| infinity to 0 if lambd is negative.
|
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha - 1) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu, sigma)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| lognormvariate(self, mu, sigma)
| Log normal distribution.
|
| If you take the natural logarithm of this distribution, you'll get a
| normal distribution with mean mu and standard deviation sigma.
| mu can have any value, and sigma must be greater than zero.
|
| normalvariate(self, mu, sigma)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(start, stop[, step]).
|
| This fixes the problem with randint() which includes the
| endpoint; in Python this is usually not what you want.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence or set.
|
| Returns a new list containing elements from the population while
| leaving the original population unchanged. The resulting list is
| in selection order so that all sub-slices will also be valid random
| samples. This allows raffle winners (the sample) to be partitioned
| into grand prize and second place winners (the subslices).
|
| Members of the population need not be hashable or unique. If the
| population contains repeats, then each occurrence is a possible

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 23/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

| selection in the sample.


|
| Repeated elements can be specified one at a time or with the optional
| counts parameter. For example:
|
| sample(['red', 'blue'], counts=[4, 2], k=5)
|
| is equivalent to:
|
| sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
| To choose a sample from a range of integers, use range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| shuffle(self, x, random=None)
| Shuffle list x in place, and return None.
|
| Optional argument random is a 0-argument function returning a
| random float in [0.0, 1.0); if it is the default None, the
| standard random.random will be used.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on roundi
ng.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| mu is the mean angle, expressed in radians between 0 and 2*pi, and
| kappa is the concentration parameter, which must be greater than or
| equal to zero. If kappa is equal to zero, this distribution reduces
| to a uniform random angle over the range 0 to 2*pi.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ----------------------------------------------------------------------
| Class methods inherited from Random:
|
| __init_subclass__(**kwargs) from builtins.type
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 24/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

| ----------------------------------------------------------------------
| Data descriptors inherited from Random:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Random:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signatur
e.

FUNCTIONS
betavariate(alpha, beta) method of Random instance
Beta distribution.

Conditions on the parameters are alpha > 0 and beta > 0.


Returned values range between 0 and 1.

choice(seq) method of Random instance


Choose a random element from a non-empty sequence.

choices(population, weights=None, *, cum_weights=None, k=1) method of Random


instance
Return a k sized list of population elements chosen with replacement.

If the relative weights or cumulative weights are not specified,


the selections are made with equal probability.

expovariate(lambd) method of Random instance


Exponential distribution.

lambd is 1.0 divided by the desired mean. It should be


nonzero. (The parameter would be called "lambda", but that is
a reserved word in Python.) Returned values range from 0 to
positive infinity if lambd is positive, and from negative
infinity to 0 if lambd is negative.

gammavariate(alpha, beta) method of Random instance


Gamma distribution. Not the gamma function!

Conditions on the parameters are alpha > 0 and beta > 0.

The probability distribution function is:

x ** (alpha - 1) * math.exp(-x / beta)


pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alpha

gauss(mu, sigma) method of Random instance


Gaussian distribution.

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 25/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

mu is the mean, and sigma is the standard deviation. This is


slightly faster than the normalvariate() function.

Not thread-safe without a lock around calls.

getrandbits(k, /) method of Random instance


getrandbits(k) -> x. Generates an int with k random bits.

getstate() method of Random instance


Return internal state; can be passed to setstate() later.

lognormvariate(mu, sigma) method of Random instance


Log normal distribution.

If you take the natural logarithm of this distribution, you'll get a


normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.

normalvariate(mu, sigma) method of Random instance


Normal distribution.

mu is the mean, and sigma is the standard deviation.

paretovariate(alpha) method of Random instance


Pareto distribution. alpha is the shape parameter.

randbytes(n) method of Random instance


Generate n random bytes.

randint(a, b) method of Random instance


Return random integer in range [a, b], including both end points.

random() method of Random instance


random() -> x in the interval [0, 1).

randrange(start, stop=None, step=1) method of Random instance


Choose a random item from range(start, stop[, step]).

This fixes the problem with randint() which includes the


endpoint; in Python this is usually not what you want.

sample(population, k, *, counts=None) method of Random instance


Chooses k unique random elements from a population sequence or set.

Returns a new list containing elements from the population while


leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique. If the


population contains repeats, then each occurrence is a possible
selection in the sample.

Repeated elements can be specified one at a time or with the optional


counts parameter. For example:

sample(['red', 'blue'], counts=[4, 2], k=5)

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 26/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

is equivalent to:

sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)

To choose a sample from a range of integers, use range() for the


population argument. This is especially fast and space efficient
for sampling from a large population:

sample(range(10000000), 60)

seed(a=None, version=2) method of Random instance


Initialize internal state from a seed.

The only supported seed types are None, int, float,


str, bytes, and bytearray.

None or no argument seeds from current time or from an operating


system specific randomness source if available.

If *a* is an int, all bits are used.

For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1 (provided for reproducing random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.

setstate(state) method of Random instance


Restore internal state from object returned by getstate().

shuffle(x, random=None) method of Random instance


Shuffle list x in place, and return None.

Optional argument random is a 0-argument function returning a


random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.

triangular(low=0.0, high=1.0, mode=None) method of Random instance


Triangular distribution.

Continuous distribution bounded by given lower and upper limits,


and having a given mode value in-between.

http://en.wikipedia.org/wiki/Triangular_distribution

uniform(a, b) method of Random instance


Get a random number in the range [a, b) or [a, b] depending on rounding.

vonmisesvariate(mu, kappa) method of Random instance


Circular data distribution.

mu is the mean angle, expressed in radians between 0 and 2*pi, and


kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.

weibullvariate(alpha, beta) method of Random instance


Weibull distribution.

alpha is the scale parameter and beta is the shape parameter.

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 27/28


27/3/24, 08:39 Semana_02 - Operaciones condicionales y lazos de control

DATA
__all__ = ['Random', 'SystemRandom', 'betavariate', 'choice', 'choices...

FILE
c:\users\asus\anaconda3\lib\random.py

La siguiente línea imprime información de la función random() :

In [20]: help(random.random)

Help on built-in function random:

random() method of random.Random instance


random() -> x in the interval [0, 1).

Como puede observar, random.random() retorna una valor entre 0 y 0.99999....

In [21]: for i in range(5):


print(random.random())

0.8309979826763929
0.839864873030073
0.6996786516183964
0.24637615547625913
0.3094165665094325

Otra función útil en la librería random es randrange() . Esta genera un rango de


valores enteros (al igual que range() ) y retorna un valor aleatorio dentro del rango
generado:

In [22]: for i in range(5):


print(random.randrange(1, 10))

2
1
2
5
6

Así también, la función uniform() retorna un valor aleatorio float en un rango:

In [23]: for i in range(5):


print(random.uniform(1, 10))

3.490770226697019
9.674063315170267
4.527729215990874
6.5165374268575125
1.3644621499051426

file:///C:/Users/Asus/Downloads/Semana_02 - Operaciones condicionales y lazos de control (1).html 28/28

También podría gustarte