Python - Funciones con def - return

 
Vista:
sin imagen de perfil
Val: 36
Ha aumentado su posición en 17 puestos en Python (en relación al último mes)
Gráfica de Python

Funciones con def - return

Publicado por Alexander (8 intervenciones) el 25/10/2020 02:05:39
Buen día

Espero se encuentren bien, hoy también necesito de su ayuda, tengo un ejercicio que no se como resolver. Gracias por siempre darme una mano. Saludos.

Escenario
Tu tarea es escribir y probar una función que toma dos argumentos (un año y un mes) y devuelve el número de días del mes/año dado (mientras que solo febrero es sensible al valor year, tu función debería ser universal).

La parte inicial de la función está lista. Ahora, haz que la función devuelva None si los argumentos no tienen sentido.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def isYearLeap(year):
#
# tu código del laboratorio anterior
#
 
def daysInMonth(year, month):
#
# coloca tu código aqui
#
 
testYears = [1900, 2000, 2016, 1987]
testMonths = [2, 2, 1, 11]
testResults = [28, 29, 31, 30]
for i in range(len(testYears)):
	yr = testYears[i]
	mo = testMonths[i]
	print(yr, mo, "->", end="")
	result = daysInMonth(yr, mo)
	if result == testResults[i]:
		print("OK")
	else:
		print("Error")


Este ejercicio hace referencia al anterior ejercicio en el que me ayudaron.

https://www.lawebdelprogramador.com/foros/Python/1764207-Regresando-el-resultado-de-una-funcion-def-return.html
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 62
Ha disminuido su posición en 2 puestos en Python (en relación al último mes)
Gráfica de Python

Funciones con def - return

Publicado por Germán (16 intervenciones) el 25/10/2020 07:48:17
1
2
3
4
5
6
7
8
import calendar
 
def isYearLeap(year):
    return calendar.isleap(year)
 
 
def daysInMonth(year, month):
    return calendar.monthrange(year, month)[-1]
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Funciones con def - return

Publicado por N0VAT1UM (1 intervención) el 24/04/2021 21:24:02
No se si ya encontraste la respuesta pero esto se me ocurrio, se puede optimizar mas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def isYearLeap(year):
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False
 
def daysInMonth(year, month):
    diasMeses = [31,28,31,30,31,30,31,31,30,31,30,31]
    if isYearLeap(year):
        if diasMeses[month - 1] == 28:
            return 29
        else:
            return diasMeses[month - 1]
    else:
        return diasMeses[month - 1]
    return None
 
testYears = [1900, 2000, 2016, 1987]
testMonths = [2, 2, 1, 11]
testResults = [28, 29, 31, 30]
 
for i in range(len(testYears)):
	yr = testYears[i]
	mo = testMonths[i]
	print(yr, mo, "->", end="")
	result = daysInMonth(yr, mo)
	if result == testResults[i]:
		print("OK")
	else:
		print("Error")
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
Imágen de perfil de Samir
Val: 14
Ha aumentado su posición en 281 puestos en Python (en relación al último mes)
Gráfica de Python

Funciones con def - return

Publicado por Samir (4 intervenciones) el 04/06/2021 22:10:18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def isYearLeap(year):
    return(year % 4 == 0 and year % 100 != 0 or year % 400 == 0)
 
def daysInMonth(year, month):
    diasPorMe]s = [31,28,31,30,31,30,31,31,30,31,30,31]
    if isYearLeap(year):
        if diasPorMes[month - 1] == 28:
            return 29
        else:
            return diasPorMes[month - 1]
    else:
        return diasPorMes[month - 1]
    return None
 
testYears = [1900, 2000, 2016, 1987]
testMonths = [2, 2, 1, 11]
testResults = [28, 29, 31, 30]
for i in range(len(testYears)):
 
	yr = testYears[i]
	mo = testMonths[i]
	print(yr, mo, "->", end="")
	result = daysInMonth(yr, mo)
	if result == testResults[i]:
		print("OK")
	else:
		print("Error")
 
#Importate recordar que por ser un ano bisiesto el mes de febrero tendra 29 Dias y es por eso que la condicion isYearLeap dentro de la funcion daysInMonth es verdadera.

https://github.com/Gaspela
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar

Funciones con def - return

Publicado por Walter (1 intervención) el 18/10/2022 04:15:27
Hola Samir
Como estas?
Estoy aprendiendo Python y vi la resolución del ejercicio (def daysInMonth(year, month):) me parecio muy buena la tuya, pero hay algo que no entiendo, return diasPorMes[month - 1], y es lo que esta entre corchetes, el -1, Como funciona?
desde ya muy agradecido
Walter
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Funciones con def - return

Publicado por Denis (2 intervenciones) el 16/07/2021 18:44:08
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def isYearLeap(año):
    if año>1582:
        if (año%4)==0 and (año%100)==0 and (año%400)==0:
            return True
        else:
            return False
    else:
        return None
 
def daysInMonth(year, month):
    meses=[1,2,3,4,5,6,7,8,9,10,11,12]
    mesestre=[4,6,9,11]
    #mesestreuno=[1,3,5,7,8,10,12]
    x=isYearLeap(year)
    if month in meses:
        if month==2:
            if x:
                return 29
            else:
                return 28
        elif month in mesestre:
            return 30
        else:
            return 31
    else:
        return None
 
testYears = [1900, 2000, 2016, 1987]
testMonths = [2, 2, 1, 13]
testResults = [29, 29, 31, 30]
for i in range(len(testYears)):
	yr = testYears[i]
	mo = testMonths[i]
	print(yr, mo, "->", end="")
	result = daysInMonth(yr, mo)
	if result == testResults[i]:
		print("OK")
	else:
		print("Error")
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Funciones con def - return

Publicado por Denis (2 intervenciones) el 16/07/2021 18:52:07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def isYearLeap(año):
    if año>1582:
        if (año%4)==0 and (año%100)==0 and (año%400)==0:
            return True
        else:
            return False
    else:
        return None
 
def daysInMonth(year, month):
    meses=[1,2,3,4,5,6,7,8,9,10,11,12]
    mesestre=[4,6,9,11]
    #mesestreuno=[1,3,5,7,8,10,12]
    x=isYearLeap(year)
    if month in meses:
        if month==2:
            if x:
                return 29
            else:
                return 28
        elif month in mesestre:
            return 30
        else:
            return 31
    else:
        return None
 
testYears = [1900, 2000, 2016, 1987]
testMonths = [2, 2, 1, 13]
testResults = [29, 29, 31, 30]
for i in range(len(testYears)):
	yr = testYears[i]
	mo = testMonths[i]
	print(yr, mo, "->", end="")
	result = daysInMonth(yr, mo)
	if result == testResults[i]:
		print("OK")
	else:
		print("Error")
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Funciones con def - return

Publicado por David (2 intervenciones) el 06/08/2021 00:18:47
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
testYears = [1900, 2000, 2016, 1987]
testMonths = [ 2, 2, 1, 11]
testResults = [28, 29, 31, 30]
def leapYear(year):
    if year % 4 != 0:
        return False
    elif year % 100 != 0:
        return True
    elif year % 400 != 0:
        return False
    else:
        return True
 
def monthYear(year, monthNumber):
    if year <= 1582:
        return print(f'{year} - {None} - The leap year is not delclared.')
    elif monthNumber <= 0 or monthNumber > 13:
        return print(f'{monthNumber} - {None} - The number of the month must be between 1 and 12')
    else:
        numberOfDaysPerMonth = [31,28,31,30,31,30,31,31,30,31,30,31]
        res = numberOfDaysPerMonth[monthNumber-1]
        if monthNumber == 2 and leapYear(year) == True:
            res = 29
        return res
 
for i in range(len(testYears)):
    year = testYears[i]
    month = testMonths[i]
    days = monthYear(year,month)
    if days == testResults[i]:
        print({'Year': year,'Month Number': month,'Number of Days': days})
    else:
        print('The process was unsuccessful.')
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Funciones con def - return

Publicado por Roberto (1 intervención) el 13/06/2022 06:00:29
aaaaaaaaaaa
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar