How to Read User Input From the Keyboard in Python

How to Read User Input From the Keyboard in Python

A common goal is to increase the interactiveness of your Python programs by allowing them to react dynamically to user input. Gaining the ability to interpret keyboard input from users opens up a world of possibilities and can greatly increase the usefulness of your programs.

Python’s keyboard input functionality enables you to create programs that can react differently depending on the choices, preferences, or information entered by various users. Instead of only carrying out static logic processes, your code can respond to modifiable conditions by retrieving input and assigning it to variables. This allows applications to be tailored to specific users.

The simplest method for obtaining keyboard data from the user in Python is to utilize the input() function. When it is called, a prompt that you designate is used to request input from the user. It then waits for the user to type an answer and hit the Enter key before proceeding. Input() returns this answer string, which you can use directly or save in a variable.

You can begin developing interactive programs that take user-customizable data directly in the terminal by using simply Python. Gaining the ability to accept user input is crucial for Python scripting to become more dynamic and for transforming basic scripts into customized applications.


How to Read Keyboard Input in Python With input()

In Python, the built-in input() method is widely used to read keyboard input. It waits for the user to type something and press Enter before returning the result as a string.

user_input = input("Enter something: ")
print("You entered:", user_input)

When you run the code, the string you specified in input() will appear on screen, and you will be able to enter any string. When you press Enter, your response will be printed on the screen as well. This is because the REPL prints return values, which in this case are the values returned by input().

When using input(), the best approach is to store it in a variable that may be used later in your code. For example, you can ask the user to enter their name. Assign input() to the name variable.

name = input("What is your name? ")
What is your name? mrcoder701

This prints the prompt “What is your name?” and then pauses while waiting for keyboard response. After typing a name and pressing Enter, the text string is saved in the name variable. This time, your input will not be automatically printed in the REPL because it is stored in a variable instead.

You can now utilize the variable in any portion of your code in the same session, for example, printing a personalized greeting.

print(f"Hello there, {name}!")
Hello there, mrcoder701!

Your application reacted based on the custom name you specified. It utilized the name you specified in the input() request.

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

  • Call input() with a prompt indicating what to enter.
  • Assign the result to a descriptively named variable.
  • Use that variable later in your code.

This is only the first step you may take when using input() in your interactive software. There are further changes you may make to guarantee that the function accepts a variety of data types.


Reading Specific Data Types With the input() Function

The general rule for input() is to collect textual input and return strings. Your code frequently requires numbers, Booleans, or other data types instead. For example, you may need integers for mathematical operations, floats for decimal computations, or Booleans for logical conditions.

Since input() returns strings, you must transform all of the input into the desired data type before using it in your code. If you request numerical input, the results will still be returned as a string:

While input() always returns a string, you can convert this string to other data types as needed. For example, to read an integer, you can use the int() function:

num = int(input("Enter an integer: "))
print("You entered:", num)

Similarly, for floating-point numbers:

float_num = float(input("Enter a floating-point number: "))
print("You entered:", float_num)

Handling Errors With input() in Python

Errors can occur when you wrap input() in a conversion function and it receives a different data type than expected. The software will then throw a ValueError and terminate. This is not how you would like your software to behave. Try the following example to see how the software rejects a different data type input:

try:
    num = int(input("Enter an integer: "))
    print("You entered:", num)
except ValueError:
    print("Invalid input. Please enter an integer.")

This code raises a ValueError  Invalid input. Please enter an integer.

You can manage this scenario by catching the exception before your user sees it. In the following example, you will write a script within a Python file. Create a folder in your selected directory.


Reading Multiple Entries From User Input

In some cases, your program may demand several entries from the user. This could be the situation if your user has various responses to a question.

In Python, you may use the list data type to store and organize a succession of elements. Lists are useful for holding multiple entries from users. You can ask users to enter several inputs, which your software will keep in a list. Open the folder and create a new Python file called list_input.py. Please enter the following code:

user_names = input("Enter the three usernames separated by commas: ")
usernames = [s.strip() for s in user_names.split(",")]

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

This Python function accepts three usernames separated by commas. You use a list comprehension to iterate through comma-separated substrings. The.strip() method removes all leading and trailing whitespaces from each substring. The processed list of usernames is then printed.

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

Enter the three usernames separated by commas: mrcoder701, coder, blogwithmrcoder701

List of usernames: ['mrcoder701', 'coder', 'blogwithmrcoder701']

Whatever the user types as a string will be stored in a list by your program. The list will be printed on the terminal. In this scenario, the application does not validate the entries.


Securing Sensitive User Inputs

In some cases, you might want to hide a user’s input on the terminal. Examples of inputs include passwords, API credentials, and even email addresses. In these cases, you can utilize the standard library package getpass to get the desired result.

The getpass module was built expressly to safeguard critical terminal entries. When using this package, the keyboard entries will not be printed to the screen. You may believe nothing is going on, but it is. In the following example, you will use an email entry to demonstrate how you may safeguard sensitive information in your program.

Note:When working with passwords and other sensitive information, such as API keys, it is critical that you never commit them to GitHub or otherwise expose them. Using getpass just secures the entry of sensitive information. You must continue to store the information securely.

Make a Python file in your examples folder and call it example_sensitive.py. In this file, type the following code:

import os
import getpass

password = getpass.getpass("Enter your password: ")
print("Password entered.")

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


Automating User Input Evaluation With PyInputPlus

The input() function allows you to create powerful and sophisticated applications. This task becomes more complicated if you have to handle all errors, check the input type, and process the results.

Third-party libraries can let you accept and handle user keyboard inputs in the terminal. One such package is PyInputPlus, which provides useful capabilities for accepting and handling user input.

When obtaining input, you can pass arguments such as min, max, greaterThan, and other parameters. It will re-prompt the user if their input fails the tests. This eliminates the need to implement loops and validation to repeatedly ask the user until they submit valid input. Other features include timeouts, configurable validation routines, and optional retry limits before rejecting data.

Overall, PyInputPlus eliminates the need to manually handle invalid input scenarios in your code. PyInputPlus avoids code duplication by combining validation and re-prompting into input function calls, allowing for 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 prevents the library from being installed globally on your PC and keeps it limited to your project. Enter the following command to create the virtual environment:

>python -m venv venv

You have created a folder called venv. Activate this virtual environment by running the following command:


# In Windows

mrcoder701> venv\Scripts\activate
(venv) mrcoder701>

# Linux + MacOS

$ source venv/bin/activate
(venv)

After you have activated your virtual environment, you can install PyInputPlus. You will use pip to install the package in your environment. In your terminal, type this command:

(venv) mrcoder701> python -m pip install pyinputplus

Once the package has been successfully installed, you can import it into the following file.

Create a Python file named example_pyinputplus.py. In the file, enter the following code to let you experiment with PyInputPlus:

import pyinputplus as pyip

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

This code allows you to choose the age range for participants in your program. If the user provides a number within the range, your software will print the age to the console and then exit. If not, the application will prompt the user to input their age again.

(venv) mrcoder701> python example_pyinputplus.py
Enter your age: -2
Number must be at minimum 0.
Enter your age: 121
Number must be at maximum 120.
Enter your age: 28
Your age is: 28

As shown above, if the user enters an age less than 0 and greater than 120, the computer will prompt them again, as indicated in the code. Once a valid input is entered, the code continues and prints the age.

PyInputPlus reduces the complexity of using input() in its basic form. The code is also simple and concise, allowing you to develop complicated interactive programs.


Conclusion

Reading user input from the keyboard is a fundamental skill in Python programming. By using the input() function along with appropriate error handling and additional libraries like PyInputPlus, you can create robust programs that efficiently gather user input for various purposes. Remember to consider security aspects, especially when dealing with sensitive information, and always validate and sanitize user input to prevent unexpected behavior or security vulnerabilities.

Show 2 Comments

2 Comments

  1. Mysimba – Quick and Easy Weight Lass

    Mysimba is a medicine used along with diet and exercise to help manage weight in adults:

    who are obese (have a body-mass index – BMI – of 30 or more);
    who are overweight (have a BMI between 27 and 30) and have weight-related complications such as diabetes, abnormally high levels of fat in the blood, or high blood pressure.
    BMI is a measurement that indicates body weight relative to height.

    Mysimba contains the active substances naltrexone and bupropion.

    https://true-pill.top/mysimba.html

  2. PabloThync

    Support your body, nourish your soul!
    Your best health is your greatest achievement!
    Elevate your performance, elevate your life!
    Quality supplements for quality living!
    Your body deserves the best—invest in supplements!

    vtkqj3vk4tuqjhwejhqw – mrcoder701.com
    https://knomofintectown.info

Leave a Reply

Your email address will not be published. Required fields are marked *