Input in python
Understanding the input() Function in Python
The input() function in Python is used to take user input.
When this function is called, the program pauses and waits for the user to type something and press Enter.
Basic Example of input()
Here’s a simple example:
How it works:
-
The program displays:
Enter your name: -
The user types their name and presses Enter.
-
The entered text is stored in the variable
name. -
The program then prints a welcome message with the user’s name.
Example with Multiple Inputs
You can use input() multiple times to collect different pieces of information:
What happens here:
-
The program first asks for your name, then for your age.
-
Both inputs are stored in variables (
nameandage). -
The program prints both values.
Taking Integer Inputs and Performing Addition
By default, input() always returns a string.
If you want to do math with numbers entered by the user, you need to convert the string to an integer using int().
Example:
How it works:
-
The program asks for two numbers.
-
The inputs are initially stored as strings (
xandy). -
int(x)andint(y)convert the inputs to integers. -
The sum is calculated and printed.
Shortcut: Convert Input to Integer Immediately
You can simplify your code by converting the input directly in the input() call:
๐This approach is cleaner and easier to read!
Using input() in Online Coding Environments
When you run a program that uses input(), you’ll see prompts like this:
The program will output:
Special Note: Competitive Programming
In competitive programming, it’s often better to avoid adding text prompts inside input().
Why? Because online judges expect only the result, not extra text.
Example without prompts:
If you enter:
The program will simply output:
๐ This avoids unwanted extra text and ensures your output matches exactly what is expected.
Key Points to Remember
✅ The input() function always returns a string. Use int() (or float()) to convert when needed.
✅ In competitive programming, avoid using prompts like "Enter a number:" in your input() calls.
✅ Make sure your program prints only the required output, especially when an exact format is expected.
๐Now you know how to use the input() function to interact with your users!
This is one of the simplest ways to make your Python programs more dynamic and fun.