In this tutorial we want to learn about Python Control Structures for Handling User Input, so handling user input is an important task in many programs. Python provides different control structures, and you can easily use them for handling user input and ensure that the input meets the program requirements. in this article we want to talk that how to use Python control structures to handle user input.
First of all let’s talk that how we can get user input in Python, so in Python you can use input() function to prompt the user for input. this function displays a message to the user and it waits for the user to enter input. after that the user has entered input, than the function returns input as a string.
For example we want to prompt the user for their name and after that we want to greet them. we can do this using this code.
1 2 |
name = input("Please enter your name: ") print("Hello " + name) |
Run the code and this will be the result
Handling User Input with Control Structures
After that we have user input, we often need to validate it and ensure that it meets our program requirements. Python provides different control structures to handle user input and ensure that it meets our requirements. these control structures are if statements, while loops and exception handling.
If Statements in Python
Python if statements allows us to check if a condition is true or false. we can use if statements to validate the user input.
For example we want to prompt the user for a number between 1 and 10. we can use this code to validate user input.
Run the code and this will be the result
While Loops in Python
Python while loops allows you to repeat a block of code as long as a condition is true. we can use while loop to prompt the user for input until they enter valid input.
For example we want to prompt the user for positive integer. we can use this code to prompt the user until they enter a valid input:
1 2 3 4 5 6 7 8 9 10 11 12 |
num = -1 while num < 0: num = input("Please enter positive integer: ") if num.isdigit(): num = int(num) else: print("Sorry you did not enter valid number.") num = -1 print("Thank you for entering valid number.") |
Run the code and this will be the result
Python Exception Handling
Python Exception handling allows us to handle errors that occurs during program execution. we can use exception handling to handle user input errors and ensure that our program does not crash.
For example we want to prompt the user for a number, if the user enters non numeric value, our program will crash. for this we can use exception handling to handle this error and display an error message to the user.
Run the code and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email