Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get user input in Python

Introduction

In this article, we will learn about user input in Python programming. User input is essential for any software program, as it allows developers to interact with their users and obtain information from them. As a beginner, learning how to get user input in Python is an essential skill that will help you build interactive applications.

What is user input?

User input is any information that a user provides to a software program. This can be in the form of text, numbers, or even files. The program takes this information and processes it to perform specific tasks or generate outputs based on the input. User input is a way for users to communicate with a software program and tell it what they want it to do.

The input() function in Python

Python provides a built-in function called input() that allows us to get user input in the form of a string. The input() function takes one optional argument, which is a string that gets displayed as a prompt for the user. The function then returns the user's input as a string.

Here's a basic example to demonstrate the input() function:

name = input("Please enter your name: ")
print("Hello, " + name)

This code will prompt the user to enter their name and then print a greeting using the provided name.

Getting numerical input

Often, we need to get numerical input from the user. Since the input() function returns a string, we need to convert the string to a number. We can do this using the int() and float() functions.

The int() function is used to convert a string to an integer, while the float() function is used to convert a string to a floating-point number. Here's an example:

age = int(input("Please enter your age: "))
print("You are " + str(age) + " years old.")

In this example, we first use the input() function to get the user's age as a string. Then, we use the int() function to convert the string into an integer. Finally, we print the user's age in a sentence. Note that we have to use the str() function to convert the integer back to a string before concatenating it with the other strings.

Here's another example that demonstrates how to get a floating-point number as input:

price = float(input("Please enter the price of the item: "))
print("The price of the item is $" + str(price))

Handling multiple inputs

In some cases, you might need to get multiple inputs from the user. To do this, you can use the input() function multiple times. Here's an example:

first_name = input("Please enter your first name: ")
last_name = input("Please enter your last name: ")
full_name = first_name + " " + last_name
print("Your full name is " + full_name)

In this example, we use the input() function twice to get the user's first and last names. We then concatenate the two names with a space in between to create the full name.

If you want to get multiple inputs in a single line, you can use the split() function. The split() function takes a string and splits it into a list of substrings based on a specified delimiter. By default, the delimiter is a whitespace character (space, tab, or newline).

Here's an example that shows how to get multiple inputs in a single line using the split() function:

name_and_age = input("Please enter your name and age, separated by a space: ")
name, age = name_and_age.split()
print("Your name is " + name + " and you are " + age + " years old.")

In this example, we first get the user's input as a single string. Then, we use the split() function to split the string into a list of two substrings based on the space character. Finally, we assign the two substrings to the name and age variables using tuple unpacking.

Validating user input

When getting user input, it's essential to check if the input is valid. This means making sure the input meets certain requirements, such as being a number within a specific range or a string with a specific length.

Here's an example that demonstrates how to validate user input:

age = int(input("Please enter your age: "))

if age < 0:
    print("Error: Age cannot be negative.")
elif age > 150:
    print("Error: Age cannot be greater than 150.")
else:
    print("Your age is " + str(age))

In this example, we first get the user's age as an integer. Then, we use an if-elif-else statement to check if the age is within the valid range (0 to 150). If the age is not within this range, we print an error message. Otherwise, we print the user's age.

Handling errors in user input

Sometimes, the user might provide an input that causes an error when trying to process it. For example, the user might enter a non-numeric value when we expect a number. In such cases, we can use exception handling to catch the error and prompt the user to enter a valid input.

Here's an example that shows how to handle errors in user input using exception handling:

while True:
    try:
        age = int(input("Please enter your age: "))
        if age < 0:
            print("Error: Age cannot be negative.")
        elif age > 150:
            print("Error: Age cannot be greater than 150.")
        else:
            print("Your age is " + str(age))
            break
    except ValueError:
        print("Error: Please enter a valid number.")

In this example, we use a while loop to keep asking the user for input until a valid input is provided. Inside the loop, we use a try block to attempt to get the user's age as an integer and check if it's within the valid range. If an error occurs while trying to convert the input to an integer, we catch the ValueError exception and prompt the user to enter a valid number. If the input is valid, we break out of the loop.

Conclusion

In this article, we covered how to get user input in Python using the input() function. We also discussed how to get numerical input, handle multiple inputs, validate user input, and handle errors in user input. By understanding these concepts, you can create interactive Python programs that allow users to provide information and receive customized outputs.

As you continue learning Python, remember to practice these techniques by building small projects that require user input. This will help you become more comfortable with handling user input and create more complex applications in the future.