2017-05-07 58 views
0

下面是一段代碼,從我的項目軟件:Python的多重嵌套,而真正的繼續/結束循環錯誤

def fun_1(self, i): 
    print("") 
    print("Welcome to Option 1: View Passwords") 
    while True: 
     print("") 
     which_o1 = input("1: Input a New Account details \n2: Exit \nPlease Input the option number: ") 

     if which_o1 == str(1): 
      with open(str(i)+'.txt', 'a+') as file: 
       while True: 
        print("") 
        web_n = input("Please Input Website name: ") 
        print("") 
        e_u = input("Please input email/username: ") 
        print("") 
        pass_w = input("Please input password: ") 

        while True: 
         print("") 
         sure = input("Website- " +web_n+"\nEmail/Username- "+e_u+"\nPassword- "+pass_w+"\nAre You sure about these details? Yes/No: ") 

         if (sure.lower()[0]) != 'y' and (sure.lower()[0]) != 'n': 
          print("") 
          print("Please input a valid response Yes/No!") 
          continue 

         elif (sure.lower()[0]) == 'y' and (sure.lower()[0]) != 'n': 
          list_log = [web_n, e_u, pass_w] 
          file.write(str(list_log) + '\n') 
          break 
          break 
          continue 

         elif (sure.lower()[0]) == 'n' and (sure.lower()[0]) != 'y': 
          break 
          continue 

     elif which_o1 == str(2): 
      return (i) 
     else: 
      print("") 
      print("Please Enter a Valid Response!") 
      continue 

所以有您可以看到,它有3個,而真正的循環。問題發生時打破和循環循環。如果你在中間elif的「pass_w」下看到最新的While True,它說elif (sure.lower()[0]) == 'y' and (sure.lower()[0]) != 'n':,在這裏我有2個break和1,因爲我想要做的是,當elif執行它時,第二,true和continue意味着循環第一次,而在代碼開始時爲true,但它只是在代碼的中間繼續循環第三行,而不是破壞它。

有沒有辦法讓我可以做到這一點?

+0

休息,並繼續不工作的方式,你不能堆疊在一起。 –

回答

0

首先,瞭解在while循環中的break語句之後不能執行任何行。因此,多次休息和繼續將無法工作。你需要重構你的代碼。就個人而言,我建議要麼執行try except語句,要麼將一些代碼放入函數中,以便當您要停止循環並將變量作爲指示傳遞給函數被調用的外部循環時,您可以return

另一種選擇可以不使用中斷並繼續,而是使用while循環檢查的變量或一組變量來決定是否應該繼續。所以,你的if的內線和elif就是你可以設置exitfirstloop = True等,並在while循環您檢查while not exitfirstloop

+0

謝謝,男人真的幫我分配!!:D我以爲我註定要改變整個項目結構!!:D非常感謝你!!:D – Titler