Skip to content
Advertisement

Should I be using an if statement or a loop?

It’s me, your friendly Python noob!

I’m working on this program and I’m trying to figure out how to get the program to stop if the number exceeds a certain threshold OR if the user enters anything other than a number to loop back around and try again.

Here is what I have so far:

JavaScript

The if statements in main() are printing what I want, but what I’m trying to do is to have the program stop under certain conditions. I know a while or for loop would help, but I can’t figure out how to set it up.

What I ended up trying next was this:

JavaScript

That didn’t work at all.

At this point I’m at a loss. Would anyone be able to nudge me in the right direction? I feel like the if statements are not the right way to go. I feel using a while loop would work better and give me the result I’m looking for.

God, I hope that makes sense.

Thanks folks!

Advertisement

Answer

This idiom should work for this scenario:

JavaScript

What we do here is loop infinitely, unconditionally, using while True. Then, depending on what the user enters,

  • If the user enters not a number, then we print an error message and jump back to the start of the loop with continue
  • Otherwise, if the user enters a number greater than 300, print a different error message and restart the loop
  • If the user’s input is valid and hasn’t hit either of those, then set ticket_a_purchased and break out of the loop.

This type of idiom works for most “conditional inputs”, where the input may or may not be valid and you want to keep asking until it is, but it’s rarely the best solution for other scenarios. Whenever reasonably possible you want to try to have a while loop with an actual condition that can be satisfied on its own. If you do this, you need to be very careful that every possible path through the loop is covered one way or another, or you could find yourself in an unbreakable loop.

Advertisement