Python Input and Output Operations

Importing Required Modules

Square Root Function

from math import sqrt

value = int(input())
result = sqrt(value)
print(result)

The input() Function

2.1 Basic Input Operations

Understanding input() Return Type

user_input = input()
print(user_input, type(user_input))

The type() function is a built-in Python function used to check the data type of a variable, such as int, float, or str.

Test Input:

123

Output:

123 <class 'str'>

Test Input:

Iphone 100 promax

Output:

Iphone 100 promax <class 'str'>

Key Observation:

  • Whether you enter numbers or text, input() always returns a string (str).
  • This is a fundamental Python rule: input() always converts keyboard input to string type.
  • The value 123 only looks like a number but is actually stored as a string.

Common Mistake: Adding Two Integers

Incorrect Code:

first = input('Enter first number: ')
second = input('Enter second number: ')
print(type(first), type(second))
print(first + second)

Output:

Enter first number: 13
Enter second number: 24
<class 'str'> <class 'str'>
1324

Problem: The values are concatenated as strings rather than added numerically.

Corrected Code:

first = input('Enter first number: ')
second = input('Enter second number: ')
print(type(first), type(second))
print(int(first) + int(second))

Output:

Enter first number: 13
Enter second number: 24
<class 'str'> <class 'str'>
37

Explanation: The variables first and second remain strings, but explicit type conversion occurs before the arithmetic operation.

Two Approaches:

  • Convert after reading: a = int(a), then print(a + b)
  • Convert during reading: a = int(input('Enter first number: '))

2.2 Common Input Patterns

2.2.1 Reading a Single Line Without Split

line = input()
line = input().strip()  # removes whitespace and tabs

2.2.2 Reading Comma-Separated Values

items = input().split(',')

Sample Input:

apple,banana,orange

2.2.3 Reading a Single Number Per Line

num1 = int(input())
num2 = float(input())

2.2.4 Reading Two Space-Separated Integers

num1, num2 = map(int, input().split())

2.2.5 Reading Hash-Separated Integers

num1, num2 = map(int, input().split('#'))

Sample Input:

1#2

2.2.6 Reading Three Comma-Separated Integers

num1, num2, num3 = map(int, input().split(','))

Sample Input:

1,2,3

2.2.7 Reading Arbitrary Comma-Separated Integers

numbers = list(map(int, input().split(',')))

Sample Input:

1,2,3,4,5

2.2.8 Mixed Format: Numbers with Spaces and Commas

numbers = list(map(int, input().replace(',', ' ').split()))

Sample Input:

1, 2, 3, 4

2.2.9 Reading Two Numbers Across Two Lines

num1 = int(input())
num2 = int(input())

Or for decimals:

num1 = float(input())
num2 = float(input())

2.2.10 Reading Fixed Count of Numbers on Multiple Lines

count = int(input())
values = [int(input()) for _ in range(count)]

Sample Input:

3
10
20
30

2.2.11 Multiple Test Cases: T Groups with 2 Numbers Each

test_cases = int(input())
for _ in range(test_cases):
    a, b = map(int, input().split())
    print(a + b)

Sample Input:

3
1 2
3 4
5 6

2.2.12 Reading Multiple Lines in a Loop

for _ in range(6):
    val = float(input())

Note: range(6) is shorthand for range(0, 6), iterating from 0 to 5 (6 iterations total).

2.2.13 Reading Until Zero is Entered

while True:
    val = int(input())
    if val == 0:
        break

2.2.14 Reading Until Specific Sentinel Values

while True:
    x, y = map(int, input().split())
    if x == 0 and y == 0:
        break

Sample Input:

1 2
3 4
0 0

2.2.15 Reading Until EOF (End of File)

import sys

data = [list(map(int, line.split())) for line in sys.stdin]

Useful for online judges with variable line counts.

2.2.16 Reading Key-Value Pairs

pairs = input().split()
config = {p.split('=')[0]: int(p.split('=')[1]) for p in pairs}

Sample Input:

a=3 b=5 c=9

2.2.17 Removing Whitespace from Input

a = int(input().strip())
b = int(input().strip())
c = int(input().strip())

Or for floating-point values:

a = float(input().strip())
b = float(input().strip())
c = float(input().strip())

The strip() Method:

This string method removes leading and trailing whitespace characters including:

  • Spaces ( )
  • Newlines (\n)
  • Tabs (\t)
  • Carriage returns (\r)
  • Other invisible whitespace

Example 1: Removing Trailing Newlines

num = int(input().strip())

Users may press Enter, adding a newline. strip() removes this before type conversion.

Example 2: String Cleaning

text = "   hello world   "
print(text.strip())

Output:

hello world

Example 3: Removing Newlines

text = "hello\n"
print(text.strip())

Output:

hello

Comparison Table:

Method Behavior
strip() Removes whitespace from both ends
lstrip() Removes whitespace from the left
rstrip() Removes whitespace from the right

Why input().strip() is Common:

User input often includes extra spaces or newlines:

       123

Using int(input()) directly would raise an error. Using int(input().strip()) handles this safely.

2.2.18 Reading 2D Arrays (Matrices) with Known Dimensions

Example 1:

rows, cols = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(rows)]

Sample Input:

3 4
1 2 3 4
5 6 7 8
9 0 1 2

Example 2:

rows, cols = 3, 4
matrix = [list(map(int, input().split())) for _ in range(rows)]

Sample Input:

1 2 3 4
5 6 7 8
9 0 1 2

Note: In the code abovee, cols isn't actually used. This is becauce the example only demonstrates row iteration. However, cols should be used for validation.

With Column Validation:

rows, cols = 3, 4
matrix = []
for _ in range(rows):
    row = list(map(int, input().split()))
    if len(row) != cols:
        print("Column count mismatch!")
    matrix.append(row)

Using Assert for Validation:

rows, cols = 3, 4
matrix = [list(map(int, input().split())) for _ in range(rows)]

for row in matrix:
    assert len(row) == cols, "Column count error"

Reading a Flat Sequence as Matrix:

rows, cols = 3, 4
data = input().split()
matrix = [list(map(int, data[i * cols:(i + 1) * cols])) for i in range(rows)]

for row in matrix:
    print(row)

Sample Input:

1 2 3 4 5 6 7 8 9 10 11 12

Output:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

2.2.19 Reading Matrices with Unknown Column Count

  • Only control the number of rows
  • Accept whatever columns the user provides

Method 1: One Value Per Line

data = []
for _ in range(3):
    val = float(input())
    data.append(val)

for item in data:
    print(item)

Sample Input:

1
5
9

Output:

1.0
5.0
9.0

Note: Blank lines will cause errors since an empty string cannot convert to float.

Method 2: Space-Separated Values Per Row

data = []
for _ in range(n):
    row = list(map(float, input().split()))
    data.append(row)

for row in data:
    print(row)

Sample Input:

1 2 3 4

56 78
9 10 11

Output:

[1.0, 2.0, 3.0, 4.0]
[]
[56.0, 78.0]
[9.0, 10.0, 11.0]

Understanding Memory Representation:

A matrix in memory is simply a list of lists with no newline characters:

M = [
    [1.0, 2.0, 3.0],
    [4.0, 5.0, 6.0]
]

The appearance of one element per line is due to the print() loop, not inherent structure.

Controlling Print Behavior:

for row in data:
    print(row)

This is equivalent to:

print(data[0])
print(data[1])

Single Line Output:

print(data)

Output:

[[1.0, 2.0, 3.0, 4.0], [56.0, 78.0], [9.0, 10.0, 11.0]]

Custom Separator:

for row in data:
    print(row, end=" ")

Output:

[1.0, 2.0, 3.0, 4.0] [56.0, 78.0] [9.0, 10.0, 11.0]

Method 3: List Comprehension (Concise)

n = int(input())
grid = [list(map(int, input().split())) for _ in range(n)]


for row in grid:
    print(row)

Sample Input:

1 2 3 4
5 6 7 8
9 10 11 12

Output:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

How Loop Variables Work:

for x in [10, 20, 30]:
    print(x)

Python automatically creates the variable x for each iteration:

  • First iteration: x = 10
  • Second iteration: x = 20
  • Third iteration: x = 30

Similarly, for row in grid: assigns row = grid[0], then row = grid[1], etc.

Method 4: Using NumPy for Complex Calculations

import numpy as np

n = int(input())
matrix = np.array([list(map(int, input().split())) for _ in range(n)])
print(matrix)

Sample Input:

1 2 3 4
5 6 7 8
9 10 11 12

Output:

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

Method 5: Reading from Files

with open('matrix.txt', 'r') as file:
    matrix = [list(map(int, line.split())) for line in file]

for row in matrix:
    print(row)

File Content (matrix.txt):

1 2 3 4
5 6 7 8
9 10 11 12

Output:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

2.2.20 Reading Unknown Number of Lines

from sys import stdin

for line in stdin.readlines():
    first, second = line.strip().split()

Sample Input:

abcab eee
12343 769

Note: Numeric values like 12343 and 769 are read as strings here.

2.3 Deep Dive: row = list(map(int, input().split()))

Understanding list and map

In Python, list and map are not keywords—they are:

  • list: A built-in type
  • map: A built-in function

Keywords are language syntax structures like if, for, while, class, and def.

Step-by-Step Breakdown

Step 1: input() reads a line as string

Sample input:

1 2 3 4

Step 2: input().split() splits by whitespace in to a list

["1", "2", "3", "4"]

Step 3: map(int, iterable) applies a function to each element

map(int, ["1", "2", "3", "4"])

This converts each string to an integer, producing a map object.

Step 4: Why Not Use list(input().split()) Directly?

row = list(input().split())

Result:

["1", "2", "3"]

All elements remain strings. For numeric operations, map(int, input().split()) is required.

Step 5: Map Returns an Iterator, Not a List

The map object is a "lazy iterator"—it doesn't generate all values at once.

Iterator Characteristics:

Characteristic Description
One at a time Produces elements one by one
Lazy evaluation Doesn't consume memory upfront
Forward-only Cannot go back to previous elements
Memory efficient Ideal for large datasets

Demonstration:

mapper = map(int, ["1", "2", "3"])
print(mapper)

Output:

<map object at 0x7fd5b...>

This confirms it's a map object, not a list.

Understanding Iterators:

Imagine a book:

  • A list is like the entire book on your desk—you can flip anywhere
  • An iterator is like an automatic page turner—only one page at a time, no going back
it = iter([1, 2, 3])

next(it)  # Returns 1
next(it)  # Returns 2
next(it)  # Returns 3
next(it)  # Raises StopIteration

Why Does map() Return an Iterator?

  • Avoids computing all results upfront (memory efficient)
  • Better suited for processing large inputs
  • Python 3 standardizes iterator-based implementations

The print() Function

Usage: print() outputs multiple variables with spaces between them, and automatically adds a newline at the end.

3.1 Basic Output Examples

# Output numbers
print(520)
print(98.5)

# Output strings
print('hello world')
print("hello world")

# Output expressions (evaluated)
print(3 + 1)

# Write to file
file_handle = open('D:/test.txt', 'a+')
print('hello world', file=file_handle)
file_handle.close()

# Output multiple items on one line
print('hello', 'world', 'Python')

Output:

520
98.5
hello world
hello world
4
hello world Python

3.2 Custom End-of-Line Character

a, b, c = 1, 2, 'x'
print(a, b, c, end='!')
print(a)
print(b)
print(c)

3.3 Rounding Decimal Values

value = 12.34567
print("value = " + str(round(value, 1)))
print("value = " + str(round(value, 3)))

3.4 Using Format Specifiers

value = 12.34567
count = 12

print("value = %d" % value)
print("value = %.0f, count = %.0f" % (value, count))
print("value = %d count = %d" % (value, count))
print("value = %d;count = %d" % (value, count))

print("value = %.1f" % value)
print("value = %.3f" % (value * count))

print("value = %f, count = %d" % (value, count))

3.5 F-Strings (Python 3.6+, Recommended)

num = int(input())
decimal = float(input())

print(f"My balance is {num} dollars")
print(f"{num};{decimal} are separated by semicolon")
print(f"Pi rounded to four decimals is {decimal:.4f}")
print(f"{int(decimal)} is an integer!")

3.6 The int() Conversion Rules

  • "123" as string converts to integer 123
  • Invalid strings like "abc" raise an error
  • Decimal 3.9 becomes 3 (truncates toward zero, not rounding)

Example 1:

val = 3.9
print(f"{int(val)} is an integer!")

Output:

3 is an integer!

int(3.9) truncates to 3.

Example 2:

text = "123"
num = int(text)
print(num, type(num))

Output:

123 <class 'int'>

Why Convert?

  • text = "123" is a string
  • num = 123 is an integer

Strings cannot perform arithmetic:

text + 1  # Raises TypeError

But after conversion:

num + 1  # Returns 124

Summary: int() converts numeric-looking strings into actual integers.

Tags: python input() print() Type Conversion f-string

Posted on Sun, 01 Nov 2026 16:46:03 +0000 by JStefan