Getting User Input in Python

Getting User Input in Python

Introduction

The way in which information is obtained and handled is one of the most important aspects of the ethos of any programming language, more so for the information supplied and obtained from the user.

Python, while comparatively slow in this regard when compared to other programming languages like C or Java, contains robust tools to obtain, analyze, and process data obtained directly from the end user.

In this article, we'll take a brief look at how to obtain information from the user through the input() function in Python with the help of some code snippets to serve as examples.

Input in Python

To receive information through the keyboard, Python uses the input() function. This function has an optional parameter, commonly known as prompt, which is a string that will be printed on the screen whenever the function is called.

Note: Before Python 3 introduced the input() function, the way to go when reading the user input was the raw_input() function. Still, it's always advised to use Python 3 and its input() function whenever you can!
In Python 3, the raw_input() function has been deprecated and replaced by the input() function and is used to obtain a user's string through the keyboard. And the input() function of Python 2 is discontinued in version 3. To obtain the same functionality that was provided by Python 2's input() function, the statement eval(input()) must be used in Python 3.

When the input()function is called, the program flow stops until the user enters the input via the command line. To actually enter the data, the user needs to press the ENTER key after inputting their string. While hitting the ENTER key usually inserts a newline character ("\n"), it does not in this case. The entered string will simply be submitted to the application.

Now that we understand the basic theory behind the input() function, let's take a look at how it actually works in Python:

# Python 3

txt = input("Type something to test this out: ")

print(f"Is this what you just said? {txt}")

Running the previous code will prompt us with the "Type something to test this out:" message. After we've typed something, it will print out what we've just typed:

Type something to test this out: Let the Code be with you!

Is this what you just said? Let the Code be with you!

String and Numeric Input

The input() function, by default, will convert all the information it receives into a string. The previous example we showed demonstrates this behavior.

Numbers, on the other hand, need to be explicitly handled as such since they come in as strings originally. The following example demonstrates how numeric type information is received:

# An input is requested and stored in a variable
test_text = input ("Enter a number: ")

# Converts the string into an integer. If you need
# to convert the user input into the decimal format,
# the float() function is used instead of int()
test_number = int(test_text)

# Prints in the console the variable as requested
print ("The number you entered is: ", test_number)

Running the previous code will give us:

Enter a number: 13
The number you entered is: 13

The more common approach is to perform both reading input and converting it into an integer in one line:

test_number = int(input("Enter a number: "))

Keep in mind that if the user doesn't actually enter an integer then this code will throw an exception, even if the entered string is a floating point number.

How to Handle Exceptions When Reading Input

There are several ways to ensure that the user enters valid information. One of the ways is to handle all the possible errors that may occur while the user enters the data. In this section we'll demonstrates some good error handling methods for errors that may arise when reading input.

But first, let us take a look at an example of some (potentially) unsafe code:

test2word = input("Tell me your age: ")
test2num = int(test2word)
print("Wow! Your age is ", test2num)

After running this code, say you enter the string "Three" instead of the number 3:

Tell me your age: Three

Here, when the int() function is called with the "Three" string, a ValueError exception is thrown and the program will stop and/or crash.

Now let's see how we would make this code safer to handle user input:

test3word = input("Tell me your lucky number: ")

try:
    test3num = int(test3word)
    print("This is a valid number! Your lucky number is: ", test3num)
except ValueError:
    print("This is not a valid number. It isn't a number at all! This is a string, go and try again. Better luck next time!")

This code block will evaluate the new input. If the input is an integer represented as a string then the int() function will convert it into a proper integer. If not, an exception will be raised, but instead of crashing the application it will be caught and the second print statement is run. Here is an example of this code running when an exception is raised:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Tell me your lucky number: Seven
This is not a valid number. It isn't a number at all! This is a string, go and try again. Better luck next time!

And this is how input-related errors can be handled in Python.

Note: You can combine this code with another construct, like a while loop to ensure that the code is repeatedly run until you receive the valid integer input that your program requires.

A Complete Example

# Make a function that will contain the
# desired program.
def example():

    # Call for an infinite loop that keeps executing
    # until an exception occurs
    while True:
        test4word = input("What's your name? ")

        try:
            test4num = int(input("From 1 to 7, how many hours do you use your smartphone?" ))

        # If something else that is not the string
        # version of a number is introduced, the
        # ValueError exception will be called.
        except ValueError:
            # The cycle will go on until validation
            print("Error! This is not a number. Try again.")

        # When successfully converted to an integer,
        # the loop will end.
        else:
            print("Impressive, ", test4word, "! You spent", test4num*60, "minutes or", test4num*60*60, "seconds using your smartphone!")
            break

# The function is called
example()

The output will be:

What's your name? Francis

From 1 to 7, how many hours do you use your smartphone?

Impressive, Francis! You spent 180 minutes or 10800 seconds using your smartphone!

Conclusion

In this article, we saw how the built-in Python input() function can be used to get user input in a variety of formats. We also saw how we can handle the exceptions and errors that can possibly occur while obtaining user input.

Last Updated: July 22nd, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup
Details
Project

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic
Details

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms