Home/Learn/Python A–Z/Type Conversion & Reading Input

Type Conversion & Reading Input

Beginner
Fundamentals

input() always returns a string — converting between str, int, float, list and friends explicitly is how Python programs take and validate data, and how every DSA judge feeds your code.

Overview

Python never silently converts a string to a number (unlike JavaScript). Reading and parsing input correctly matters double on AiCanCode: our DSA judge (and most competitive platforms) feeds your program via stdin as text — you convert it. The patterns here — int(input()), list(map(int, line.split())) — are the exact first lines of nearly every DSA solution you will submit.

Explicit Conversion

int(), float(), str(), list(), set(), tuple() are constructor functions. int("42") works; int("4.2") raises ValueError (go through float first). bool() follows truthiness rules: empty things are False.

Conversions + truthiness (empty = False)
int("42")        # 42
float("3.14")    # 3.14
str(99)          # "99"
int("4.2")       # ValueError!  use int(float("4.2")) -> 4
int("ff", 16)    # 255 — base conversion

list("abc")      # ['a', 'b', 'c']
set([1, 2, 2, 3])# {1, 2, 3} — dedupe trick

# Truthiness — what bool() says
bool(0), bool(""), bool([]), bool(None)   # all False
bool(42), bool("hi"), bool([0])           # all True
# so instead of: if len(items) > 0:
if items:                     # pythonic
    print("has data")

Reading stdin — the DSA Judge Pattern

This is exactly how your Python solutions read test cases on AiCanCode's judge: input() reads one line as a string; split() breaks it on whitespace; map(int, ...) converts each piece.

The first lines of every DSA submission
# Input:
# 5
# 3 8 1 9 4
n = int(input())                        # first line -> int
nums = list(map(int, input().split()))  # "3 8 1 9 4" -> [3, 8, 1, 9, 4]
print(max(nums))                        # 9

# Reading ALL of stdin at once (multi-line safe):
import sys
data = sys.stdin.read().split()
n = int(data[0])
nums = [int(x) for x in data[1:1+n]]

# Two values on one line
a, b = map(int, input().split())

Key Points to Remember

  • 1input() ALWAYS returns str — convert explicitly with int()/float()
  • 2list(map(int, input().split())) is the standard array-reading idiom
  • 3Truthiness: 0, "", [], {}, set(), None are falsy — write "if items:" not "if len(items) > 0:"
  • 4For multi-line judge input, sys.stdin.read().split() is the safest pattern

Interview Questions

Sign in to ask Aria
1

What does input() return and what happens if the user types 42?

EasyCognizant
2

Which values are falsy in Python? Why is "if not my_list:" preferred over "if len(my_list) == 0:"?

EasySwiggy

Ask Aria about Type Conversion & Reading Input

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…