September 30, 2023

Input from User in Python – input() function

If you have to take user input from keyboard in Python that can be done using input() function. Python input() function takes the entered value and returns it as a string once user presses Enter.

Syntax of input() function

The syntax of Python input() function is

input(msg)

Here msg is the optional string that is displayed on the console.

User input in Python example

val = input('Please enter your name: ')
print('Entered Value- ', val)
Output
Please enter your name: knpcode
Entered Value- knpcode

Input as number in Python

Note that input() function always returns entered value as string. If you want to get the value as integer or float you need to convert it explicitly.

val = input('Please enter a number: ')
# Convert to int
val = int(val)
# now use in arithmetic operation
print(val+5)
Output
Please enter a number: 8
13

You can use int() function along with the input() function to shorten the code-

val = int(input('Please enter a number: '))
# now use in arithmetic operation
print(val+5)

For float numbers you can use float() function

val = float(input('Please enter a number: '))
# now use in arithmetic operation
print(val+5)

Multiple values as input in Python

You can write separate input() functions to take more than one inputs from user. But Python provides a shorter version by using for loop along with input() function to take multiple inputs. Entered values are parsed as separate values by using split() method which considers space as delimiter by default. Therefore separate the separate inputs by space.

num1, num2, num3 = [int(x) for x in input('Please enter three integers: ').split()]
print('Sum of entered numbers-', (num1+num2+num3))
Output
Please enter three integers: 4 5 6
Sum of entered numbers- 15

That's all for the topic Input from User in Python – input() function. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment