Home Resource Centre Python input() Function (+Input Casting & Handling With Examples)

Python input() Function (+Input Casting & Handling With Examples)

Input and output functions are essential for every programming language, as they allow users to directly interact with a program (like providing data and receiving data). While output functions display data, input functions like the input() function in Python let users provide data to the program. 

In this article will discuss Python’s input() function in detail, using examples to illustrate its functionality and versatility.

What Is Input() Function In Python? 

The input() function in Python language is a built-in method that allows interaction between the user and the program by prompting users to enter data via the keyboard. Originating from Python's core library, input() serves as a fundamental tool for gathering user input. (Fun fact: The source code of the input function was written in  C language.)

  • In its simplest form, the input() function accepts an optional string parameter—a message that guides users on what data they should provide. 
  • This message, often referred to as a "prompt," helps improve communication by specifying the expected input. 
  • Regardless of the type of data the user enters (such as an integer or float), input() always returns it as a string.

Because input() returns data as a string, we often store this return value in a variable, which we can then manipulate or use elsewhere in the program.

Syntax Of Input() Function In Python

var = input(prompt)

Here,

  • The term var refers to the variable that is used to store the data that was entered by the user.
  • The term input is the name of the function itself and the parentheses () contains the prompt.
  • The prompt is the message where the user can specify what data she wants from the end user.

Parameters Of Input() Function In Python

The built-in function input() accepts a single optional parameter called prompt. This parameter is a string that serves as a message to the user, helping them understand what type of input is expected.

Suppose we want to ask the user to enter a number and then display it back to them. 

Code Example:

Output:

Enter a Number: 20
Number is: 20

Explanation:

In the simple Python program example

  1. We declare a variable called number to store the user input. 
  2. Then, we use the input() function to prompt the user to provide a value with the string- ‘Enter a Number: ‘.
  3. This string message is the parameter of the input function.
  4. Next, we output the number entered by the user to the console with the print() function, where we separate two arguments (message and number to print) with a comma.

Return Type of Input Function In Python

As mentioned before, the input() function in Python always returns data as a string. Even if the user enters an integer, float, or boolean, the returned value will be of string type. To check this, we have given a simple Python code example below, where we will use the type() function to verify the type of the input.

Code Example:

Output:

Enter a Number:10
<class 'str'>

Explanation:

As in the previous Python program example,

  1. We use the input() function to take user input and store it in the number variable.
  2. Then, we use the type() function inside a print statement to check and display the type of the input returned by input() to the variable. 
  3. As seen in the output window, the type of the input is string (str) class.

Check out this amazing course and learn to code in the Python programming langauge with ease.

Working Example Of Input() Function In Python

In this example Python program below, we’ll demonstrate how to read an integer and a float from the user with the input() function. We will also add the input values and display the result.

Code Example:

Output:

Enter an integer value: 10
Enter a float value:11.2
Summation of number1 and number2 is 21.2

Explanation:

In the Python code example,

  1. We first declare a variable called number1 to store an integer input from the user.
  2. Then, we use the input() function inside the int() function to prompt the user to provide an integer value. Here:
    • The prompt specifies that we want an integer value. 
    • Since we know that input() returns a string, we use the int() function to convert the input from a string into an integer and assign it to the number1 variable.
  3. Similarly, we declare another variable number2 to store the user-provided floating-point value.
    • Just like before, we use the input() function with a prompt to specify that we want a float value.
    • Then, use the float() function to convert the string input to float and store it in the number2 variable.
  4. Next, we perform the addition operation on the two variables and assign the outcome to the variable sum
  5. Lastly, we display the sum value using the print() function.

Getting Multiple Inputs In One Line Using Input() Function In Python

In some cases, you might need to take multiple inputs from the user at once. For example, when dealing with arrays or lists, you’ll read multiple values at the same time. You will have to combine the split() function with the input() function in Python programs to collect multiple inputs in a single line. Here is how this will work–

  • The input() function will prompt the user to enter the value.
  • And the split() function will split the input string (returned by input) based on a specified delimiter (parameter inside split) and returns a list of values (default).

Let’s look at the syntax of split() with input() function in Python, followed by an example demonstrating its use.

Syntax:

values=input(prompt).split(delimiter)

Here, we have the input() function itself with the prompt to take input and the values variable to store that.

  • The split function performs the task of splitting the input, and the delimiter inside the parentheses is a character used for splitting. 
  • Suppose you use a comma as a delimiter; then, the function will separate the words in the input string by commas.
  • The dot character between the two functions is used to chain them.

Let’s create a sample Python program to check how this works in action. In this program:

  • We will first prompt the user to enter a single string 
  • Then we will use input() with split() to accept multiple strings in a single line, separated by whitespace.
  • We will print both the inputs to give a more comprehensive insight into the working of the input() function in Python.

Code Example:

Output:

Enter a single value: Unstop
Single input as string: Unstop
Enter multiple values separated by space: Learn Compete Practice
Multiple inputs as list of strings: ['Learn', 'Compete', 'Practice']

Explanation:

In the example Python code,

  1. First, we prompt the user to enter a single value using the input() function and store it in the variable single_input. 
  2. We then display this input using the print() function.
  3. Next, we prompt the user to provide multiple values separated by spaces. Here:
    • The input() function takes this input and returns its string form.
    • The split() function marks them as individual values based on where the whitespace is placed and stores them in an iterable assigned to variable mulitple_inputs.
  4. Next, we print the list of strings returned by the input() and split() combination.
  5. This reflects the comparison between taking a single and multiple inputs.

Level up your coding skills with the 100-Day Coding Sprint at Unstop and claim the bragging rights, now!

Getting Multiline Input From Input() Function In Python

​​In some scenarios, you might need to read multiple lines of values from the user. For example, when dealing with arrays or lists, you may sometimes need to gather input line by line. There are two common cases for this:

Case 1: Reading A Specified Number Of Lines

Sometimes, the total number of values in the array or list will be specified in advance. In such cases, you will first read the number of values (denoted as n) and then read n lines of input, appending each value to the list.

Code Example:

Output:

Enter N value: 3
Enter 3 values, one for each line
23
11
89
[23, 11, 89]

Explanation:

In the Python code sample,

  1. We first prompt the user to enter the number of values they want to input, storing it in the variable n. Here:
    • The input() function gives the prompt to the user and returns the input to the program.
    • Then, the int() function converts the string input into an integer, which determines how many lines of input will follow.
  2. Next, we create an empty list called array, to store the values entered by the user.
  3. Then, we use a for loop to runs n times, prompting the user to enter a value during each iteration. Each of these values is side-by-side appended to the array list using the append() function.
  4. Finally, the print() function outputs the array list containing all the user inputs.

Case 2: Reading Multiple Lines Until Enter Is Pressed Without A Value

Unlike in the situation discussed above, in some cases, you may not know how many lines of input to expect. Instead, the input collection continues until the user presses Enter without entering a value.

Code Example:

Output:

Enter a value: Hi
Enter a value: Unstop
Enter a value: 
['Hi', 'Unstop']

Explanation:

In the Python program sample,

  1. We first create an empty list called array to store user inputs.
  2. Then, we use a while loop, which starts at True, creating an infinite loop that continues until the user presses Enter without typing anything (an empty input).
  3. Inside the loop, we use the input() function to prompt the user to enter a value and read it, storing it in x.
    • Then, we use an if-else statement to check the input. The if condition (x:) checks if the input is not empty. If true, the input value is appended to the array.
    • If the input is empty (i.e., the user presses Enter without typing), the loop is terminated on encountering the break statement in the else block.
  4. We then use a print() function to display the array containing all the entered values before the empty input.

Type Casting & Input() Function In Python

What is Type Casting? Type casting is the process of converting a value from one data type to another without altering its actual content. It is important to convert the data types when you need data to be compatible with specific operations or functions.

Syntax:

new_var=(type) var

Here,

  • The new_var is the variable to store the type casted value, and var is the variable that holds the value that needs to convert data type.
  • The type is the required data type.

Using Type Casting with input() Function in Python

As discussed, by default, the input() function returns user input as a string. So, to work with other data types, we have to type-cast the input value to the desired data type.

Syntax:

var=(type) input(prompt)

Here,

  • The var is a variable used to store the data typecasted value, and type is the required data type of the input value.
  • The input captures user input with the prompt specifying the kind of input to give.

Example: Converting Input to Integer

Here, we will cast the string value returned by the input function into its original type, i.e. an integer.

Code Example:

Output:

Enter Number: 10
Number +1 is 11

Explanation:

In this Python example code

  1. We first use the input() function to capture an input and then use int() to convert it to an integer value.
  2. Then, we increment it by 1 inside the print function and display the result.

Handling User Input & Validation

Managing user input is essential in interactive applications, especially in handling errors, validating data, and converting types appropriately. Python has several built-in modules and functions for this.

  • We know that the input() function in Python returns a string by default, and if the user enters a non-numeric string when an integer is expected, a ValueError will occur. 
  • For instance, entering a string instead of an integer in a prompt that expects an integer can trigger this error. Input validation helps mitigate this.

Code Example:

Output:

Enter a Number: Hi
ValueError: invalid literal for int() with base 10: 'Hi'

Explanation:

In this example,

  1. We first prompt the user to provide a number, capture it using input() and then convert it to integer type using the int() function.
  2. Then, we print this value to the console using the print() function.
  3. However, as shown in the output, if the user inputs a non-integer value, this program will throw an error.

It is important to employ input validation in such cases. But how?

What Is Input Validation?

It is the process of clearly defining the requirements for user input and putting validation checks in place to ensure they are met. In other words, input validation ensures that user input meets specific requirements. Using the try-except approach in Python is effective for handling exceptions like ValueError when input doesn’t meet expectations. 

Let’s take a look at the syntax for this, followed by a sample program, to see how we can use this approach to validate values captured by the input() function.

Syntax:

try:
    # Code that might raise an exception
except:
    # Code to handle the exception

Here,

  • The keyword try indicates that the code followed by the colon (:) might contain an exception.
  • The except Python keyword indicates that the code followed by the colon (:) contains stipulations of how to handle the expectation if found.

Let’s look at an example of using the try-except block with the input() function in Python to take and validate input.

Code Example:

Output:

Enter a Number: Hi
Entered is not a number, Please enter a number
Enter a Number: No
Entered is not a number, Please enter a number
Enter a Number:1
1

Explanation:

In the example,

  1. We initiate a while loop starting with True (an infinite loop) to repeatedly prompt the user to provide a value until a valid input is given. Here:
    • The try block contains the input() function to prompt the user to enter a value to be cpatured and the int() function to convert it to an integer.
    • Then, we have the except block, which checks if an error was generated. If yes, it prints an error message, and the loop runs again. 
    • If an error is not thrown, then the else block is executed, which contains a break statement ending the loop.
  2. After that, we display the input value to the console using the print() function.

Looking for guidance? Find the perfect mentor from select experienced coding & software experts here.

Input() Vs. Raw_Input() Function In Python

The table below highlights the difference between the raw_input() function and the input() function in Python across the two versions.

Feature

input() (Python 2.x)

input() (Python 3.x)

raw_input() (Python 2.x)

Functionality

Evaluates input expression and returns result based on evaluated type

Always returns input as a string

Always returns input as a string

Data Type of Return Value

Depends on the evaluated input (e.g., integer for 10, list for [1,2])

Always returns str type

Always returns str type

Syntax

value = input(prompt)

value = input(prompt)

value = raw_input(prompt)

Presence

Available in Python 2.x

Available in Python 3.x

Available only in Python 2.x

Evaluation of Expressions

Evaluates the input as a Python expression (e.g., entering 1+1 will return 2)

Does not evaluate expressions, takes input as plain text

Does not evaluate expressions, takes input as plain text

Security Implications

Risky if used to evaluate untrusted input

Safer, as no evaluation is performed

Safer, as no evaluation is performed

Common Use Case

Used when expressions are intentionally evaluated

Used for capturing user input

Used for capturing user input

Example (input: 10)

Returns integer 10

Returns string "10"

Returns string "10"

Example (input: 1+1)

Returns integer 2 (evaluates 1+1)

Returns string "1+1"

Returns string "1+1"

Example (input: [1, 2, 3])

Returns list [1, 2, 3]

Returns string "[1, 2, 3]"

Returns string "[1, 2, 3]"

As is evident, while Python has two functions for capturing input: input() and raw_input(), the distinction exists only in Python 2.x, as raw_input() was removed in Python 3.x.

Conclusion

The input() function in Python is a straightforward way to capture user input, making it essential for interactive programs. With an optional prompt parameter to guide users on the type of input needed, it enables smooth communication between a program and its user.

In Python 3.x, input() always returns the input as a string, even if the user enters a number or other data type. This design improves security and consistency by avoiding expression evaluation, which was a feature of the input() function in Python 2.x. 

However, this also means that with the input() function in Python 3.x, you’ll need to use typecasting to work with the returned string in other formats, and in some cases, adding validation with a try-except block can help handle unexpected input.

To summarize:

  • input() Usage: Reads user input as a string, promoting secure and consistent handling of data.
  • Prompt Parameter: Optional text to help users understand what input is expected.
  • Typecasting Requirement: Convert strings to other data types (e.g., int, float) as needed.
  • Python 2.x vs. 3.x: Unlike Python 2.x, input() in 3.x does not evaluate expressions, improving security.
  • Validation: Using try-except for input validation helps manage unexpected data types.

Frequently Asked Questions

Q. What is the difference between input and print functions in Python?

The input() function in Python captures data entered by the user and returns it as a string, while the print() function displays data on the console. In other words, input() is used for input, while print() is used for output.

Q. What are command-line arguments, and how do they differ from the input() function?

Command-line arguments are a way to provide input to a program when it is executed from the command line or terminal. These arguments are specified after the program's name and are separated by spaces. They allow users to pass information to the program without interacting with it during its execution. 

In contrast, the input() function prompts for user input during runtime and waits for a response, allowing interactive input while the program runs. The table below highlights the difference between command-line arguments and the input() function in Python.

Aspect

Command-line Arguments

input() Function

When provided

Provided at the time of program execution.

Prompts the user for input while the program is running.

User Interaction

No interaction is required after the program starts.

Requires user interaction to provide input when prompted.

Access

Accessed via the sys.argv from sys module.

Input is read as a string by the function and can be processed immediately within the program.

Q. How can I take multiple inputs (e.g., 10 values) from a user in Python?

To take multiple inputs from the user, say 10, you can use a for loop containing the input() function to repeatedly prompt the user to provide values. On receiving them, you can append them to a list (you will need to create an empty list beforehand). 

Let’s build a Python example program to show how we can take 10 value inputs from the user and then print the same.

Code Example:

Output:

Enter 10 values, one per line:
1
2
3
...
10
The values are: ['1', '2', '3', ... '10']

Q. How do you calculate the sum of user input of two values in Python?

To calculate the sum of two user input values, we need to read the values from the user one by one, then convert them into int type and store them into two variables. We can then perform the addition operation on those two variables.

Code Example:

Output:

Enter a value: 5
Enter b value: 6
The sum of a and b is: 11

Q. What type of data does input() function in Python return?

The input () function in Python will always return the user input data as a string type value. Given below is an example where we check the type of user input with and without type conversion.

Code Example: 

Output:

Enter a value:10
<class 'str'>
Enter an integer value:20
<class 'int'>

In this example, 

  • We first prompt the user to provide an integer value using input() and then check its data type using the type() function and print it to the console.
  • Then, we prompt the user again to enter an integer value, but this time, we use the int() function to typecast the value returned by the input() function into the integer type.
  • After that, we check the variable’s data type and print it, which, as shown in the output console, belongs to class ‘int’.

This shows that the input() function in Python always returns the value as a string. And we need to typecast it to other types if needed.

Here are a few other Python articles you might be interested in reading:

  1. Python Namespace & Variable Scope Explained (With Code Examples)
  2. Python String Replace() And 8 Other Ways Explained (+Examples)
  3. Python Bitwise Operators | Positive & Negative Numbers (+Examples)
  4. Fibonacci Series In Python & Nth Term | Generate & Print (+Codes)
  5. Python Logical Operators, Short-Circuiting & More (With Examples)
  6. Python IDLE | The Ultimate Beginner's Guide With Images & Codes
Shivani Goyal
Manager, Content

An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.

TAGS
Computer Science Engineering Python programming language
Updated On: 28 Nov'24, 10:39 PM IST