How to ask for user input in python?

Python has an input() function which allows the programmer to ask users for input text. The control of the program pauses executing when it encounters an input() function and resumes the execution again when the user has given the input.

The input () function has an optional parameter known as a prompt that takes a string and is printed whenever the input() function is called. The below example illustrates the use of input and prompt parameters. Here "Enter a number: " is passed to the prompt parameter.

num = input("Enter a number: ")

The input() function by default converts every input to a string data type. For example,

text = input("Enter a string value:")
print("Data type of text variable: ", type(text))
num = input("Enter a integer value: ")
print("Data type of num variable: ", type(num))

The above program returns the output as

Enter a string value:Hello
Data type of text variable:  <class 'str'>
Enter a integer value: 134
Data type of num variable:  <class 'str'>

Get an integer input in python

from the user

To obtain an integer input, the string value has to be explicitly converted to an integer by typecasting. The following code takes an input from the user and typecast to an integer value.

num = int(input("Enter number: "))
print("Data type of num variable: ", type(num))

The above code gives output as

Enter number: 89
Data type of num variable:  <class 'int'>

Get a float input in python from the user

To obtain a float input, the string value has to be explicitly converted to a floating-point value by typecasting. The following code takes an input from the user and typecast to a float value.

val = float(input("Enter a decimal number: "))
print("Data type of val variable: ", type(val))

The above program returns the output as

Enter a decimal number: 65.5
Data type of val variable:  <class 'float'>

Get a list input in python from the user

The user can use the same input() function to get user input, just you have to enter values with a space separator. The map() function has two parameters, a function and an iterable. It passes each data item of the iterable as an argument to the function. map(int, input("Enter a number")) passes each value of user input to the int function.

The list() constructor explicitly converts all the data items to a list and returns a list iterable. The following example demonstrates the use of the map() function to get a list input in python from the user.

list_1 = list(map(int,input("Enter a list of number : ").split()))
print("list_1 = ", list_1)
print("Type of list_1: ", type(list_1))

The above program returns the output as

Enter a list of number : 1 4 6 3 8
list_1 =  [1, 4, 6, 3, 8]
Type of list_1:  <class 'list'>
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions