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 –
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 –
- 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.
- 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.
- 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,
- When sys.stdin.readline() is executed, program waits for user to provide input.
- As soon as value is entered, it is stored in variable sampleName.
- 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.