How to Read User Input From the Keyboard in Python

How to Read User Input From the Keyboard in Python

by Vincent Matinde Feb 21, 2024 basics best-practices

You may often want to make your Python programs more interactive by responding dynamically to input from the user. Learning how to read user input from the keyboard unlocks exciting possibilities and can make your code far more useful.

The ability to gather input from the keyboard with Python allows you to build programs that can respond uniquely based on the preferences, decisions, or data provided by different users. By fetching input and assigning it to variables, your code can react to adjustable conditions rather than just executing static logic flows. This personalizes programs to individual users.

The input() function is the simplest way to get keyboard data from the user in Python. When called, it asks the user for input with a prompt that you specify, and it waits for the user to type a response and press the Enter key before continuing. This response string is returned by input() so you can save it to a variable or use it directly.

Using only Python, you can start building interactive programs that accept customizable data from the user right within the terminal. Taking user input is an essential skill that unlocks more dynamic Python coding and allows you to elevate simple scripts into personalized applications.

How to Read Keyboard Input in Python With input()

You can create robust and interactive programs by taking advantage of input(). It opens up possibilities for creating scripts that respond dynamically based on adjustable conditions, personalized data, and real-time decision-making from the user. It is an ideal option when you want to read keyboard input with Python.

Getting started is straightforward. Just launch the Python interpreter shell, and you can immediately utilize input() for basic interactivity.

To try it, first open your terminal and launch the Python REPL by typing python and hitting Enter. This will display the familiar >>> Python prompt indicating the REPL is ready. Use input(), passing any string in the parentheses:

Python
>>> input("What is your name? ")
What is your name? Vincent
'Vincent'

Once you execute the code, the string that you specified in input() will be rendered on screen, and you’ll be able to type in any response. Your response will also print to the screen once you press Enter. This is because the REPL automatically prints return values—in this case, the value returned by input().

The best practice when using input() is to assign it to a variable that you can use later in your code. For example, you can ask the user to type in their name. Assign input() to the name variable:

Python
>>> name = input("What is your name? ")
What is your name? Vincent

This prints the prompt What is your name? and pauses, waiting for keyboard input. After the user types a name and presses Enter, the text string is stored in the name variable. This time, your input won’t automatically print in the REPL, because a variable stores the value instead.

You can now use the variable in any part of your code in the same session, like printing a personalized greeting:

Python
>>> print(f"Hello there, {name}!")
Hello there, Vincent!

Your program reacted based on the custom name that you provided. It used the name that you gave in the input() request.

This is the essential pattern when working with Python keyboard input:

  1. Call input() with a prompt explaining what to enter.
  2. Assign the result to a descriptively named variable.
  3. Use that variable later in your code.

By following this template, you can start building all types of interactive scripts tailored to custom data from different users. Your programs can gather input of all types, such as names, numbers, and lists, making it quite handy in processing data from your users.

This is just the initial step that you can take in using input() in your interactive program. There are other modifications that you can make to ensure that the function takes in all manner of data types.

Reading Specific Data Types With the Input Function

The general rule for input() is that it collects textual input and delivers strings. Your code often needs numbers, Booleans or other data types instead. For example, maybe you need to get integers for math operations, floats for calculations with decimals, or Booleans for logical conditions.

As input() returns strings, you need to convert all the input into the targeted desired data type before using it in your code. If you ask for numerical input, the outcome will still be returned as a string:

Python
>>> age = input("How old are you? ")
How old are you? 35

>>> type(age)
<class 'str'>

The input function accepts the numerical value. When you check the age variable, its type is a string. This is the function’s default behavior. But what if you need to do calculations on those numbers? You can convert the string input to integers and floats.

Luckily, Python makes it straightforward to convert input strings into any data type needed. You can pass the input() result into a type conversion function like int(), float(), or bool() to transform it on demand. For example, using the int() type conversion will convert the input to the desired integer type:

Python
>>> age = int(input("How old are you? "))
How old are you? 35

>>> type(age)
<class 'int'>

You wrapped input() in a type conversion function, int(). This converts any numeric string into an integer. Now when you check the type of the age variable, it returns int.

You can use the same approach to convert numerical inputs to floats. For example, you might want to log the user’s weight:

Python
>>> weight = float(input("What is your weight in pounds? "))
What is your weight in pounds? 165

>>> weight
165.0

>>> type(weight)
<class 'float'>

In the example, you convert "165" to the floating-point value 165.0. You check the type of weight to confirm that the conversion worked as expected.

You’ll use int() or float() whenever you need a numeric value. The input will always start as a string, but you can convert it to numbers as needed. This is an important point to note to ensure you get the desired results from your interactive program.

Handling Errors With input() in Python

Errors can occur if you wrap input() in a conversion function, and it receives a different data type than what it expected. The program will then raise a ValueError and terminate. This is not the way that you’d want your program to behave. Try out the next example to see how the program will reject a different data type input:

Python
>>> age = int(input("How old are you? "))
How old are you? Thirty-five
Traceback (most recent call last):
  ...
ValueError: invalid literal for int() with base 10: 'Thirty-five'

This code raises a ValueError since Python can’t convert "Thirty-five" into an integer. Your users might not comprehend the error.

To handle such a case, you can catch the exception before your user sees it. In the next example, you’ll write a script within a Python file. Create a folder within your preferred directory.

Open your favorite editor and create a new Python file, which you should save to the folder that you just created. You can name it whatever you want. In this case, it’s named integer_input.py. Enter the following code:

Python integer_input.py
while True:
    try:
        age = int(input("How old are you? "))
    except ValueError:
        print("Please enter a number for your age.")
    else:
        break

print(f"Next year, you'll be {age + 1} years old")

The above code has utilized the tryexcept code blocks in handling exceptions. The content inside the try block is the code that might raise an error. In this example, the code is trying to convert user input to an integer. The except block is what gets executed if there’s an error in the corresponding try block. For example, it might catch a ValueError.

Save your file and then, in your terminal, navigate to where you’ve saved this Python file. You can execute it with this command:

Windows PowerShell
PS> python integer_input.py
How old are you? Thirty-five
Please enter a number for your age.
How old are you? 35
Next year, you'll be 36 years old

The content of your file will load, asking you How old are you?. Now if you enter a string like "Thirty-five", your program will gracefully handle the error and give you information on why your input wasn’t successful. It’ll give you another chance to enter the correct values, and it’ll execute to the end.

Converting input with int() and float() gives you the flexibility to accept numeric and textual input. Handling the ValueError cases makes the program more robust and user-friendly when incorrect types are entered, and it gives meaningful error messages to the user.

Reading Multiple Entries From User Input

There are scenarios in which your program would require multiple entries from a user. This can be the case when your user might have multiple answers to a question.

In Python, the list data type allows you to store and organize a sequence of elements. Lists are good at storing multiple entries from users. You can request that users enter multiple inputs, which your program can store in a list. Open your folder and create a new Python file, list_input.py. Enter the following code:

Python list_input.py
user_colors = input("Enter the three secondary colors separated by commas: ")
colors = [s.strip() for s in user_colors.split(",")]

print(f"List of colors: {colors}")

This Python code takes input from the user, expecting three secondary colors separated by commas. You use a list comprehension to iterate over comma-separated substrings. For each substring, the .strip() method removes any leading or trailing whitespaces. The processed list of colors is then printed out.

In your terminal, run the Python file to see the code in action:

Windows PowerShell
PS> python list_input.py
Enter the three secondary colors separated by commas: orange, purple, green
List of colors: ['orange', 'purple', 'green']

Your program will place whatever the user types as a string within a list. It’ll then print the list out on the terminal. In this case, the program doesn’t check if the entries are correct. For example, you could type red, yellow, blue, and it’d render them on the terminal.

What if you wanted to check the entries and compare them with the correct answers before printing them on the terminal? That’s possible.

You can make even more dynamic programs, such as quizzes, using input() together with lists, sets, or dictionaries. Create a new Python file called multiple_inputs.py and save it in your folder. In this file, add this code to ask for multiple inputs from the user:

Python multiple_inputs.py
print("Name at least 3 colors in the Kenyan flag.")

kenya_flag_colors = {"green", "black", "red", "white"}
user_colors = set()

while len(user_colors) < 3:
    color = input("Enter a color on the Kenyan flag: ")
    user_colors.add(color.lower())

if user_colors.issubset(kenya_flag_colors):
    print(
        "Correct! These colors are all in the Kenyan flag: "
        + ", ".join(user_colors)
    )
else:
    print(
        "Incorrect. The colors of the Kenyan flag are: "
        + ", ".join(kenya_flag_colors)
    )

This code asks the user to input three of the colors of the Kenyan flag, and it checks if they guessed correctly by comparing the input to the kenya_flag_colors set. It uses a while loop to repeatedly prompt the user for a color input and adds it to user_colors. The loop runs as long as user_colors has fewer than three items.

You use the .lower() string method to convert all inputs into lowercase strings. By converting each color to lowercase, you ensure a case-insensitive match during the comparison since all the colors in kenya_flag_colors are also in lowercase.

For example, if the user enters Green, the comparison will still recognize it as a correct answer due to the uniform lowercase conversion.

Once the loop ends, the code then checks if each of the user’s guesses is one of the actual colors. If so, a success message is printed along with the user’s colors. If not, a failure message is printed with the actual Kenyan flag colors.

Now you can run the multiple_inputs.py file in your terminal to see the code in action:

Windows PowerShell
PS> python multiple_inputs.py
Name at least 3 colors in the Kenyan flag.
Enter a color on the Kenyan flag: Red
Enter a color on the Kenyan flag: Yellow
Enter a color on the Kenyan flag: Green
Incorrect. The colors of the Kenyan flag are: green, red, black, white

In these examples, you use input() with a list or a set to repeatedly prompt for user input and collect the results. You can then validate the input against expected values to provide feedback to the user.

Here’s another example of how you can collect user input without prompting the user repeatedly, like the last example. It’s scalable since you can add more multiple-answer questions to the program. Create another Python file and name it quiz.py. Inside the file, enter the following code:

Python quiz.py
questions = {
    "What are the four colors of the Kenyan flag? ": {
        "green", "black", "red", "white"
    },
    "What are the three colors of the French flag? ": {
        "blue", "red", "white"
    },
    "How do you spell the first three numbers in Norwegian? ": {
        "en", "to", "tre"
    },
}

for question, correct in questions.items():
    while True:
        answers = {
            answer.strip().lower() for answer in input(question).split(",")
        }
        if len(answers) == len(correct):
            break
        print(f"Please enter {len(correct)} answers separated by comma")
    if answers == correct:
        print("Correct")
    else:
        print(f"No, the correct answer is {', '.join(correct)}")

In the above code, you ask your user questions, check their answers, and provide feedback. You define a dictionary named questions containing the questions as keys and the correct answers as values in sets. You can add more questions and answers to the dictionary.

The code loops through the dictionary items using .items(). Inside the loop, it enters a while True loop to repeatedly prompt the user to enter the right number of answers.

You convert the user’s input to a set after first converting it to a list with .split(). Then you compare the length of the set to see if the user gave the expected number of answers. If not, you print a message telling the user how many answers to provide and repeat the loop. Once the number of answers is correct, you move on to the next question.

You then compare the user’s answer set to the correct set using ==. If they match, you print a Correct message. Otherwise, a message shows the correct answers. You can now run the file in your terminal to see the quiz code in action:

Windows PowerShell
PS> python quiz.py
What are the four colors of the Kenyan flag? red, white, black
Please enter 4 answers separated by comma
What are the four colors of the Kenyan flag? red, white, black, green
Correct
What are the three colors of the French flag? blue, red, green
No, the correct answer is red, blue, white
How do you spell the first three numbers in Norwegian? en, to, tre
Correct

Check out the quiz tutorial to learn how to create a more complete quiz application. This will also show you how to leverage input() in your bigger and more involved projects.

Securing Sensitive User Inputs

In some situations, you’d like to hide a user’s input on the terminal. Examples would be inputs such as passwords, API keys, and even email addresses. In these conditions, you can use the standard library package getpass to achieve the intended effect.

The getpass module is specifically created to protect sensitive entries in the terminal. When using this package, the keyboard entries won’t be printed on the screen. You may even think nothing is going on, but it is. For the following example, you’ll use an email entry to showcase how you can protect sensitive information in your program.

Create a Python file in your tutorial folder and name it sensitive.py. Inside this file, type out the following code:

Python sensitive.py
import os
import getpass

def verify_email(email):
    allowed_emails = [
        email.strip() for email in os.getenv("ALLOWED_EMAILS").split(",")
    ]
    return email in allowed_emails

def main():
    email = getpass.getpass("Enter your email address: ")
    if verify_email(email):
        print("Email is valid. You can proceed.")
    else:
        print("Incorrect email. Access denied.")

if __name__ == "__main__":
    main()

This script imports getpass and uses it to hide the entry of the email address. You also have an environment variable, which is stored outside the script. You use the environment variable to avoid adding sensitive information directly to your code. You access environment variables by using getenv() in the os module.

You use the name-main idiom to check whether the Python script is being run or imported. If it’s the main script being executed, then it calls main().

The getpass.getpass() function acts like the input() function but doesn’t display anything on the screen as you type. Before you run the file, you need to store your email value outside this file. In your terminal, add the following:

Windows PowerShell
PS> set ALLOWED_EMAILS=info@example.com
Shell
$ export ALLOWED_EMAILS=info@example.com

This is a basic way of ensuring sensitive information doesn’t show up in the main program. One way you can organize environment variables related to a project is to store them in a .env file. You must make sure this file is never uploaded to public spaces such as GitHub or the cloud.

Now run the sensitive.py file and enter the email you set in the environment variable:

Windows PowerShell
PS> python sensitive.py
Enter your email:
Email is correct. You can proceed.

As you type the email address, you don’t see any values on the terminal. This ensures no prying eyes can see your sensitive information. Once you confirm, you’ll move to the next step of the program. If you get the email address wrong, then you won’t move to the next stage of the program.

Automating User Input Evaluation With PyInputPlus

You can craft robust and complicated programs based on the input() function. However, this task becomes convoluted if you have to handle all errors, check the input type, and process the results.

Third-party libraries can enhance your ability to accept and process user keyboard inputs in the terminal. One such library is PyInputPlus, which gives you handy tools to accept and handle user input seamlessly.

The PyInputPlus module is a Python package that builds on and enhances input() for validating and re-prompting user input. It was created in 2019 by Al Sweigart, author of Automate the Boring Stuff with Python, and aims to reduce tedious input validation code by providing an array of input types and validation options.

You can specify arguments like min, max, greaterThan, and other parameters when retrieving input. It will re-prompt the user if their input doesn’t pass the tests. This means you don’t have to write loops and validation to keep asking the user until they provide valid input. Other features include timeout limits, custom validation functions, and optional retry limits before rejecting input.

Overall, PyInputPlus removes the need to manually handle invalid input cases in your code. By incorporating validation and re-prompting in the input function calls, PyInputPlus reduces code duplication and helps create more robust command-line programs and interactive prompts in Python.

The following example will showcase how this module can lessen your workload. First, you need to install the PyInputPlus library in your terminal. You should do this in a virtual environment.

A virtual environment will prevent the library from being installed globally on your machine and will be limited to your project. In your prompt, enter the following command to create the virtual environment:

Windows PowerShell
PS> python -m venv venv

You’ve created a folder named venv. Activate this virtual environment using the following command:

Windows PowerShell
PS> venv\Scripts\activate
(venv) PS>
Shell
$ source venv/bin/activate
(venv)

Once you’ve activated your virtual environment, you can install PyInputPlus. You’ll use pip to install the package in the environment. In your terminal, enter this command:

Windows PowerShell
(venv) PS> python -m pip install pyinputplus

Once you’ve successfully installed the package, you can import it into the file that you’ll create next.

Create a Python file and name it inputplus.py. In the file, enter the following code that will help you experiment with PyInputPlus:

Python inputplus.py
import pyinputplus as pyip

age = pyip.inputInt(prompt="Enter your age: ", min=0, max=120)
print(f"Your age is: {age}")

With this code, you can set the age range that you’d accept in your program. If the user enters a number within the range, then your program will print the age in the console and then terminate. If not, the program will re-prompt the user to enter the age again:

Windows PowerShell
PS> python inputplus.py
Enter your age: -1
Number must be at minimum 0.
Enter your age: 125
Number must be at maximum 120.
Enter your age: 35
Your age is: 35

As you can see above, the program will re-prompt the user if they enter an age that’s less than 0 and more than 120, as specified in the code. Once an acceptable input is provided, the code continues and executes by printing the age.

With PyInputPlus, you reduce the complexity of using input() in its basic form. The code is also brief and concise, ensuring that you can then build complex interactive programs.

In the next example, you’ll create a banking app that will run in the terminal. The example will show how much you can do with the library to enhance input().

Now in the same folder, create another Python file. You can name it banking_app.py. Within the file, you can type out the following code:

Python banking_app.py
import pyinputplus as pyip

account_balance = 1000

print("Welcome to REALBank.")
while True:
    print(f"\nYour account balance: ${account_balance}")
    transaction_type = pyip.inputChoice(["Deposit", "Withdraw", "Exit"])

    if transaction_type == "Exit":
        break
    elif transaction_type == "Deposit":
        deposit_amount = pyip.inputInt(
            prompt="Enter amount (max $10,000): $", min=0, max=10000
        )
        account_balance += deposit_amount
        print(f"Deposited ${deposit_amount}.")
    elif transaction_type == "Withdraw":
        withdrawal_amount = pyip.inputInt(
            prompt="Enter amount: $", min=0, max=account_balance
        )
        account_balance -= withdrawal_amount
        print(f"Withdrew ${withdrawal_amount}.")

print("\nThank you for choosing REALBank. We hope to see you again soon!")

Once you save the file, you can run it in your terminal. Your virtual banking application will start, prompting you to enter different options.

The initial bank account balance is set to $1000. You can change this to any positive number. The program enters an infinite loop, displaying the current account balance and offering three options: Deposit, Withdraw, and Exit.

The user is prompted to choose one of the options using pyip.inputChoice(). If the user chooses Exit, then the loop terminates, and the program prints a farewell message. This interactivity can allow the user to perform multiple transactions:

Windows PowerShell
PS> python banking_app.py
Welcome to REALBank.

Your account balance: $1000
Please select one of: Deposit, Withdraw, Exit
Deposit
Enter amount (max $10,000): $5000
Deposited $5000.

Your account balance: $6000
Please select one of: Deposit, Withdraw, Exit

If the user chooses Deposit, then the program prompts them to enter the deposit amount with a limit of $10,000, and the account balance is updated accordingly, in the same session.

The same interactivity is achieved when withdrawing from the bank account. If still in the same session, the application will update the bank balance automatically:

Windows PowerShell
Your account balance: $6000
Please select one of: Deposit, Withdraw, Exit
Withdraw
Enter amount: $4000
Withdrew $4000.

Your account balance: $2000
Please select one of: Deposit, Withdraw, Exit

What if your user decides to withdraw an amount that’s more than their bank balance? Your program will be able to handle the anomaly gracefully, with a comprehensible message:

Windows PowerShell
Your account balance: $2000
Please select one of: Deposit, Withdraw, Exit
Withdraw
Enter amount: $4000
Number must be at maximum 2000.
Enter amount: $2000
Withdrew $2000.

Your account balance: $0
Please select one of: Deposit, Withdraw, Exit

According to the code, users can’t enter amounts higher than the current bank balance for withdrawals. The program will ask for the allowed amount to proceed. You can also choose the exit option to move on. As such, PyInputPlus makes your programs dynamic.

Conclusion

Now you have a comprehensive understanding of handling user input in Python, and you’ve explored various techniques and modules to enhance your interactive programming skills.

You started by delving into the basics, using the input() function to collect user input and exploring methods to ascertain and manipulate the data types. This foundational knowledge is crucial for creating versatile programs that can adapt to diverse user inputs.

Moving on, you practiced error handling strategies, ensuring your programs gracefully handle unexpected inputs, enhancing user experience and program robustness. You then used the getpass module, offering a secure way to accept sensitive information such as passwords without displaying them on the screen.

Finally, you created a banking application using PyInputPlus. This not only reinforced your understanding of input validation but also showcased the practical application of these concepts in building interactive and dynamic programs.

You now can model real-life entities like banks and craft intricate, interactive programs with multiple answers right in your terminal. This knowledge opens the door to creating engaging, user-friendly applications that respond intelligently to user input, providing a solid foundation for your journey into Python programming.

Congratulations on completing this tutorial, and best of luck in applying these newfound skills to your future projects!

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Vincent Matinde

Vincent Matinde is a Python developer with a strong passion for coding and problem-solving. Over the past four years, he has immersed himself in the world of Python including data analytics, and web development.

» More about Vincent

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!