5 Ways of Taking Input in Python


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

1. One Line of String

S = input()

Call the built-in function input() without passing any arguments to read the entire line as a string.

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. -- The Python Standard Library Documentation

Let's say you are solving a problem that gives you a line of text and asks you to print its length.

The quick brown fox

You can do this:

S = input()
print(len(S))

2. One Integer Per Line

A = int(input())
B = int(input())

Since input() reads an entire line and it returns a string, you can call it once per line and convert the return to an int.

If the input looks like this:

26
14

And you want to print the sum of these two integers, you can do this:

A = int(input())
B = int(input())
print(A+B)

3. Multiple Integers on a Line

But how can you take input where there are two or more integers on the same line?

26 14 19

You can call input() to read the entire line, then call split() on the string to separate each number into a separate string, and then convert each string to an integer:

S = input() # S => "26 14 19"
Sarray = S.split() # Sarray => ["26", "14", "19"]
A = int(Sarray[0]) # A => 26
B = int(Sarray[1]) # B => 14
C = int(Sarray[2]) # C => 19

If you know that there will be a specific number of numbers on that line, you can shorten the code.

For two numbers:

A, B = map(int, input().split())

For three numbers:

A, B, C = map(int, input().split())

And so on.

4. Floats Instead of Integers

A = float(input())
B, C = map(float, input().split())
Darray = list(map(float, input().split()))

If you want to read floating-point numbers (instead of integers) from your input, use the float() function instead of int() (or float instead of int when using with map()).

5. Read Until EOF

Sometimes you will have to read the entire input, line by line, without knowing exactly how many lines it contains.

import sys

for line in sys.stdin:
	# This loop will run until the input reaches the end.
	# Do something with the line variable here.

Say the input has a series of integers, one per line, of an arbitrary quantity. To find the summation you can do this:

import sys

R = 0
for line in sys.stdin:
	A = int(line)
	R += A
print(R)

Wrap Up

In competitive programming, these are the most common ways you will be taking inputs. As you learn to solve advanced problems, the input layout may become a bit more complicated. Even in those scenarios, you will be using some variation or combination of the ways outlined in this article.

If you have any questions, you are welcome to discuss them below.


Discussion

Related Tutorials

Faster I/O

Learn how to use faster I/O methods in sport programming.

    Toph uses cookies. By continuing you agree to our Cookie Policy.