2

Good afternoon! I'm a beginner in coding and i'm trying to do an exercise done for Python. Building a nested While Loop, i'm with a bug in my little he last line of the code says elif continua == "N"or "n": i = -1 and it should exit all the while loop (the nested and the first one), since i=-1 and the condition for the while loop to work in this code is i > 0 (or at least this is my purpose doing this line of coding.). But all of the sudden the loop starts again and i dont know why.
Can someone help me to get out of this loop?

b = 0

i = 1
valorTotal = 0.00
Audiencia = True
listadevalores = []
while i >= 0:

    a = int(input("Digite a quantidade de itens de audiência que serão calculados: "))
    i=a+1
    while i>1: 
        a=0
        v = float(input ("Insira os valores: "))
        valorTotal = valorTotal + v
        b+=1
        i-=1
        listadevalores.append(v)
        if b>1:
            if listadevalores[b-1] < listadevalores[b-2]:
            Audiencia = False
      else: 
        if Audiencia == True
        print ("Audiência sempre crescente. Média de audiência: ", (valorTotal/b))
        elif Audiencia == False
        print ("Audiência nem sempre crescente. Média de audiência: ",(valorTotal/b))
        continua = input ("Deseja continuar? S/N")
        if continua == "S"or "s":
            b=0
            valorTotal = 0.00
             Audiencia = True
             listadevalores = []
             i=0
        elif continua == "N"or "n":
           i = -1  
7
  • Have you considered just using break? Commented May 30, 2021 at 16:56
  • As an aside both continua == "S"or "s" and continua == "N"or "n" are both incorrect. For instance, to check for"S" or "s" you can use continua == "S" or continua == "s" Also, continua == "S"or "s" is always True, so the lines in the condition will always be executed. Commented May 30, 2021 at 16:59
  • @Erich break would only break the nested loop, not the outer loop. Commented May 30, 2021 at 16:59
  • In addition to DarrylG's comment, you can also use continua in ("S", "s") Commented May 30, 2021 at 17:00
  • continua is not defined. Commented May 30, 2021 at 17:00

2 Answers 2

2

There were several errors in your code.

  • missing : at the end of if or elif statemennts
  • several incorrect intendations (maybe a formating issue while copy paste)
  • You cannot chain bool checks lile continua == "N" or "n" use continua == 'n' or continua == 'N' or in this case even better continua.lower() == 'n'

You are searching for break. Here is a working version of your code:

b = 0

i = 1
valorTotal = 0.00
Audiencia = True
listadevalores = []
while i >= 0:

    a = int(input("Digite a quantidade de itens de audiência que serão calculados: "))
    i=a+1
    while i>1: 
        a=0
        v = float(input ("Insira os valores: "))
        valorTotal = valorTotal + v
        b+=1
        i-=1
        listadevalores.append(v)
        if b>1:
            if listadevalores[b-1] < listadevalores[b-2]:
                Audiencia = False
    else: 
      if Audiencia == True:
          print ("Audiência sempre crescente. Média de audiência: ", (valorTotal/b))
      elif Audiencia == False:
          print ("Audiência nem sempre crescente. Média de audiência: ",(valorTotal/b))
      continua = input ("Deseja continuar? S/N")
      if continua.lower() ==  "s":
          b=0
          valorTotal = 0.0
          Audiencia = True
          listadevalores = []
          i=0
      elif continua.lower() == "n":
          break

The flow of your code is a bit hard to read. Especially it is difficult to understand what your i,a,b variables are doing. Here is a second version which showes how to make your code a bit easier to understand.

def floatInput(input_str):
    number = None
    while not number:
        try:
            number = float(input (input_str)) 
        except:
            print('not a float number in Portuguese')
    return number
    

while True:
    a = int(floatInput("Digite a quantidade de itens de audiência que serão calculados: "))
    listadevalores = []
    
    for i in range(a):
        v = floatInput("Insira os valores: ")
        listadevalores.append(v)
    
    mean = sum(listadevalores) / len(listadevalores)
    
    if sorted(listadevalores) == listadevalores:
        print ("Audiência sempre crescente. Média de audiência: ", (mean))
    else:
        print ("Audiência nem sempre crescente. Média de audiência: ",(mean))
    
    continua = input ("Deseja continuar? S/N")
    
    if continua.lower() ==  "s":
        continue
    
    break

Here is some explanation to the improved parts.

Inputs

The input may be not a number although it is needed. This might create crashes. The exception for strings that cannot be parsed are handled by try: ... except: The second while loop is moved in a seperate function and out of the main flow to make it easier to read. Also it now can be called several times without the need for reapeating code. The while loop is self terminating when number gets a valid value.

Variabels

The meaning of i,a and b are not directly self explanatory. Also they are set at different positions in the code. You already have all information you need in the list. Ascending lists by definition does not change when they get sorted. We can use this trick to check if the sorted list is the original list sorted(listadevalores) == listadevalores. So we don't need to work on the list elements. The mean value can be calculated by dividing the sum of all list elements, using the build in sum by the lengt of the list sum(listadevalores) / len(listadevalores).

Sign up to request clarification or add additional context in comments.

3 Comments

You should try to explain everything that you changed
He may not have learned functions yet as part of his study plan. In most lessons guides, looping comes before modularity. And probably is also not familiar with try and excepts or would know what the sorted function does. But it is a vast improvement.
@Hofbr thats why it`s the second solution. To show different concepts as a starting point for deeper understanding and helping OP to improve his skills. But I added some explanations for the major changes.
1

It seems that you have wrong indentation in question. Please fix this.

Also, it may help you: create variable that tells your loops to proceed and set it to False when you need to stop the loops. An example:

loop = True

while your_condition and loop:

    // Do some stuff here

    while your_next_condition and loop:

        // Do some stuff here

        if something_happened:
            loop = False

2 Comments

This really helped me on building while loops. Thanks.
@LorenzoFioreze but be aware that creating complicated loop conditions does make your code complicated. If there is a way to solve the problem with re-structuring and breaks it could be a better way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.