It doesn’t seem like a good idea. It seems that the while
is part of the function algorithm (it is one that asks for a data validating it) and should not be separated. Even the name of the function is not good and so already indicates that there is something wrong there.
If the noose were part of the game as a whole there would be enough to do, but it does not have the break
. The validation function does not come out until something valid is typed, the loop is purposefully infinite. Of course, there is an output, but then as it is a function, it is not of the loop that you want to leave, it is of the function. The break
works too, because there is a return
implicit at the end of every function, and if there is nothing after the loop block, it is it that will run, but I find it simpler to be explicit in the output.
def pedeChute():
while True:
try:
chute = int(input("chute: "))
if chute == 0:
return chute
except:
pass
def jogo():
while True:
#algo aqui
chute = pedeChute() #sempre será válido
#algo aqui
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
If it makes sense to have the comparison outside the function (it doesn’t look but it can be), then it would only be a way out of the game loop and not a validation, then it could do so:
def pedeChute():
while True:
try:
chute = int(input("chute: "))
return chute
except:
pass
def jogo():
while True:
#algo aqui
chute = pedeChute() #sempre será válido
if chute == 0:
break
#algo aqui
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Note that in the function that asks for the data does not make a complete validation, only analyzes if a number has been typed.
This is a typical junior mistake (or train) and at least at this point gives an indication that wants to reach full (some people do not want, they will be stubborn and will not ask, make mistakes all their lives, and so will not evolve). It is not a mistake of code, but of definition of responsibility, a junior misses this, a full can no longer, so there are many people with this title but not ability to do so. Learning this already helps to move to the next level, but understanding that when you do not know if you ask and listen to who already has the experience is what makes evolve the most.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.
– Maniero