Python > Core Python Basics > Input and Output > Reading Input from the User (input())
Basic User Input with `input()`
This snippet demonstrates how to read user input from the console using the `input()` function in Python. The `input()` function pauses the program and waits for the user to type something and press Enter. The entered text is then returned as a string.
Basic Input Example
This code prompts the user to enter their name and age. The `input()` function displays the prompt message (e.g., 'Please enter your name: ') to the user. The user's input is then stored in the `name` and `age` variables, respectively. Note that the input is always read as a string, even if the user enters a number.
name = input("Please enter your name: ")
print("Hello, " + name + "!")
age = input("Please enter your age: ")
print("You are " + age + " years old.")
Converting Input to a Number
Since `input()` always returns a string, you often need to convert the input to a different data type (e.g., integer, float) using functions like `int()` or `float()` if you're expecting numeric input. In this example, we convert the age from a string to an integer and then perform arithmetic operations on it. We also show how to convert to a floating point number.
age_str = input("Please enter your age: ")
age = int(age_str)
print("In 10 years, you will be " + str(age + 10) + " years old.")
height_str = input("Please enter your height in meters: ")
height = float(height_str)
print("Your height is " + str(height) + " meters.")
Concepts Behind the Snippet
The `input()` function is a fundamental part of interactive programs. It allows the program to receive data from the user while the program is running. Understanding how to use `input()` is essential for building applications that require user interaction.
Real-Life Use Case
Imagine a simple calculator program. The program would use `input()` to get the two numbers the user wants to add, and then display the result. Web applications also indirectly use input mechanisms, usually through HTML forms, where the submitted data eventually makes its way to the server-side Python code.
Best Practices
Always validate user input. Assume the user might enter something unexpected (e.g., text when a number is expected). Use `try-except` blocks to handle potential errors during type conversion. For example, if the user enters 'abc' when the program expects an integer, `int('abc')` will raise a `ValueError`. Handle this exception gracefully by displaying an error message and prompting the user again.
Interview Tip
Be prepared to discuss the importance of validating user input, especially when working with sensitive data or performing critical operations. Mention the potential for injection attacks if input is not sanitized or validated correctly.
When to Use `input()`
Use `input()` when you need to get information from the user while the program is running. This is common in interactive applications, command-line tools, and scripts that require user configuration.
Alternatives
For non-interactive programs or when input is provided through files or arguments, alternatives include reading from files using `open()` or using the `argparse` module to handle command-line arguments. Libraries like `getpass` can be used to securely obtain passwords from the user.
Pros
Cons
FAQ
-
What happens if the user doesn't enter anything and just presses Enter?
The `input()` function will return an empty string (``). You'll need to handle this case in your code if an empty input is not valid. -
How can I prevent the user from entering too much text?
You can limit the amount of text the program processes after receiving the input by truncating the string using slicing (`name = name[:50]` to keep only the first 50 characters, for example). -
Is there a way to hide the input from the user, like when asking for a password?
Yes, you can use the `getpass` module for that. The `getpass.getpass()` function will prompt the user for input without displaying it on the screen.