Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Python  Module 2 – Values, variables, numbers and strings

Input and output: print(), input() and stdin

Control what print() writes with sep, end, file and flush, read and check what users type with input(), and read whole inputs from stdin for coding judges.

  • Beginner
  • 15 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 15 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Explain where standard input, standard output and standard error go
  • Use sep, end, file and flush to control what print() writes
  • Read user input with input() and convert it safely
  • Read many lines from standard input for judge-style problems
  • Choose a conversion that never runs code that a user typed

Before you start

What you’ll learn · Before you start

What you will learn

  • Explain where standard input, standard output and standard error go
  • Use sep, end, file and flush to control what print() writes
  • Read user input with input() and convert it safely
  • Read many lines from standard input for judge-style problems
  • Choose a conversion that never runs code that a user typed

Before you start

On this page

A coding judge runs your program on an input such as 5, 10 20 and 30 40 50 on three lines, and compares what the program prints with the expected answer, 6 numbers, total 155. Reading text and writing text is all that happens there, and every program talks to the outside world the same way, through three standard streams: The three text channels every program starts with: standard input to read from, standard output for its results and standard error for messages. In Python they are sys.stdin, sys.stdout and sys.stderr..

Below, you control what print() writes and where it goes, read and check what a person types with input(), read a whole input the way judges give it, and see why a program must never run text that someone typed.

Every program reads one stream and writes two

A program reads from standard input, writes its results to standard output, and writes error messages to standard error. In a terminal all three are connected to the terminal itself, but the shell can connect them to files or to other programs, a redirection: Connecting a program's standard input or output to a file or to another program instead of the terminal, as the shell does in python3 solve.py < input.txt > out.txt., and that is how online judges and coding tests feed a program its data and collect its answer. The diagram follows the three streams from where the text comes in to where each one goes, with the shell’s <, >, 2> and |:

Standard input flows into your program through input(); print() writes to standard output, and file=sys.stderr to standard error.Standard input (stdin)keyboard, < file or | pipeYour programStandard output(stdout)screen or > fileStandard error(stderr)screen or 2> fileinput(), sys.stdinprint()file=sys.stderr

The three standard streams of a program

Text description of the diagram

The diagram shows, from top to bottom, where a program's text comes from and where it goes.

  • At the top is standard input (stdin): the keyboard, or a file when the program is started with < file, or the output of another program after a | pipe.
  • An arrow labelled input(), sys.stdin leads from it down to your program: input() reads one line of it, sys.stdin reads it as a file.
  • From your program, one arrow labelled print() leads to standard output (stdout), which is the screen, or a file after > file.
  • Another arrow, labelled file=sys.stderr, leads to standard error (stderr): print(…, file=sys.stderr) writes there. It is the screen too, unless the program is started with 2> file, so error messages stay visible when the normal output goes to a file.

Each stream is a file object of the sys module: sys.stdin, sys.stdout and sys.stderr. input() and print() use them for you, and later sections use them directly where that is clearer.

Checkpoint

Check: The three standard streams

  1. Question 1 of 2 Where does print() write, unless you tell it otherwise?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: To standard output

    print() writes to sys.stdout, standard output. In a terminal that is the screen; with > file it is that file.

  2. Question 2 of 2 A tool runs as python3 tool.py > out.txt and calls print("warning", file=sys.stderr). Where does the warning appear?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: On the screen

    Keeping error messages on standard error means a user who saves the results in a file still sees the warnings, and the file holds results only.

print() writes its arguments to standard output, turning each into text with str(). Four keyword arguments change what it writes and where:

sep, end, file and flush Python · print_options.py
import sys

# By default print() puts a space between values and a line break at the end.
print("tea", "coffee", "juice")
print("tea", "coffee", "juice", sep=", ")
print("tea", "coffee", "juice", sep="")

# end replaces the line break, so the next print() carries on the same line;
# flush=True writes "Saving" out at once instead of keeping it in the buffer.
print("Saving", end="", flush=True)
print("...", end=" ")
print("done")

# Values of any type are written with str(); print() on its own writes an empty line.
print(42, 2.5, True, None, [1, 2])
print()

# file=sys.stderr sends a message to standard error instead of standard output.
print("warning: the price list is empty", file=sys.stderr)

Output

tea coffee juice
tea, coffee, juice
teacoffeejuice
Saving... done
42 2.5 True None [1, 2]

Printed as an error (standard error)

warning: the price list is empty

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 print_options.py

  • sep goes between the values (a space unless you say otherwise), and sep="" glues them together.
  • end is written after the last value (a line break unless you say otherwise). end="" or end=" " lets the next print() carry on the same line.
  • file=sys.stderr sends the text to standard error. The output above shows it under its own label: error messages stay visible on the screen even when a user saves the normal output in a file with > results.txt, and they do not end up mixed with the results.
  • flush=True makes Python write the text at once, as the program does for “Saving”. Output is normally collected in a output buffer: Memory where written text waits before it is sent on: a line at a time when standard output is a terminal, in larger blocks for a file or a pipe. print(..., flush=True) sends it at once. first: a line at a time in a terminal, and in larger pieces when it goes to a file or a pipe. So a progress message printed with end="" may appear late unless you add flush=True, as in print("Working…", end="", flush=True), and lines on standard output and standard error can come out in a different order from the one the program wrote them in.

The four calls below sum up what sep and end add around the values, with every line break named:

Call What it writes
print("tea", "coffee") tea coffee and a line break
print("tea", "coffee", sep="") teacoffee and a line break
print("Saving", end="") Saving, and no line break
print() a line break on its own

Commas in a print() call are often all you need to join values: print("Total:", 5) works where print("Total: " + 5) raises TypeError, because + cannot add a number to a string. An f-string gives you full control over the layout. Press Edit, add sep="-" to the first print() of the program and run it: that line becomes tea-coffee-juice.

Checkpoint

Check: What print() writes

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print("a", "b", sep="")
    print("c", end="!")
    print("d")
    Show the answer: Question 1 of 2

    Answer: ab c!d

    sep goes between the values of one call and end after its last value. Changing end from the line break to "!" lets the next print() continue on the same line.

  2. Question 2 of 2 Which line prints Total: 5?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: print("Total:", 5)

    Commas let print() join values of any type with its separator, a space by default. With +, both sides must already be strings.

input() returns one line, always as a string

input() waits for one line of input and returns it as a string, without the line break at the end. With an argument, it first writes that prompt to standard output, without a line break. Whatever the user types is text, even 29, so a number must be converted, and the conversion must be checked, because people mistype:

Asking until the answer is a number Python · ask_age.py
name = input("Your name: ").strip()

# Ask again until the answer is a whole number.
while True:
    text = input("Your age: ")
    try:
        age = int(text)
        break
    except ValueError:
        print(f"{text!r} is not a whole number, try again.")

print(f"Hello, {name}! Next year you will be {age + 1}.")

Input (standard input)

Kavya
twenty
 29

Output

Your name: Your age: 'twenty' is not a whole number, try again.
Your age: Hello, Kavya! Next year you will be 30.

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 ask_age.py

  • .strip() removes spaces the user typed by accident. int() ignores spaces and a line break around the digits by itself, so " 29" is read as 29.
  • int(text) raises ValueError for text that is not a whole number, such as "twenty". The try block catches it, explains the problem and asks again; the while True loop (the control-flow lessons cover loops) ends with break once a number has been read.
  • The output looks run together because the answers came from the input shown above it, not from a keyboard: input() writes each prompt and then reads a line without printing it. In a terminal, the user’s typing is shown by the terminal itself, so each answer appears after its prompt.

Step through the same run one message at a time, from each call of input() to the string it hands back:

Interactive · message by message Three calls to input() in the run of ask_age.py Step through the run one message at a time. Each step says what input() writes, what it reads and what it hands back.
Three calls to input() in the run of ask_age.py, step 8 of 8. Messages so far: ask_age.py to input(): input("Your name: "); input() to The person or the input: Your name: ; The person or the input to input(): Kavya and a line break; input() to ask_age.py: 'Kavya'; input() to ask_age.py: 'twenty'; input() to ask_age.py: ' 29'.ask_age.pyage = 29input()one call at a timeThe person or the inputlines of textinput("Your name: ")Your name: Kavya and a line break'Kavya''twenty'' 29'

The drawing shows the whole scene; its 8 steps are listed below.

Every step as text
  1. A call with a prompt. The program calls input() with the prompt "Your name". Nothing else in the program runs until input() returns.
  2. The prompt goes out. input() writes the prompt to standard output without a line break, so a person sees it and types right after it.
  3. One line comes back. The first line of the input is Kavya and a line break. input() reads that line, line break and all.
  4. A string is returned. input() drops the line break and returns the rest as a string. The program's .strip() then takes away any spaces typed by accident.
  5. The age, as text. The next call writes "Your age" in the same way and reads the second line, the word twenty. input() hands it back as a string, as it does every line.
  6. int() refuses it. int() raises ValueError for 'twenty'. The except block prints that the answer is not a whole number, and the while loop calls input() again.
  7. A number at last. The third line is a space and 29. input() returns ' 29', still a string, and int() ignores the space around the digits and gives the number 29.
  8. The greeting. break ends the loop, and the program prints its greeting with age + 1, which is 30. Three calls to input() read three lines; a fourth would raise EOFError.

Note

The code runners of this site cannot pause a program to wait for your typing, so they give it all of its input before it starts. The Run button on this page uses the input shown above the output, and the Python Online Compiler has an Input box where you type every line before you press Run. In both, input() reads those lines in order, one per call.

Python Online Compiler Run ask_age.py with your own answers in the Input box, one line for each input() call.

When the input runs out

When there is nothing left to read, input() raises EOFError (EOF is short for end of file (EOF): The point where a stream has nothing left to read. input() raises EOFError there, sys.stdin.readline() returns an empty string, and a for loop over sys.stdin simply stops.):

One line too few Python · end_of_input.py
first = input()
print("Read:", first)

# There is no second line, so input() raises EOFError.
second = input()
print("Read:", second)

Input (standard input)

first line

Output (exit status 1)

Read: first line

Printed as an error (standard error)

Traceback (most recent call last):
  File "end_of_input.py", line 5, in <module>
    second = input()
EOFError: EOF when reading a line

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 end_of_input.py

When you type the input in a terminal, you end it by pressing Ctrl-D (macOS and Linux) or Ctrl-Z followed by Enter (Windows). A program that reads until the end of its input should not count on a fixed number of input() calls; the next section shows the usual ways.

Checkpoint

Check: Reading a line with input()

  1. Question 1 of 2 The person types 29 and presses Enter. What happens?

    Read the code, then choose one answer.

    age = input("Age: ")
    print(age + 1)
    Show the answer: Question 1 of 2

    Answer: A TypeError

    Everything input() returns is a string. Convert it first, int(age) + 1, inside try with an except ValueError for answers that are not numbers.

  2. Question 2 of 2 What does input() do when there is no line left to read?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It raises EOFError

    input() raises EOFError at the end of the input, so a program that reads an unknown number of lines should loop over sys.stdin or read everything with sys.stdin.read().

A judge’s input is read whole or line by line

Online judges and coding tests give a program all of its input on standard input and compare what it prints with the expected answer. Two patterns cover most problems. The first reads everything at once:

Read all the input, then split it Python · sum_all.py
import sys

# Read everything at once and split it into words, whatever the line breaks.
words = sys.stdin.read().split()
total = 0
for word in words:
    total += int(word)
print(len(words), "numbers, total", total)

Input (standard input)

5
10 20
  30 40   50

Output

6 numbers, total 155

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 sum_all.py

sys.stdin.read() returns the whole input as one string, and split() cuts it into words on spaces and line breaks alike, so the program does not care how the numbers are spread over lines. Follow that input through the program, stage by stage:

Interactive · stage by stage From a judge's input to the total, in four stages Step through what sum_all.py does with its input. Each stage shows the value it hands on to the next.
From a judge's input to the total, in four stages, step 5 of 5. Showing Standard input, sys.stdin.read() ('5\n10 20\n 30 40 50\n'), split() (['5', '10', … '50']: 6 words), int() and += (total = 155).Standard inputthree lines from numbers.txtsys.stdin.read()'5\n10 20\n 30 40 50\n'split()['5', '10', … '50']: 6 wordsint() and +=total = 155

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. The judge's input. The input is three lines, 5, then 10 20, then 30 40 50 with extra spaces. The program does not know how many numbers each line holds.
  2. Read it all. sys.stdin.read() returns the whole input in one call, a string of 21 characters with the line breaks and spaces still in it.
  3. Split on any whitespace. split() with no argument cuts at every run of spaces and line breaks and drops the empty pieces, so how the lines were laid out no longer matters.
  4. Convert and add. The loop turns each word into a number with int() and adds it to total, which ends at 155.
  5. The answer. The program prints 6 numbers, total 155, and it would print the same however the judge spread the numbers over lines.

The second pattern goes line by line:

One line at a time Python · line_by_line.py
import sys

# A for loop over sys.stdin reads one line at a time and stops at the end of the input.
for line in sys.stdin:
    print(repr(line), "->", line.rstrip("\n").upper())

# readline() returns "" once the input has run out, instead of raising EOFError.
print(repr(sys.stdin.readline()))

Input (standard input)

tea
chai latte

Output

'tea\n' -> TEA
'chai latte\n' -> CHAI LATTE
''

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 line_by_line.py

A for loop over sys.stdin gets one line per turn, each with its "\n" still on the end (which is what repr() makes visible; only the last line can lack it, when the input does not end with a line break), and stops when the input ends, without an EOFError. sys.stdin.readline() reads a single line and returns an empty string once there is nothing left. On your own computer, you can feed a program a whole file exactly as a judge does: python3 solve.py < input.txt (py solve.py < input.txt in the Windows Command Prompt). PowerShell has no < for input, so there you pipe the file in instead: Get-Content input.txt | py solve.py.

Key idea

Read a judge’s input whole with sys.stdin.read().split() when only the values matter, and with a for loop over sys.stdin when the lines do; neither counts on knowing how many lines will come.

Checkpoint

Check: Reading a judge's input

  1. Question 1 of 2 A judge's input holds three numbers on its first line and two on its second. How many words does sys.stdin.read().split() return?

    Type a number.

    A hint

    split() with no argument treats line breaks like spaces.

    Show the answer: Question 1 of 2

    Answer: 5 words

    read() returns both lines as one string, and split() cuts it at every run of spaces and line breaks, so all five numbers end up in one list, whatever the lines were.

  2. Question 2 of 2 The input is the single line tea. What does this print?

    Read the code, then choose one answer.

    import sys
    first = sys.stdin.readline()
    second = sys.stdin.readline()
    print(repr(first), repr(second))
    Show the answer: Question 2 of 2

    Answer: 'tea\n' ''

    sys.stdin.readline() returns each line with its "\n", and "" at the end. An empty line in the middle of the input comes back as "\n", so "" always means the end.

Never eval() what a user types

eval(text) runs text as a Python expression. You may see eval(input()) used to read a number or a list, but it runs anything the user types, and an expression can import modules, read files and delete them. Convert numbers with int() or float(), which accept numbers and nothing else.

Call What it accepts Runs code?
int(text), float(text) a number written as text No
ast.literal_eval(text) Python literals: numbers, strings, lists, dictionaries and the like No
eval(text) any expression at all Yes, whatever it is given

For text that holds a Python literal, such as a list or a dictionary, ast.literal_eval() reads the value and refuses anything that would run code:

Literals only, no code Python · literal_eval.py
import ast

# literal_eval() reads Python literals (numbers, strings, lists, dictionaries …) and nothing else.
print(ast.literal_eval("[3, 1, 2]"))
print(ast.literal_eval("{'tea': 20, 'coffee': 30}"))

# Anything that would run code is refused, where eval() would have run it.
try:
    ast.literal_eval("__import__('os').getcwd()")
except ValueError as error:
    print("refused:", type(error).__name__)

Output

[3, 1, 2]
{'tea': 20, 'coffee': 30}
refused: ValueError

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 literal_eval.py

Security

Treat everything a program reads, from a user, a file or the network, as untrusted. Convert it with a function that accepts only the format you expect, limit its size, and handle the error when it does not fit. Even ast.literal_eval(), which runs no code, is not recommended by its documentation for untrusted data: a small crafted input can use up memory or crash the interpreter. Keep it for text you trust, such as a value your own program wrote, and use a data format such as JSON (a later lesson) for data from outside.

Checkpoint

Check: Converting without running code

  1. One question A web form sends a price such as 49.50. Which is the right way to read it?

    Choose one answer.

    Show the answer: One question

    Answer: float(text) inside try, handling ValueError

    Convert outside text with the function that accepts exactly the format you expect, here float(), and handle the error when the text does not fit.

Practise: read marks from judge-style input

The exercise reads the layout many judge problems use: a count on the first line and the values on the next. Write the function so that it works on a list of lines and on sys.stdin alike, and refuses input that does not fit the layout. Sample tests run in the page, and the first hint sits under the prompt:

Exercise · Easy · Python

Read marks from judge-style input

Online judges and coding tests give a program its data on standard input in a fixed layout. In this one, the first line holds n, the number of students, and the second line holds their n marks, separated by spaces:

3
70 80 95

Write read_marks(lines), which takes the lines of such an input and returns the average mark, rounded with round(average, 2). For the input above it returns 81.67.

  • lines can be a list of strings such as ["3", "70 80 95"], or an open file such as sys.stdin or an io.StringIO, whose lines still end with "\n". A program would call print(read_marks(sys.stdin)).
  • The numbers may have extra spaces around them, and lines after the second are ignored.
  • Raise ValueError when the second line is missing, when n is less than 1, when the second line does not hold exactly n marks, or when a mark is not a whole number, such as 80.5 or eighty.

The sample tests import your function from marks.py.

Starter code · marks.py

def read_marks(lines):
    """Return the average of the n marks on the second line, rounded to two decimals."""
    # Replace this line with your code.
    return 0.0
The sample tests · test_marks.py
import io

from marks import read_marks


def raises_value_error(lines):
    """True when read_marks(lines) raises ValueError."""
    try:
        read_marks(lines)
    except ValueError:
        return True
    return False


def test_lists():
    """averages the marks of a list of lines"""
    assert read_marks(["3", "70 80 95"]) == 81.67
    assert read_marks(["4", "10 20 30 40"]) == 25.0
    assert read_marks(["1", "100"]) == 100.0


def test_files():
    """reads lines that end with a line break, as a file gives them"""
    assert read_marks(io.StringIO("3\n70 80 95\n")) == 81.67
    assert read_marks(io.StringIO(" 2 \n  50   61 \n")) == 55.5


def test_extra_lines():
    """ignores the lines after the second"""
    assert read_marks(["2", "40 60", "not a mark"]) == 50.0


def test_wrong_count():
    """raises ValueError when the number of marks is not n"""
    assert raises_value_error(["3", "70 80"])
    assert raises_value_error(["2", "70 80 90"])


def test_missing_line():
    """raises ValueError when there is no second line"""
    assert raises_value_error(["3"])
    assert raises_value_error([])


def test_bad_values():
    """raises ValueError for n below 1 and for marks that are not whole numbers"""
    assert raises_value_error(["0", ""])
    assert raises_value_error(["-1", "5"])
    assert raises_value_error(["2", "70 eighty"])
    assert raises_value_error(["2", "70 80.5"])
A hint

list(lines) turns a list, a file or an io.StringIO into a list of its lines, so you can check its length and take rows[0] and rows[1]. int() ignores spaces and the "\n" around a number, split() with no argument does the same for the marks, and int("eighty") raises the ValueError you need without any extra check.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Last, the questions on this lesson come one at a time, starting from what you have missed or not tried yet, with each answer explained as soon as you check it:

Practice that adapts to you

Practise this lesson

14 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 14 ask_age.py is given the three lines Kavya, twenty and 29 as its input. What does it print?

    What does this program print? Choose one answer.

    name = input("Your name: ").strip()
    
    # Ask again until the answer is a whole number.
    while True:
        text = input("Your age: ")
        try:
            age = int(text)
            break
        except ValueError:
            print(f"{text!r} is not a whole number, try again.")
    
    print(f"Hello, {name}! Next year you will be {age + 1}.")
    Show the answer: Question 1 of 14

    Answer: it prints

    Your name: Your age: 'twenty' is not a whole number, try again.
    Your age: Hello, Kavya! Next year you will be 30.

    input() writes its prompt without a line break and returns the line it read without printing it, so when the answers come from a file or an input box, the prompts run together. int(" 29") ignores the space and gives the number 29, so the last line can add 1 to it.

  2. Question 2 of 14 What does this print?

    Read the code, then choose one answer.

    print("x", "y", sep="-", end="!")
    print("z")
    Show the answer: Question 2 of 14

    Answer: x-y!z

    sep goes between the values and end replaces the line break at the end, so the first call writes x-y! and no line break. The second call carries on the same line.

  3. Question 3 of 14 A user types 42 and presses Enter. What does input() return?

    Choose one answer.

    Show the answer: Question 3 of 14

    Answer: The string '42'

    input() always returns a string, without the line break at the end. Convert it yourself with int() or float(), inside try and except ValueError, because the user may type something that is not a number.

  4. Question 4 of 14 The input holds whole numbers spread over several lines, several on some lines. Which line gets a list of all of them as strings?

    Choose one answer.

    Show the answer: Question 4 of 14

    Answer: sys.stdin.read().split()

    sys.stdin.read() returns all of the input as one string, and split() with no argument splits it on spaces and line breaks alike. input() and readline() read only one line, and split(" ") would leave the line breaks inside the pieces.

  5. Question 5 of 14 Which of these never run code that is written in the text they are given?

    Choose every answer that is right.

    Show the answer: Question 5 of 14

    Answer:

    • float(text)
    • ast.literal_eval(text)
    • int(text)

    int() and float() accept only numbers, and ast.literal_eval() only Python literals such as lists and dictionaries; anything else raises an exception. eval() runs whatever expression it is given, so a user could make your program delete files or read secrets. Even so, the documentation of ast.literal_eval() advises against using it on untrusted data, because a crafted input can exhaust memory.

  6. Question 6 of 14 In python3 solve.py < input.txt > out.txt, where does the output of print() in solve.py go?

    Choose one answer.

    Show the answer: Question 6 of 14

    Answer: Into out.txt

    < and > belong to the shell: they connect a program's standard input and standard output to files before the program starts. The program itself reads and prints as always.

  7. Question 7 of 14 Users run your report tool with > results.txt, and its error messages vanish into that file. What change keeps them on the screen?

    Choose one answer.

    Show the answer: Question 7 of 14

    Answer: Print the error messages with file=sys.stderr

    Results belong on standard output and messages about problems on standard error. Then a user can save the results and still see the problems.

  8. Question 8 of 14 What does print() write after its last value when end is not given?

    Choose one answer.

    Show the answer: Question 8 of 14

    Answer: A line break

    print() writes sep between its values (a space) and end after them (a line break), unless you give other values.

  9. Question 9 of 14 A long job prints Working… with end="" just before a slow step, but the message only appears when the step has finished. What fixes it?

    Choose one answer.

    Show the answer: Question 9 of 14

    Answer: Add flush=True to that print()

    Output is collected in a buffer, a line at a time in a terminal and in bigger pieces in a file or a pipe. A message without a line break can sit there, so ask for flush=True when it must show now.

  10. Question 10 of 14 A person types two whole numbers on one line, such as 3 4. Which code reads them as two ints?

    Choose one answer.

    Show the answer: Question 10 of 14

    Answer: parts = input().split(), then int(parts[0]) and int(parts[1])

    input() always returns one string. Split it into pieces, then convert each piece with int(), inside try in case a piece is not a number.

  11. Question 11 of 14 What does a for loop over sys.stdin give on each turn?

    Choose one answer.

    Show the answer: Question 11 of 14

    Answer: One line of the input, with its line break

    A file object such as sys.stdin gives its lines one by one to a for loop, and the loop stops at the end of the input without an error.

  12. Question 12 of 14 A judge sends numbers until the end of the input, with no count telling how many. Which way reads them all?

    Choose one answer.

    Show the answer: Question 12 of 14

    Answer: sys.stdin.read().split(), then int() on each word

    Read until the end of the input, with sys.stdin.read() or a loop over sys.stdin, so the program never depends on a count it was not given.

  13. Question 13 of 14 Why is eval(input()) dangerous?

    Choose one answer.

    Show the answer: Question 13 of 14

    Answer: It runs whatever expression the user types

    eval() turns text into running code. Read numbers with int() or float(), and data with a parser that accepts only the format you expect.

  14. Question 14 of 14 A public web form sends a list of numbers as text. What should the program read it with?

    Choose one answer.

    Show the answer: Question 14 of 14

    Answer: A data format such as JSON, then a check of each item

    For data from outside, use a data format with its own parser, limit the size, and check what you got. The lesson's security note says the same.

Interview questions

Fresher · What does input() return, and how do you read a number with it safely?

input() reads one line from standard input and returns it as a string without its line break; with an argument, it first writes that prompt to standard output. The result is always text, even when the person typed 42, so a number has to be converted. Call int(text) or float(text) inside try and catch ValueError, which they raise for anything that is not a number, such as "forty" or "4 2", and a loop can then ask again. int() ignores spaces and a line break around the digits, so .strip() is optional there. Never use eval(input()) to get a number, because it runs whatever the user types. When the input runs out, input() raises EOFError, so a program that reads an unknown number of lines should loop over sys.stdin instead.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A solution reads a million numbers, one per line, with int(input()) in a loop. It passes the small tests but runs out of time on the large one. Explain where the time goes, rewrite the reading, and say how you would measure the gain without the judge.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    A calculator program reads each line with eval(input()), so that users can type 2 + 3 * 4. Explain why that is unsafe, and replace it with code that accepts arithmetic on numbers and nothing else.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • A program reads standard input and writes standard output and standard error, and the shell can connect each of them to a file or to another program.
  • print() writes to standard output; sep goes between values, end after them, file=sys.stderr sends error messages to standard error and flush=True writes at once.
  • input() returns a string without the line break; convert it with int() or float() inside try and handle ValueError.
  • At the end of the input, input() raises EOFError, while a loop over sys.stdin simply stops.
  • For judge-style input, sys.stdin.read().split() reads every value at once, and a for loop over sys.stdin reads line by line.
  • Never pass user input to eval(). Convert numbers with int() or float(), and keep ast.literal_eval() for literals from a source you trust.

Terms in this lesson

end of file (EOF)
The point where a stream has nothing left to read. input() raises EOFError there, sys.stdin.readline() returns an empty string, and a for loop over sys.stdin simply stops.
output buffer
Memory where written text waits before it is sent on: a line at a time when standard output is a terminal, in larger blocks for a file or a pipe. print(..., flush=True) sends it at once.
redirection
Connecting a program's standard input or output to a file or to another program instead of the terminal, as the shell does in python3 solve.py < input.txt > out.txt.
standard streams
The three text channels every program starts with: standard input to read from, standard output for its results and standard error for messages. In Python they are sys.stdin, sys.stdout and sys.stderr.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.