User Input in Python
User input allows a Python program to receive data directly from the user while the program is running. This interaction makes programs dynamic and useful in real-world applications such as calculators, login systems, form processing, and command-line tools.
Python provides a built-in function called input() to collect data from the user through the keyboard.
What is the input() Function?
The input() function is used to take input from the user. When the program reaches this function, it pauses and waits for the user to enter a value. Once the user enters the value and presses Enter, the program continues execution.
In this example, the program asks the user to enter their name and then prints a greeting message.
Input Always Returns a String
By default, the value returned by the input() function is always treated as a string, even if the user enters numbers.
The output will show that the data type is str (string).
Converting User Input to Numbers
If you want to perform mathematical operations on user input, you need to convert the input into numeric data types such as int or float.
Using int() for Integer Input
Using float() for Decimal Input
Here, the input is converted into numeric values so arithmetic operations can be performed.
Taking Multiple Inputs
Python allows users to input multiple values in a single line and then split them into separate variables.
The split() function separates the input values based on spaces.
Taking Multiple Numeric Inputs
You can also convert multiple inputs into integers using map().
This program allows the user to enter two numbers and calculates their sum.
Real-World Example
User input is widely used in real-world applications such as calculators and form-based programs.
This program takes two numbers from the user and prints their sum.
Handling Invalid Input
Sometimes users may enter incorrect data types, which can cause errors. In such cases, error handling can be used to prevent program crashes.
This program prevents errors if the user enters invalid data.
Best Practices for User Input
- Always display a clear message when asking for input.
- Convert input values to the correct data type when necessary.
- Use error handling to prevent crashes.
- Validate user input when building real-world applications.
Conclusion
User input is an important feature in Python that allows programs to interact with users. By using the input() function along with type conversion functions such as int() and float(), developers can create dynamic and interactive applications.
In the next tutorial, we will learn about Functions in Python and how to organize reusable blocks of code.

