In this tutorial, we’ll cover how to get input from the user in Python. This can be useful in a variety of applications, from simple console-based games to more complex command-line tools. Using the built-in input()
function, you can easily prompt the user for information and store it in a variable for later use.
Note: This tutorial assumes that you are using Python 3. If you’re using Python 2, the function to use is raw_input()
instead of input()
.
Step 1: Basic Input
The simplest way to get input from the user is to use the input()
function. This function pauses the program and waits for the user to enter some text, then returns that text as a string.
Here’s a basic example:
1 2 |
name = input("What is your name? ") print("Hello, " + name + "!") |
This code prompts the user for their name, then prints a personalized greeting.
Output:
What is your name? John Hello, John!
Step 2: Converting Input to an Integer
If you want to get an integer input from the user, you’ll need to convert the string returned by input()
using the int()
function.
Here’s an example that demonstrates this:
1 2 3 |
age_str = input("How old are you? ") age = int(age_str) print("In 5 years, you'll be " + str(age + 5) + " years old.") |
This code prompts the user for their age, then calculates and prints how old they’ll be in five years.
Output:
How old are you? 25 In 5 years, you'll be 30 years old.
Step 3: Handling Invalid Input
Sometimes, users might enter invalid input, like a non-numeric value when you’re expecting a number. To handle this situation, you can use a try
–except
block to catch any exceptions thrown during input conversion.
Here’s an example:
1 2 3 4 5 6 |
try: weight_str = input("How much do you weigh (in kilograms)? ") weight = float(weight_str) print("You weigh " + weight_str + " kg.") except ValueError: print("Invalid input. Please enter a number.") |
This code attempts to convert the user’s input to a floating-point number. If the conversion fails (due to a ValueError
), an error message is displayed instead of crashing the program.
Output:
How much do you weigh (in kilograms)? abc Invalid input. Please enter a number.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
name = input("What is your name? ") print("Hello, " + name + "!") age_str = input("How old are you? ") age = int(age_str) print("In 5 years, you'll be " + str(age + 5) + " years old.") try: weight_str = input("How much do you weigh (in kilograms)? ") weight = float(weight_str) print("You weigh " + weight_str + " kg.") except ValueError: print("Invalid input. Please enter a number.") |
Conclusion
With the input()
function and a few basic techniques, you can easily get input from users in Python. This powerful feature allows you to build interactive programs that are responsive and flexible.
Keep in mind that handling invalid input is important for a robust user experience, so make use of try
–except
blocks when working with user inputs.