How to Get User Input for Your Python Application - dummies

How to Get User Input for Your Python Application

By John Paul Mueller

Very few applications exist in their own world — that is, apart from the user. This applies to Python applications as well. In fact, most applications interact with users in a major way because computers are designed to serve user needs. To interact with a user, an application must provide some means of obtaining user input.

Fortunately, the most commonly used technique for obtaining input is also relatively easy to implement. You simply use the input() function to do it.

The input() function always outputs a string. Even if a user types a number, the output from the input() function is a string. This means that if you are expecting a number, you need to convert it after receiving the input. The input() function also lets you provide a string prompt. This prompt is displayed to tell the user what to provide in the way of information.

The Input01.py file contains an example of using the input() function in a simple way. Here’s the code for that example:

Name = input("Tell me your name: ")
print("Hello ", Name)

In this case, the input() function asks the user for a name. After the user types a name and presses Enter, the example outputs a customized greeting to the user. Try running this example at the command prompt or the Python Shell window. Here are the typical results when you input John as the username.

image0.jpg

You can use input() for other kinds of data; all you need is the correct conversion function. For example, the code in the Input02.py file provides one technique for performing such a conversion, as shown here:

ANumber = float(input("Type a number: "))
print("You typed: ", ANumber)

When you run this example, the application asks for a numeric input. The call to float() converts the input to a number. After the conversion, print() outputs the result. When you run the example using a value such as 5.5, you obtain the desired result.

It’s important to understand that data conversion isn’t without risk. If you attempt to type something other than a number, you get an error message.

image1.jpg