while True inside while True

Asked

Viewed 417 times

0

How do I end the while True session completely inside another one? Ex: I did it with break, but it’s only finishing it inside another (while True). look at an example below.

while True:
    test = input('Digite pra ir pro proximo while True: ')
    while True:
        test1 = input('Digite (S) pra sair totalmente: ').upper()
        if test1 == 'S':
            break
  • yes, the break only comes out of the execution of the last while... how about instead of using a while true, put a condition that can come out on its own? , for example something like while test1 != "S"?

  • 1

    It doesn’t seem to make much sense, it certainly should write this code differently and then this problem wouldn’t exist.

  • while True: test = input('Type to go in the next while True: ') Test1 = input('Type (S) to exit fully: '). upper() while Test1 != " S": Test1 = input('Type (S) to exit fully: '). upper() Else: break

  • would look that way?

  • Maniero, and what other way?

2 answers

0

If it is a situation created as a hobby or puzzle, one can raise a exception treated:

while True:
  try:
    test = input('Digite pra ir pro proximo while True: ')
    while True:
        test1 = input('Digite (S) pra sair totalmente: ').upper()
        if test1 == 'S':
            raise RuntimeError()
  except RuntimeError:
    break

But the ideal is refactoring of the code:

test = None
while True:
  if test is None:
    test = input('Digite pra ir pro proximo while True: ')
  else:
    test1 = input('Digite (S) pra sair totalmente: ').upper()
    if test1 == 'S':
       break

0

  • 1

    and if you need to process something within the first while, or still after it? it doesn’t seem like a good solution

  • In this case, you should not use while true for your second while but rather a condition that you can control, as you commented: while Test1 != " S". But as the question begins with "how do I end the session totally in while True within another", I believe that the wish is not to execute something in the first while but just to finish the execution.

  • that’s the same point, maybe put this in your answer get better... it’s like "look, Return would do it, but it’s not the best solution, bla bla bla", it’s nice to always give a better solution. is like that joke "my code is giving error! comments him that gives error" :)

  • It is not logical to use two While True, use only one and control what you want with if

Browser other questions tagged

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