Placement Prep

Python Input: input(), Type Conversion, and Multiple Values

Learn how Python's input() function works, how to convert strings to int or float, read multiple values with split() and map(), and handle EOFError in placement tests.

By FACE Prep Team 5 min read
python input-handling type-conversion placement-prep programming-basics technical-python

Python’s input() function reads one line from the terminal and always returns a string, with no automatic type detection or conversion.

That one sentence is behind the most common TypeError beginners encounter: attempting arithmetic on a value that looks like a number but is still a string. The rest of this guide covers every practical variation: basic usage, safe type conversions, reading multiple values on one line, handling multi-line input the way placement-test judges expect, and a quick-reference table of the four input patterns that appear across almost every online coding round.

What input() Returns (and Why It Matters)

The Python 3 docs are direct: input() reads a line from stdin, strips the trailing newline, and returns a str. No exceptions, no coercion.

name = input("Enter your name: ")
print(type(name))   # <class 'str'>

Run this. Enter your name. The output is <class 'str'>.

Run it again. Enter a number. The output is still <class 'str'>. The value looks like an integer, but Python treats it as a string of digit characters.

n = input("Enter a number: ")
print(n + 10)   # TypeError: can only concatenate str (not "int") to str

Python’s + operator does not silently coerce types. You must convert explicitly.

n = int(input("Enter a number: "))
print(n + 10)   # works correctly

The prompt argument is optional. Placement-test environments and online judges pipe input directly through stdin, so you’ll often see:

# No prompt — standard for competitive programming
n = int(input())

Both forms work identically. The prompt is purely for display in interactive sessions and has no effect on what input() returns.

Type Conversion: int(), float(), and ast.literal_eval()

There are three safe ways to convert string input to a usable type in Python 3.

int() and float()

int() converts a string to an integer. It accepts leading and trailing whitespace, and an optional leading + or - sign. It raises ValueError on anything else, including decimal strings like "3.14".

a = int(input("Enter an integer: "))

float() converts a string to a floating-point number. It accepts decimal notation and scientific notation ("2.5e3" evaluates to 2500.0).

x = float(input("Enter a decimal: "))

Both raise ValueError if the input doesn’t match the expected format. Guard with try/except:

try:
    n = int(input("Enter an integer: "))
    print("You entered:", n)
except ValueError:
    print("That is not a valid integer.")

ast.literal_eval()

The ast.literal_eval() function from Python’s standard library parses a string that represents a Python literal: numbers, strings, bytes, tuples, lists, dicts, sets, booleans, and None. It does not execute code.

import ast

raw = input("Enter a list like [1, 2, 3]: ")
data = ast.literal_eval(raw)   # returns an actual Python list
print(type(data))               # <class 'list'>

Use ast.literal_eval() when the test input arrives as a pre-formatted Python literal structure and you want to parse it without writing a custom parser.

Why not eval()?

eval() evaluates arbitrary Python expressions. If someone passes "__import__('os').system('rm -rf /')" as input, eval() runs it. In a controlled test environment the inputs are fixed, but the habit of using eval() transfers to production code and creates serious security holes.

Rule of thumb: int() for integers, float() for decimals, ast.literal_eval() for structured literals. There is no legitimate use of eval() for input conversion.

Multiple Inputs on One Line: split() and map()

Most placement-test problems give two or more values on a single line, space-separated. The standard idiom:

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

What this does, step by step:

  • input() reads the entire line as a string (for example, "3 7").
  • .split() splits on whitespace and returns a list: ["3", "7"].
  • map(int, ...) applies int() to every element, producing an iterator of integers.
  • a, b = ... unpacks the two integers into separate variables.

For three values, as in problems like finding the greatest of three numbers:

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

For a variable number of values (the pattern for array sum problems and similar):

nums = list(map(int, input().split()))

Switch int to float wherever the values are decimal:

values = list(map(float, input().split()))

Mismatch errors. If the problem promises exactly two values but the test input contains three, Python raises ValueError: too many values to unpack. Read the problem’s input format specification before choosing between fixed unpacking (a, b = ...) and list conversion (list(map(...))).

Custom delimiter. If values are comma-separated instead of space-separated:

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

Pass the delimiter character to .split() as an argument.

Reading Multi-Line Input: sys.stdin and EOFError

Placement tests and online judges use several formats for multi-line input. Knowing all four patterns before the test means you spend zero time on input parsing during the actual round.

Pattern 1 — N lines, count given first

The problem states: “The first line contains N. The next N lines each contain one value.”

n = int(input())
for _ in range(n):
    line = input()
    # process each line

Pattern 2 — Read until EOF

The problem feeds data until end-of-file with no explicit count. Calling input() when stdin is exhausted raises EOFError.

while True:
    try:
        line = input()
        # process line
    except EOFError:
        break

This is the most common pattern in online coding judges. Write it once in a template file and reuse it.

Pattern 3 — Read all stdin at once

import sys

data = sys.stdin.read()           # entire input as one string
lines = data.strip().split('\n')  # split into lines

Use this when you need all the input before any processing can begin (for example, building a grid or matrix). It is also faster than calling input() in a tight loop when the input is large.

Pattern 4 — Iterate over sys.stdin

import sys

for line in sys.stdin:
    line = line.rstrip('\n')
    # process line

Idiomatic when the line count is unknown and you want to avoid the try/except boilerplate.

Common Placement-Test Input Patterns

The four formats that cover almost every standard placement coding problem:

Input FormatExample InputPython to Read It
Single integer7n = int(input())
Two integers, one line3 7a, b = map(int, input().split())
N then N values4 then 1 2 3 4n = int(input()); nums = list(map(int, input().split()))
N lines, one value each3 then 10, 20, 30n = int(input()); vals = [int(input()) for _ in range(n)]

The two-integers pattern is where most beginners spend too long. a, b = map(int, input().split()) is the answer. Memorise it the way you memorise a keyboard shortcut.

For hands-on practice, start with the programs in Python basic programs. Each one requires reading input; working through them reinforces every pattern in the table above. When you’re ready for something more involved, the calculator program combines integer input, type conversion, and operator logic in one small project.


Once input parsing is automatic, the interesting work starts. TinkerLLM’s Python-first environment lets you take the same input() and map() patterns from placement test practice and apply them inside a real LLM workflow: reading parameters, passing prompts, processing results. The entry point is ₹299 for the first month. If you can handle the four input patterns in this guide, you have the Python foundation to start building there.

Primary sources

Frequently asked questions

Does input() return a string or an integer in Python 3?

Always a string. Even if the user types 42, you get the string '42'. Convert explicitly with int(), float(), or ast.literal_eval() before using the value in arithmetic.

How do I read two numbers on the same line in Python?

Use a, b = map(int, input().split()). This reads one line, splits on whitespace, and converts each token to int. Swap int for float if decimal values are expected.

What is EOFError and why does it appear in coding tests?

EOFError is raised when input() reaches end-of-file, which is how online judges signal the end of test input. Wrap your loop in try/except EOFError: break to handle it cleanly.

Is eval() safe for converting user input in Python?

No. eval() executes arbitrary Python expressions, which is a security risk. Use int() or float() for numbers, or ast.literal_eval() for complex literals. None of these execute arbitrary code.

How do I read a list of numbers as input in Python?

Use list(map(int, input().split())) to read all space-separated integers from one line into a Python list.

What is the difference between input() in Python 2 and Python 3?

Python 2 had raw_input() (returns string) and input() (evaluates the expression). Python 3 dropped raw_input() and made input() always return a string, equivalent to Python 2's raw_input().

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF