Interview Kickstart has enabled over 21000 engineers to uplevel.
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:
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 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.
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:
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
'''
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]
'''
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:
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']
'''
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'}
'''
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!
---------
Article contributed by Problem Setters Official
Attend our webinar on
"How to nail your next tech interview" and learn