A step-by-step guide to infinite loops and try/except statements
Photo by Sigmund on Unsplash
User input is a tricky thing. I learned very early on that just because you prompt the user?s ?email address? or ?age?, you?re not going to get a garbled mess of characters.
When building, you have to assume that the user is going to screw things up?
To keep our scripts functioning through malice and stupidity, we need to set up proper mechanisms for requesting command line input from users.
Let?s go through some of the basics and build a solid plan for requesting user input continuously until they enter an appropriate response.
Required Tools
Before we get started, let?s take inventory of what we?ll be using in our code.
- The input() function: This function takes a single string argument which is the prompt shown on the screen. The user will then be able to submit a response that will be returned by the function.
- while loop: I recently wrote about the difference between while and for loops. Essentially, we?re picking a while loop since we do not know the number of iterations that will be needed.
- try/except statement: The try/except statement will serve as our first line of defense to safeguard against values that would throw an exception. I?ve written a similar primer on try/except.
- if statement with break: The combination of an if and break statement will help us evaluate custom conditions for validity?criteria that would not throw an exception, but do not make sense.
Building the Loop
Alright, now that we?ve introduced the four components of our solution, we?re going to be requesting the user to enter their age. Let?s get to work!
Create an infinite loop
The first step is to create an infinite loop. Normally, when you hear infinite loop, it?s in the context of ?I accidentally wrote an infinite loop.? Don?t worry, this time we want one.
while True: pass
I?m using the keyword pass as a syntactic placeholder. Do not run this code yet.
Add try/catch statement
Inside our infinite loop, the first step is to add our try/except statement.
while True: try: pass except Exception as e: print(e)
What happens here is that everything inside the try portion of the statement will attempt to be executed. If any exception is thrown, then the except clause will execute.
In our case, this means printing the error message, which is assigned to the variable e.
Request user input
Now it?s time to ask the user for input. We?ll use the input() function, which by definition returns a string. We?re also going to be converting to an integer since we?re requesting the user?s age.
while True: try: age = int(input(“Enter your age: “)) except Exception as e: print(e)
Define positive case
Our last step, we?re going to define the criteria for a valid response so that we can exit the loop. Custom logic is required here since Python has no concept of what an ?age? is?the interpreter does not know that a negative age makes no sense.
Finally, now we can test our code! Here?s a sample of entering some bogus values.
Conclusion
With this setup, you?re able to customize exactly what you?d like to request.
Want to handle exceptions differently? You can specify exactly what type of exception you catch and handle each independently. Want to change the criteria for a positive value? Simply update the if statement.
Do you have a different method for requesting user input that meets the same criteria? Share your thoughts below. Thanks for reading!