Python Program to Take Input (With Example)

In this article, we will learn to write python program to take input using built-in methods.

Below built-in methods can be used to take input in python –

  1. Using input() Method
  2. Using sys.stdin.readline() Method

Using input() Method

This built-in method can be used to take input from console. Once user enters input, it evaluates the expression and identifies if it is number or string or list.

Let’s take an example,

n = input("Enter something")
print("Entered value: ", n)

Now, let’s see how these works –

  1. As soon as first line executes, A user message, “Enter something”, is shown in console. This user message is optional. We can simply use input() as well. After this, program flow will be stopped until user provides some input.
  2. Now, whatever is entered in console. input() method converts that into string. After that, value is stored in variable. Here, it will be stored in variable – n.
  3. Then, value of variable n is printed to console.

Using sys.stdin.readline() Method

There is an another method, sys.stdin.readline(), to take input from user using sys module in python.
– stdin stands for standard input which is in stream form from which program reads input provided by user.
sys.stdin.readline() also accepts escape character entered by user.
– We can provided number of characters to be read at a time.

Consider below example,

import sys
  
sampleName = sys.stdin.readline()
print(sampleName)

Here,

  1. When sys.stdin.readline() is executed, program waits for user to provide input.
  2. As soon as value is entered, it is stored in variable sampleName.
  3. After that, we print those value using print() method.

When we run above program, output is –

Tutorialwing
Tutorialwing

Here, first line is user input and second line is value stored in variable sampleName printed using print() method.

That’s how we can write python program to take input with example.

Leave a Reply