Python input() Tutorial: Getting User Input in Python
Last updated 5 months, 1 week ago | 248 views 75 5

Getting input from users is essential for interactive programs. In Python, the input()
function allows your program to read data from the user via the console.
This tutorial covers:
-
How
input()
works -
Converting input data types
-
Formatting prompts
-
Using input in conditionals and loops
-
Common mistakes and best practices
-
A complete example project
What is input()
?
Python’s built-in input()
function reads a line of text entered by the user and returns it as a string.
name = input("Enter your name: ")
print("Hello, " + name + "!")
Sample Output:
Enter your name: Alice
Hello, Alice!
Note: Everything returned by
input()
is of typestr
(string), even if the user enters a number.
Converting Input Types
To use numbers, convert the string input using int()
, float()
, etc.
Example: Convert to Integer
age = int(input("Enter your age: "))
print("You will be", age + 1, "next year.")
Example: Convert to Float
price = float(input("Enter the price: "))
print("With tax:", price * 1.07)
⚠️ If the input cannot be converted, Python will raise a
ValueError
. Usetry-except
to handle this gracefully.
Validating User Input
Always validate user input when expecting specific formats or data types.
Example: Using try-except
try:
score = int(input("Enter your score: "))
print("Score recorded:", score)
except ValueError:
print("Invalid input. Please enter a number.")
Input Inside Loops
You can use input()
in loops to keep prompting until the user enters valid data.
Example: Input Until Correct
while True:
answer = input("Type 'yes' to continue: ").lower()
if answer == "yes":
break
print("Try again!")
Formatting Prompts
Make prompts more user-friendly by:
-
Using descriptive messages
-
Including units or formats in the prompt
Example:
height = float(input("Enter your height in meters: "))
Real-World Input Example: Simple Calculator
print("Simple Calculator")
try:
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2
else:
result = "Unknown operator"
print("Result:", result)
except ValueError:
print("Invalid input! Please enter numbers.")
✅ Tips for Using input()
Tip | Description |
---|---|
Use strip() |
Removes leading/trailing spaces |
Use .lower() or .upper() |
Normalize user input for comparison |
Validate input | Use try-except or conditions |
Reuse input logic | Encapsulate in functions for reusability |
⚠️ Common Pitfalls
Mistake | Explanation | Fix |
---|---|---|
Forgetting to convert input | Input is always string | Use int() , float() , etc. |
Not handling invalid input | Program crashes | Use try-except |
Assuming case sensitivity | "Yes" != "yes" | Use .lower() or .upper() |
Confusing print and input | print() shows output, input() gets input |
Don’t mix them up |
Complete Example: Interactive Greeting
def greet_user():
name = input("What is your name? ").strip().title()
try:
age = int(input("How old are you? "))
print(f"\nHi {name}, you are {age} years old!")
if age < 18:
print("You're still a minor.")
else:
print("You're an adult.")
except ValueError:
print("Invalid age. Please enter a number.")
greet_user()
Conclusion
The input()
function is your gateway to creating interactive Python programs. Whether you're building games, forms, or calculators, knowing how to collect and validate user input is essential.
Remember:
-
Always convert and validate input.
-
Use friendly, clear prompts.
-
Wrap input logic in functions for better reuse and testing.