5 Ways of Taking Input in Python

To use Python in competitive programming, you will have to know how to take input from stdin.


This is a companion discussion topic for the original entry at https://toph.co/tutorials/5-ways-taking-input-python

in the first line, there is only 3, only one input… this is creating problem in my code, how can I ignore that ?

my code is like, a, b = map(int, input().split())

is there any way leave b in blank here ? or I am writing the code in the wrong way :frowning:

help me out, @hjr265

1 Like

Can you give me an example of what the input looks like?

in c i saw people write ----->>>

int a,b,c;
scanf("%d%d%d",&a,&b,&c);
...

how can write this in python??

Hey @imran.py, welcome to Toph.

I am sorry I didn’t notice your post earlier. You can do something like this in Python 3:

a, b, c = map(int, input().split())

Nice list of taking inputs in Python. Let me add on two more ways compatible with Python 3.10.

  1. Use stdin.readline for faster inputs
    Usage:
import stdin
string_input = stdin.readline().strip('\n')

Using readline from stdin is faster than the built-in input() function.

  1. Shorter multiline input
open(0)  # By default, 0 argument to open directs it to reading entire STDIN in a single go
multiline_integers = map(int, open(0))

Using open(0) to take inputs by means of file-handling function open() function allows shorter code that can be helpful in writing shorter code, for cases like Code Golfing.

Hoping that it adds some value to this thread. Happy Pythoning! :slight_smile:

1 Like

@harshit Thank you for sharing these tricks!

I have added them to the main tutorial and credited you as the contributor.

@harshit
To make it clear, open(0) can be used not only with Python 3.10 but also with all versions of Python 3.x.

To read the entire stdin as a string, someone can do-

stdin = open(0).read()

If you’re wondering why to put 0 in place of the filepath, here’s what it represents:

0 stands for stdin

1 stands for stdout

2 stands for stderr

You may ask “why is that?”

Because, in terminal

< is used to read stdin from a file

> is used to write stdout to a file

2> is used to write stderr to a file

Instead of using these symbols, Python allows us to use 0, 1, and 2 to represent these file descriptors.