About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Taking Input in Python

You need a way to interact with the computer system in order to solve your problem. Interaction with the computer system would be impossible without a way to take input from the user. There are various ways in which a system can take input:

  • Through a dialog box
  • Through the command line
  • Through a file
  • Through events that occur when a user performs some action (mostly used in game development or web development, where the most common way to give input is to interact with the software)

Every language provides a way to take input from the user; Python is no different. The most common way to take input in Python 3 is using the input() function, which takes input from the keyboard. We’ll explore this function in this article:

  • Python’s Input Function
  • How the Python Input Function Works
  • Python Input List
  • Python Input Validation
  • Python Input Example
  • Strengths Python’s Input Function 
  • Weaknesses Python’s Input Function 
  • FAANG interview questions on taking input in Python
  • FAQs on Python’s Input Function 

Python’s Input Function

Python input() function, as the name suggests, takes input from the user. Whatever you enter in the prompt will be converted to a string. Even if you enter a digit, it will be read as a string. If you want to use it as an integer, you need to convert it with the help of the int() function.

How the Python Input Function Works

Syntax of input() in Python:
input(prompt)

Here, the prompt parameter is optional. If this parameter is defined, a prompt with the passed argument will be displayed before taking the input.

Let’s now see how input() works:

  • Whenever Python’s interpreter finds input() while interpreting code, it will stop the execution and prompt the user to enter something before proceeding further. The rest of the program will not be executed until the user enters some value.
  • If an argument is passed to the input() function, a prompt with the passed argument will be displayed. This argument is optional, generally used to describe what the value is for or what value is expected from the user.
  • Whatever user enters is converted into a string. input() automatically converts the entered user value to a string, and if the user wants to use it in any other type, they have to explicitly convert the type of the function.
  • input() reads one complete line at a time; it does not stop reading the values if the space character is reached, though it will stop if the new line character is reached.

user_input = input('Enter any string: ')
print(user_input)

'''
Output:
Enter any string: Hello World, this is one line input
Hello World this is one line input
'''

Python Input List

While solving problems, we often need a way to input a list of values. As we already know, whatever we enter gets converted into a string. So we need to find a way to convert the string into a list of values. There are various ways of entering a list of values:

1. Values are space-separated (or comma-separated)

In this case, we simply split the string using space; the result will be a list of values.

user_input = input().strip().split(' ')
print(user_input)

'''
Output
1 2 3 4
['1', '2', '3', '4']
'''

Here we use strip() to remove leading and trailing spaces.

2.  One value in one line

In this case, we take one input at a time and insert it into our list.

user_input = int(input())  # Read number of item in list
user_list = []
for i in range(user_input):
    value = input()
    user_list.append(value)

print(user_list)           # Print list of items

'''
Output
3
1
2
3
['1', '2', '3']
'''
3. Using map() for converting type of input values

Here, we first strip the input values, i.e., remove leading and trailing space, and then split the values from the space character. Finally, we map each value to an integer and then finally convert them to list type.

user_list = list(map(int, input().strip().split()))
print(user_list)

'''
Output
1 2 3 4
[1, 2, 3, 4]
'''

4. Using list comprehension

This is basically an alternative to taking a list of values as input. The only difference is each input value should be entered in a new line.

user_input = int(input())
user_list = [int(input()) for _ in range(user_input)]
print(user_list)

'''
Output
4
1
2
3
4
[1, 2, 3, 4]
'''

Python Input Validation

When taking input from the user, we can’t always be sure that the user will always input valid information. For this, we need a way to validate user input. Validating user input is more or less a logical problem; it depends on what data we want from the user and depending on that, we can impose some rules. If the entered data does not follow the criteria, we will display an error message explaining that the data entered is not valid.

In Python, we can use exception handling to validate user input. For example, if the expected value should be an integer, we will typecast the input value to an integer. If there is an error, it means that whatever the user entered is not an integer.

try:
    user_input = int(input('Enter a number: '))
except Exception:
    print('Not a number')

'''
Output
Enter a number: Hello
Not a number
'''

There can be other ways of validating user input, For example, you can use regular expressions (regex), or you can write your own rules.

The most common validation techniques are:

  • Type Check: Checking the type of data (float, int, char, etc.)
  • Length Check: Checking the length of input data (in case of list, string, tuple, etc.)
  • Regex Check: Use regular expressions to validate strings (in email, mobile number, etc.)
  • Range Check: Check if the entered number is in a given range

Python Input Example

Let’s have a look at a couple of simple examples to see how input() works.

Example 1: Write a program to input 5 integer values and print it in the form of a list in Python.

total_values = int(input())
user_input = [int(input()) for _ in range(total_values)]
print(user_input)

'''
Output
5
1
2
3
4

5
[1, 2, 3, 4, 5]
'''
Example 2: Write a program to read till the end of the line.

user_values = []
while True:
    try:
        value = input()
        user_values.append(value)
    except Exception:
        break
print(user_values)

'''
Output
1
2
3
4
['1', '2', '3', '4']
'''

Strengths of Python’s Input Function

  • input() reads one complete line at a time; it does not stop reading at a space. However, it will stop if a new line character is reached
  • input() reads the data in the form of a string. You can always be sure that any input will be a string, so you don't need to check for the type of data before applying any validation. You can typecast the data if you want to use it in any other form.
  • With the help of typecasting, if the user input is not of valid type, Python will raise a ValueError exception indicating it is not of the expected type.

Weaknesses of Python’s Input Function

  • Since input() does not provide any type of validation of its own (due to dynamic typecasting), the coder has to take care of it. 
  • Because input() reads one complete line at a time, you need to perform one more operation (split) to read a list of characters.
  • There will always be a need to convert to a specific type because the entered data will always be of string type 

FAANG Interview Questions on Taking Input in Python

  1. Given two sorted lists of integers, merge them into a single sorted list
  2. Variation of the above problem: Given k sorted list of integers, merge all of them into a single sorted list
  3. Given a sequence of integers and two numbers left and right. Find the number of subsequences whose bitwise AND value will lie in the range of left and right, i.e., Left <= bitwise_and_value <= right
  4. Take two integers, low and high as input, and output numbers of integers that are in the range of low and high, and their digit sum is one. Digit sum is the sum of all digits of an integer. For example, the digit sum of 123 is 6.
  5. Given a string, check if the string is valid JSON.

FAQs on Taking Input in Python

Question 1: What is the difference between input() and raw_input() function in Python?

Answer: raw_input() is used only in Python2 while input() is used in Python 2.x as well as Python 3.x. Also, raw_input() always uses input data in string format, whereas input() tries to detect the type of data and automatically convert it to the required type. Though this property of input() only works in Python2.x, it is best to typecast the data before using it.

Question 2: How do we remove leading and trailing space from user input

Answer: strip() function in Python is very useful in this case; it will remove leading and trailing space from the user-entered value.

Question 3: How to take input as a Python dictionary object?

total_words = int(input())
word_map = dict()

for i in range(total_words):
    key, value = input().strip().split()
    word_map[key] = value

print(word_map)

'''
Output
5
1 hello
2 world
3 I
4 am
5 L
{'1': 'hello', '2': 'world', '3': 'I', '4': 'am', '5': 'L'}

'''

Preparing for a Tech Interview? 

If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview preparation, we have trained thousands of engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

---------

Article contributed by Problem Setters Official

Attend our Free Webinar on How to Nail Your Next Technical Interview