簡體   English   中英

我怎樣才能擺脫這個嵌套的while循環? (Python)

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

下午好。 我是編碼的初學者,我正在嘗試為 Python 做一個練習,構建一個嵌套的 While 循環,我在我的小代碼中有一個錯誤,他最后一行代碼說elif continua == "N"or "n": i = -1並且它應該退出所有的 while 循環(嵌套的和第一個),因為 i=-1 並且 while 循環在此代碼中工作的條件是 i > 0(或至少這是我做這行編碼的目的。)。 但是突然之間循環又開始了,我不知道為什么。
有人可以幫我擺脫這個循環嗎?

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  

您的代碼中有幾個錯誤。

  • 缺失:ifelif語句的末尾
  • 幾個不正確的意圖(可能是復制粘貼時的格式問題)
  • 您不能鏈接布爾檢查 lile continua == "N" or "n"使用continua == 'n' or continua == 'N'或者在這種情況下甚至更好continua.lower() == 'n'

您正在尋找break 這是您的代碼的工作版本:

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

您的代碼流有點難以閱讀。 尤其是很難理解你的 i,a,b 變量在做什么。 這是第二個版本,它展示了如何使您的代碼更易於理解。

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

以下是對改進部分的一些解釋。

輸入

盡管需要,但輸入可能不是數字。 這可能會導致崩潰。 無法解析的字符串的異常由try: ... except:第二個 while 循環移動到單獨的 function 中並移出主流程以使其更易於閱讀。 現在也可以多次調用它而無需重復代碼。 number獲得有效值時, while循環將自行終止。

變量

i,a 和 b 的含義不能直接自我解釋。 它們也被設置在代碼中的不同位置。 您已經在列表中獲得了所需的所有信息。 根據定義升序列表在排序時不會改變。 我們可以使用這個技巧來檢查排序列表是否是原始列表sorted(listadevalores) == listadevalores 所以我們不需要處理列表元素。 平均值可以通過將所有列表元素的sum除以列表的長度sum(listadevalores) / len(listadevalores)

看來您的縮進有問題。 請解決這個問題。

此外,它可能會幫助您:創建變量來告訴您的循環繼續,並在您需要停止循環時將其設置為 False。 一個例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM