Python Basics
Data Types & I/O
Complete lesson for Data Types & I/O using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Data Types & I/O
Section: Python Basics. Learn Python’s core built-in types and how to print and format values clearly without interactive input.
Scalar built-in types
int— unlimited precision integers:42,0b1010,0o17,0xFF.float— double-precision floating point:3.14,2.5e3(IEEE 754 quirks apply).complex—3+4jwith.realand.imag.bool— subclass ofintwith valuesTrueandFalse.None— the sole value ofNoneType, meaning “no value”.
print(10, type(10).__name__)
print(2.5, type(2.5).__name__)
print(True, type(True).__name__)
print(None, type(None).__name__)
# Output:
# 10 int
# 2.5 float
# True bool
# None NoneType Python data types overview
Python values are objects with a type. The poster below groups the built-ins you will use
every day: int, float, complex, bool,
str, None, then sequences (list/tuple)
and dict/set. Unlike Java, you do not declare a type on the variable —
the object carries its type, and you inspect it with type() or
isinstance().
- Numbers:
int(exact),float(binary decimals),complex. - Text / flags:
stris immutable Unicode;boolisTrue/False. - None: the single
NoneTypevalue — compare withis None. - Collections:
list/tuplefor ordered items;dict/setfor maps and unique values.
Strings as sequences of text
- Create with single, double, or triple quotes:
"hi",'hi',"""multi""". - Strings are immutable — methods return new strings.
- Index with
s[0], slice withs[1:4]; negative indices count from the end. - Raw strings
r"C:\path"reduce backslash escaping (useful for regex and Windows paths).
s = "Python"
print(s[0], s[-1], s[0:3])
print(s.lower(), s.upper())
print(len(s))
# Output:
# P n Pyt
# python PYTHON
# 6 Type inspection and conversion
type(x)returns the type object; often printtype(x).__name__for readability.isinstance(x, int)is preferred overtype(x) is intwhen subclasses matter (boolis anint).- Convert with constructors:
int("42"),float("3.5"),str(99),bool(0). - Invalid conversions raise
ValueError(e.g.,int("3.5")fails — usefloatfirst).
| Expression | Result |
|---|---|
| int(3.9) | 3 (truncates toward zero) |
| float(3) | 3.0 |
| str(True) | 'True' |
| bool("False") | True (non-empty string!) |
| int(True) | 1 |
Numeric basics
- Integer division
//floors toward -∞;%is modulo consistent with that. **is exponentiation;pow(x, y)is the function form.round(x, n)uses bankers’ rounding for ties in many cases — know it exists.divmod(a, b)returns(a // b, a % b).
print(17 // 5, 17 % 5)
print(divmod(17, 5))
print(2 ** 8)
print(round(2.5), round(3.5))
# Output:
# 3 2
# (3, 2)
# 256
# 2 4 Booleans and None
TrueandFalseare keywords; they equal1and0but should be used as booleans.Noneis a singleton — compare withis None.- Functions without an explicit
returnyieldNone. - Avoid using
Noneas a silent failure without documenting it.
flag = True
print(flag, flag + 1)
value = None
print(value is None)
# Output:
# True 2
# True print() output control
print(*objects, sep=" ", end="\n")converts objects withstr()and writes them.- Change
septo join with commas or tabs; changeendto keep multiple prints on one line. file=can redirect (advanced); default is stdout.- For learning, prefer many small prints over complex formatting first.
print("a", "b", "c", sep="-")
print("same", end=" ")
print("line")
# Output:
# a-b-c
# same line String formatting options
- f-strings (3.6+):
f"x={x}"— preferred for clarity and speed. str.format:"x={0}".format(x).- Percent formatting:
"x=%s" % x— older style, still seen in logs. - Format specs:
f"{pi:.2f}",f"{n:04d}",f"{s:>10}"for alignment and precision.
name = "Ada"
score = 95.5
print(f"{name} scored {score:.1f}")
print("{0} scored {1:.1f}".format(name, score))
print("%s scored %.1f" % (name, score))
# Output:
# Ada scored 95.5
# Ada scored 95.5
# Ada scored 95.5 Deterministic I/O in this course
- Lessons avoid
input()so every program has a fixed# Output:section you can verify. - When you need user input later,
input(prompt)returns a string — cast it yourself. - For files, use
pathlib/openin later stdlib lessons. - Always validate and convert external strings before numeric math.
# Simulated input: pretend the user typed "42"
raw = "42"
number = int(raw)
print(number * 2)
# Output:
# 84 Useful string methods
strip,lstrip,rstripremove whitespace.splitandjoinbreak and rebuild text.replace,startswith,endswith,find,countcover common searches.isdigit,isalpha,isalnumhelp validate before conversion.
text = " alice,bob,cara "
clean = text.strip()
parts = clean.split(",")
print(parts)
print(" | ".join(parts))
print(clean.startswith("ali"))
# Output:
# ['alice', 'bob', 'cara']
# alice | bob | cara
# True Advanced — Data Types & I/O
Float imprecision
- Binary floating point cannot represent many decimals exactly:
0.1 + 0.2 != 0.3. - Use
roundfor display; usedecimal.Decimalfor money-like exact base-10 math. - Compare with tolerances:
math.isclose(a, b). - Integers are exact; prefer ints for counts and money in paise/cents when possible.
print(0.1 + 0.2)
print(round(0.1 + 0.2, 1) == 0.3)
# Output:
# 0.30000000000000004
# True Text encodings
- Python 3
strholds Unicode code points;bytesholds raw octets. - Encode/decode with
.encode("utf-8")and.decode("utf-8"). - Default source encoding is UTF-8; keep files UTF-8 in editors.
- Never guess encodings for binary files — treat them as
bytes.
bool is a subclass of int
isinstance(True, int)isTrue— a classic interview gotcha.- Prefer explicit boolean context over using
True/Falsein arithmetic. - When accepting API values, normalize with
bool(...)carefully —bool("False")isTrue. - For config parsing, compare to known strings instead of wrapping arbitrary text in
bool.
print(isinstance(True, int))
print(True + True)
print(bool("False"), bool(""))
# Output:
# True
# 2
# True False Formatting mini-language
- Alignment:
<left,>right,^center; width after the sign. - Types:
dint,ffloat,xhex,%percentage. - Thousands separators:
f"{n:,}"(locale-independent comma). - Debug f-strings (3.8+):
f"{expr=}"prints expression and value — avoid in production logs if secrets exist.
n = 255
pi = 3.14159
print(f"{n:04d}", f"{n:#x}", f"{pi:.2f}", f"{n:,}")
expr = 2 + 2
print(f"{expr=}")
# Output:
# 0255 0xff 3.14 255
# expr=4 Tricky Interview Points
Q1) What are Python’s basic built-in types?
Answer Common scalars include int, float, complex, bool, str, and NoneType. Collections like list, tuple, dict, and set come next in the course.
Q2) Are Python integers limited size?
Answer No practical fixed width in CPython — ints grow as needed (memory permitting).
Q3) Why is 0.1 + 0.2 not 0.3?
Answer Floats use binary IEEE 754 representation; many decimal fractions cannot be represented exactly.
Q4) How do you convert a string to an integer safely?
Answer Call int(s) inside try/except for ValueError, or validate with s.isdigit() for simple unsigned cases (note: isdigit rejects signs and spaces).
Q5) What does bool("False") return and why?
Answer True, because any non-empty string is truthy. Parse explicitly by comparing to "True"/"False" if needed.
Q6) How do f-strings work?
Answer An f-string evaluates expressions inside braces and formats them into a new string at runtime, e.g. f"{name}".
Q7) What is None used for?
Answer To represent the absence of a value: default arguments, optional results, and uninitialized state. Compare with is None.
Q8) Difference between / and //?
Answer / always performs true division (float result for ints). // performs floor division.
Q9) Are strings mutable?
Answer No. String methods return new strings; you rebind names to new values.
Q10) How do you print without a newline?
Answer Pass end="" (or another ending) to print.
Q11) Why prefer isinstance over type(x) is T?
Answer isinstance allows subclasses. Example: True is an instance of int.
Q12) What is the output type of input()?
Answer Always str. Convert explicitly with int, float, etc. (This course avoids input() in samples.)
Simple Programs
Conversions round-trip
n = 42
print(str(n), int("42"), float("3.5"), int(3.9))
# Output:
# 42 42 3.5 3 Format a receipt line
item = "Notebook"
qty = 3
price = 45.5
total = qty * price
print(f"{item:10} x{qty} @ {price:.2f} = {total:.2f}")
# Output:
# Notebook x3 @ 45.50 = 136.50 Parse simulated CSV row
row = "101,Ada,95.5"
pid, name, score = row.split(",")
print(int(pid), name, float(score))
# Output:
# 101 Ada 95.5 Normalize whitespace and case
raw = " PyThOn "
clean = raw.strip().lower()
print(clean)
print(clean.replace("py", "Py"))
# Output:
# python
# Python Numeric helpers
a, b = 29, 5
print(a // b, a % b, divmod(a, b))
print(abs(-12), pow(2, 5), round(3.14159, 3))
# Output:
# 5 4 (5, 4)
# 12 32 3.142 Boolean conversion table
values = [0, 1, 0.0, 0.1, "", "0", None, [], [1]]
for v in values:
print(repr(v), bool(v))
# Output:
# 0 False
# 1 True
# 0.0 False
# 0.1 True
# '' False
# '0' True
# None False
# [] False
# [1] True Problem Solving Tricks
- Prefer f-strings for new code; they read better than
%or long.formatchains. - Use
repr(x)when debugging to see quotes and escape characters. chr/ordconvert between characters and code points for ASCII-range drills.- Triple-quoted strings hold multi-line text without
clutter. - Chain conversions carefully:
int(float("3.0"))when strings may look float-like. - For tables, format with fixed widths:
f"{name:<12}{score:>6}". - Remember
sepandendbefore reaching for string concatenation. str.splitlines()handlesandmore safely than splitting on"\n"alone.- Keep monetary values as integer cents until display time when floats hurt.
Practice Programs List
- Convert five strings to ints and print their sum; include one invalid string handled with a fallback.
- Format a float as currency with two decimals using an f-string.
- Given
"a,b,c", split and join with" -> ". - Show that
bool("0")is True and explain in a comment. - Print a multiplication table row for 7 using f-strings and width specs.
- Demonstrate
0.1 + 0.2and a rounded comparison. - Build a multi-line string of three verses and print it.
- Use
isinstance(True, int)and write one sentence on why it matters. - Strip and title-case a messy name string
" aDa loVeLaCe ". - Simulate three user ages as strings, convert, and print the average as float.
- Create a bytes object from a UTF-8 string and decode it back.