简体   繁体   中英

How can i get out of this nested while loop? (Python)

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  

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) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM