User Input in Python
Python allows programs to interact with users by accepting input at runtime.
This makes programs dynamic, interactive, and more useful.
The built-in input() function is used to read data entered by the
user.
Basic User Input
When Python encounters the input() function, program execution pauses until
the user types something and presses Enter.
Example: Read and Display User Input
Output:
Welcome, John!
Using a Prompt Message
You can display a message directly inside the input() function.
This shows the message and waits for user input on the same line.
Example: Input with Prompt
Output:
Hello, Emma
Taking Multiple Inputs
A program can request multiple inputs.
Python pauses at each input() call until the user responds.
Example: Multiple User Inputs
Output:
What is your favorite food? Biryani
Which year were you born? 1998
You live in Chennai, love Biryani, and were born in 1998.
Input Is Always a String
Data received using input() is always of type string, even if the user
enters numbers.
To perform calculations, you must convert the input to a numeric type such
as int() or float().
Example: Convert Input to Number
Output:
Circle area: 78.50
Validating User Input
User input should always be validated to prevent errors.
If a user enters invalid data, the program should handle it gracefully instead of crashing.
Example: Validate Numeric Input
Output:
Invalid input. Please enter a numeric value.
Enter a valid number: 42
Input accepted. Thank you!
Why Input Validation Matters
- Prevents runtime errors
- Improves user experience
- Makes programs more reliable
- Helps handle unexpected user behavior
