Reading input from user in Python
In this post, we will see how to take input from user in Python.
- To read input from user we use the
input()
method - There are 2 cases when reading input from the user, They are
- Reading single input
- Reading multiple inputs
Reading single input
To read a single input from the user, we can simply use the input()
method.
Syntax
variable = input(' prompt ')
Example
name = input("enter name")
print(name)
Reading integers from console
n = int(input("enter n"))
print(n)
Reading float values from console
n = float(input("enter n"))
print(n)
Reading Multiple inputs
To read multiple values we need to use the split()
method or list comprehension.
Using split() method
a,b = input("enter first and last name").split()
print(a+b)
Using list comprehension
x, y = [int(x) for x in input("Enter value ").split()]
print(x+y)