We have just learned about while and for loops. Let's learn about how you can use loops to ensure that a user enters valid input.
When dealing with user input, it's crucial to validate the data before using it in your program. Incorrect input can lead to errors or undesired behavior.
Input validation is the process of checking if the data provided by the user meets certain criteria.
Let's begin with the simple example below. A program to multiply the user's input by 10.
We are 'trusting' that the user will type in a correct input, an integer. Try typing in a string, such as 'cat'.
You will get the following cryptic output. But essentially this is just a crash, followed by an error message.
The error message explains that we tried to use a string when it was expecting an integer.
Traceback (most recent call last):
File "/tmp/sessions/f81cb2293bb5d390/main.py", line 2, in <module>
result = int(user_input) * 10
ValueError: invalid literal for int() with base 10: 'cat'
There are ways to catch and handle these errors, but we are going to learn that in the next project.
For now, let's use a Python function that can determine whether a given string is numeric or not: isdigit()
Run the program and try a string such as 'cat', then run it again and try a number such as 7.
Much better, it doesn't crash and the error message is a bit more helpful. However, the program just ends and the user can't try again.
We can modify the above example.
Instead of using an if statement, we use a while loop
We are checking if the input is not a number
If it's not, we inform the user of "invalid input" and then ask for input again.
If the input is valid, the loop does not run at all
You can use a while loop to check for all sorts of input, not just numbers.
As the input validation begins to get more complex, we should explore a couple of further techniques.
Two key words, continue and break, help you control the flow within loops more effectively.
continue skips back to the start of the loops and break stops the loop entirely.
In the example above, we simply skip over printing the value 3.
In contrast, this code above completely stops the loop when the value reaches 3.
Let's combine these concepts to begin checking multiple conditions when validating user input.
I want to write a program that checks that for valid variable names in Python. These must not start with a digit.
Check to see if it is empty, if so print a helpful error message
Check to see if it starts with a digit, if so print a helpful error message
If it is valid, let the user know
In your lab exercises, you will need to utilise these ideas to solve the input validation problems.
Complete the following requirements:
Create a menu. Use a while loop to validate the menu choices. 1 and 2 are valid, 3 exits the program.
1 and 2 print a message of your choice and then loop again. Anything else prints an error message and loops again.
Use a while loop to continue prompting the user until they enter an integer between 1 and 100.
Write a loop that iterates through numbers from 1 to 100.
The loop skips even numbers using continue and stops when it reaches 50 using break.
Press Ctrl + F5 to run the program or open a terminal and type python lab3.py
You should now know how to validate user input and check for multiple conditions using loops.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 3 complete"
Press Commit to main
Press Push origin
Here is a video from Harvard's CS50P course that covers the content of the this lab. Optional, but useful if you need further explanation.