Skip to main content

Python - Input Methods



In this blog we will see how to get input value from console, typecasting input to integer/float/string, different ways to get multiple inputs from console and the common errors we make in using these input methods in python.

 

How to get the input from console?

  • input() function is used to get input from console.
  • When the input() is used in program, program execution flow will be stopped until user gives the input
  • Whatever user enters as input, will be converted to string. 
  • If we get any integer or float value, typecasting should be done.

Syntax: 

input(prompt)

Example:

name = input("Enter your name")


How to typecast input to integer/float/string?

Syntax:

int(input())

float(input())

str(input())

Example:

a = int(input())

b = int(input())

print(a+b)


How to get multiple input from user in Python?

 There are two methods to achieve this.

  • Using split() method
  • Using List comprehension


Using split() method:

split() method used to get multiple inputs from user and split the input based on the separator specified. If the separator is not specified, space is used as separator.

Syntax:

input().split(separator, maxsplit)

Example:

boys, girls = input("Enter number of boys and girls").split()

students_rank = list(map(int,input("Enter the students rank").split()))

print(boys)

print(girls)

print(students_rank)

Output:

Enter number of boys and girls: 5 4

Enter students marks: 5 6 1 3 2 4 7 8 9

5

4

[5, 6, 1, 3, 2, 4, 7, 8, 9]


Using List comprehension:

Example:

x, y = [int(i) for i in input("Enter 2 values").split()]

z = [int(i) for i in input("Enter multiple values").split()]

print(x)

print(y)

print(z)

Output:

Enter 2 values: 2 3

Enter multiple values: 1 2 3 4 5

2

3

[1, 2, 3, 4, 5]


Common Errors:




Comments