Python intermedio para desarrolladores
Jasmin Ludolf
Senior Data Science Content Developer
# Crea una función
def average(values):
# Calcula la media
average_value = sum(values) / len(values)
# Redondea el resultado
rounded_average = round(average_value, 2)
# Devuelve rounded_average
return rounded_average
values = Argumento# Redondea pi a 2 dígitos
print(round(3.1415926535, 2))
3.14
Pasa argumentos asignando valores a keywords
Útil para entender y seguir los argumentos
# Redondea pi a 2 dígitos
print(round(number=3.1415926535
Pasa argumentos asignando valores a keywords
Útil para entender y seguir los argumentos
# Redondea pi a 2 dígitos
print(round(number=3.1415926535, ndigits=2))
3.14
# Obtén más info sobre la función help
print(help(round))
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise,
the return value has the same type as the number. ndigits may be negative.
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
$$
numberndigitsHelp on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise,
the return value has the same type as the number. ndigits may be negative.
None = sin valor / vacío
Argumento por defecto: forma de fijar un valor default para un argument
Sobrescribimos None con 2
Valor usado a menudo: defínelo con un argumento por defecto
# Crea una función
def average(values):
average_value = sum(values) / len(values)
rounded_average = round(average_value, 2)
return rounded_average
# Crea una función def average(values, rounded=False):
# Crea una función def average(values, rounded=False):# Redondea a dos decimales si rounded es True if rounded == True:average_value = sum(values) / len(values) rounded_average = round(average_value, 2) return rounded_average
# Crea una función def average(values, rounded=False):# Redondea a dos decimales si rounded es True if rounded == True: average_value = sum(values) / len(values) rounded_average = round(average_value, 2) return rounded_average# Si no, no redondees else: average_value = sum(values) / len(values) return average_value
# Lista de tiempos de preparación (minutos)
preparation_times = [19.23, 15.67, 48.57, 23.45, 12.06, 34.56, 45.67]
# Obtén la media sin redondear
print(average(preparation_times, False))
28.4585714
# Obtén la media sin redondear
print(average(preparation_times))
28.4585714
# Obtén la media redondeada
print(average(values=preparation_times, rounded=True))
28.46
Python intermedio para desarrolladores