A proposed infinity loop PYTHON exercise

Asked

Viewed 137 times

-2

HELLO, I’m trying to resolve the issue below, but I can’t make the LOOP work, since the exercise asks that even after choosing a type of average, the instruction comes back asking infinitely the same thing:

***Implement a python script with:

  • a function that takes three numerical values and one character per parameter .
  • if the character passed as argument is 'A' or 'a', the function returns the arithmetic mean of the numerical values
  • if the character passed as argument is 'P' or 'p', the function returns the weighted average (weights: 5, 3 and 2) of the numerical values;
  • and if the character passed as argument is 'H' or 'h', the function returns the harmonic mean of the numerical values.
  • this script should interact with the user referring to the three values and also what type of average the user wants to calculate.
  • this script must be interactive, that is, it must query if the user wants to perform a new calculation at the end of each execution and, if the answer is affirmative, repeat the process.***

My code for the above question:

    num1=float(input('Digite um primeiro número: ')) 
    num2=float(input('Digite um segundo número: ')) 
    num3=float(input('Digite um terceiro número: '))
        
        #FORMULAS DAS MEDIAS: 
    med_arit=((num1 + num2 + num3) / 3) 
    med_harm=((1/num1 + 1/num2 + 1/num3)/3) 
    med_pond=((num1*5 + num2*3 + num3*2) / 10)
        
    print('Os números inseridos respectivamente são: {:.0f}, {:.0f} e {:.0f}.'.format(num1,num2,num3)) print('================================', '\n')
        
    med=str(input('Agora para saber as MÉDIAS: 
\nARITMÉTICA, digite [A]; 
\nHARMÔNICA digite [H]'
\nPONDERADA digite [P]' 
\nDIGITE A LETRA DA MÉDIA DESEJADA: '))
        
        
        while True:
            try:
            if med in 'Aa':
                print('A MÉDIA ARITMÉTICA é igual a ', med_arit)
                break
            elif med in "Hh":
                print('A MÉDIA HARMÔNICA é igual a ', med_harm)
                break
            elif med in "Pp":
                print('A MÉDIA PONDERADA é igual a ',med_pond)
                break
            else:
                print(input('Voçê inseriu um valor errado, tente novamente: '))

2 answers

0

Another interesting way to resolve this issue is by implementing a class encompassing all the means we desire. This way we can implement the following code:

class Medias:
    def __init__(self, num1, num2, num3):
        self.v1, self.v2, self.v3 = num1, num2, num3

    def media_aritmetica(self):
        return (self.v1 + self.v2 + self.v3) / 3

    def media_ponderada(self):
        return ((self.v1 * 5) + (self.v2 * 3) + (self.v3 * 2)) / 10

    def media_harmonica(self):
        return (1 / self.v1 + 1 / self.v2 + 1 / self.v3) / 3


while True:
    numero_1 = float(input('Digite o primeiro valor: '))
    numero_2 = float(input('Digite o segundo valor: '))
    numero_3 = float(input('Digite o terceiro valor: '))

    medias = Medias(numero_1, numero_2, numero_3)

    while (me := input('Média Aritmética, Ponderada ou Harmônica? [A/P/H] ').upper()) \
            not in {'A', 'P', 'H'}:
        print('Valor INVÁLIDO!')

    if me == 'A':
        m_aritmetica = medias.media_aritmetica()
        print(f'A média aritmética é: {m_aritmetica:.2f}')
    elif me == 'P':
        m_ponderada = medias.media_ponderada()
        print(f'A média ponderada é: {m_ponderada:.2f}')
    else:
        m_harmonica = medias.media_harmonica()
        print(f'A média harmônica é: {m_harmonica:.2f}')

    while (resp := input('Desejas realizar outro cálculo? [S/N] ').upper()) not in {'S', 'N'}:
        print('Valor INVÁLIDO!')
    if resp == 'N':
        break

Note that when we execute this code we must enter each of the three values and press Enter. Then the class will be instantiated Medias. Later we received the following message:

Média Aritmética, Ponderada ou Harmônica? [A/P/H]

At this point we must choose one of the suggested averages. For this, we must type the first letter of the desired average. Then it will be checked whether the expression assigned to the variable me corresponds to one of the three letters - A, P or H. If the expression assigned to the variable me NAY is one of these three letters, we will be asked again one of the options. Otherwise, it will be checked which letter was typed and, according to the typed letter, a specific method will be called, belonging to the class Medias.

Example: If the typed letter is to or To, will be called the method media_arithmetic() and consequently the arithmetic mean shall be calculated and the result shall be displayed with two decimal places.

Having performed the first calculation the script will ask us:

Desejas realizar outro cálculo? [S/N]

Right now we must type s or S for YES or n or N for NAY. In case we type s or S the script will be executed again requesting the three values and, consequently, the new operation. If we type n or N, the script terminates its execution.

0

We can create a function with the calculation parameters and create a condition to exit the program at the end.

def media(num1, num2, num3, med):
    if med in 'Aa':
        med_arit=((num1 + num2 + num3) / 3) 
        return 'A MÉDIA ARITMÉTICA é igual a ' + str(med_arit)
    elif med in "Hh":
        med_harm=((1/num1 + 1/num2 + 1/num3)/3) 
        return 'A MÉDIA HARMÔNICA é igual a ' + str(med_harm)
    elif med in "Pp":
        med_pond=((num1*5 + num2*3 + num3*2) / 10)
        return 'A MÉDIA PONDERADA é igual a ' + str(med_pond)
    else:
        return 'Voçê inseriu um valor errado, tente novamente: '
    
med = ""
while med.lower() != "n":
    med=str(input('''Agora para saber as MÉDIAS: 
    \nARITMÉTICA, digite [A] 
    \nHARMÔNICA digite [H]
    \nPONDERADA digite [P]
    \nDIGITE A LETRA DESEJADA: '''))

    num1=float(input('Digite um primeiro número: ')) 
    num2=float(input('Digite um segundo número: ')) 
    num3=float(input('Digite um terceiro número: '))
    print('Os números inseridos respectivamente são: {:.0f}, {:.0f} e {:.0f}.'.format(num1,num2,num3)) 
    print('================================', '\n')

    print(media(num1, num2, num3, med))
    print('================================', '\n')
    med = input("Deseja efetuar um novo cálculo? [S]im ou [N]ão: ")
    print('================================', '\n')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.