In our previous article, we examined the print function and how it outputs values to the console. In this lesson, we dive into another essential function: the input function. The input function prompts the user to enter data via the console and returns the entered value as a string.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Understanding the Input Function
The input function is designed to pause program execution until the user provides an input. You can include a prompt within the input function to guide the user on what to enter. Consider the following example demonstrating the output of a simple print command:Capturing User Input
To capture user input, you assign the result of the input function to a variable. In the snippet below, a prompt is displayed, and the user’s response is stored:Example: Capturing a Favorite Color
If you want to know a user’s favorite color, assign the input to a variable and then use that variable later in your program:Remember that the value returned by the input function is always a string. This is an important detail when you are handling arithmetic operations.
Working with Numerical Input
When a user enters a number, it is returned as a string. Attempting to perform arithmetic operations on a string will result in a TypeError. Consider this example:int() to convert a string to an integer or float() for a floating-point number.
Converting Input Using Typecasting
Here’s how you can convert the user input from a string to an integer before performing subtraction:int() directly to ensure that the returned value is numeric:
Summary
Let’s review what we’ve learned about the Python input function:- The input function pauses the program and waits for a user response.
- You can provide a prompt string inside the input function to guide the user.
- The value returned by input() is always a string.
- Use typecasting functions such as
int()orfloat()to convert the input into a numeric type for arithmetic operations.