Taking Inputs in Python

Introduction

As developers, we often need to take input from user in different scenarios. Python provides two in-built functions to read user inputs:

  • input(prompt)
  • raw_input(prompt) – works in older version of Python 2.x

Prompt represents the message before the user provides the input.

Example: input(“Enter the number:”), where the string inside the parenthesis between “ “  is called  prompt.

Different ways to take user input in Python

1.      Using input() function

The input() function works in both Python 2.x as well as Python 3.x version. It first takes the user input and then evaluates the expression. By default, the input is taken as a string.

Program:

ip_string = input("This is an example of user input: ")
print(ip_string)

Output:

This is an example of user input: taking user input
taking user input

2.      Using raw_input() function

The raw_input() function is similar to input() function of Python. It is recommended to use raw_input() in Python 2.x version because of input function vulnerabilities.

Taking multiple inputs in Python

To take multiple inputs in one line we have two in-built functions provided by Python:

  • split()
  • List comprehension

 

1.      Using split()

Generally split() function is used to split the string but one can also use to take multiple input in one line. The input is separated by a specified separator or white space.

Syntax:

input().split(separator, maxSplit)

            where,

separator: A separator is a delimiter that splits the string from that point. By default,

white space acts as the delimiter. It is an optional parameter.

maxSplit: It defines maximum number of splits. It is an optional parameter.

Program:

            ip_num1, ip_num2 = input("Enter two numbers: ").split()
print("First number: ", ip_num1)
print("Second number: ", ip_num2)

Output:

Enter two number: 5 6

First number: 5

Second number: 6

2.      Using List comprehension

List comprehension is widely used by Python developers to create list. But we can also use list comprehension to take multiple inputs from users.

 

Program:

ip_num = [int(ip_num) for ip_num in input("Enter numbers: ").split()]
print("Entered numbers are: ", ip_num)

Output:

Enter number: 5 6 7 8

Entered numbers are: [5, 6, 7, 8]

If we want to take inputs separated by any other delimiter, say comma (,) or colon (:) we can provide it as parameter in split() function.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.