input() reads a line from the keyboard, print() writes to the screen. This chapter covers all four — expression, statement, type conversion, input/output — in one tightly-connected block, because every Python program you write from here on uses them together.
11.1 Expression vs. Statement
| Expression | Statement |
|---|---|
| Combination of values, variables and operators that evaluates to a single value. | A complete instruction that tells Python to do something. |
| Always has a result. | Does not always have a result. |
| Can appear inside another statement. | Is an "executable line" of the program. |
Examples: 2 + 3, a * b + 5, "hi" + name, len(data), x > 0 | Examples: x = 5, print("hi"), if x > 0:, for i in range(10):, return value |
print(a + b * 2) contains the expression a + b * 2. But an expression by itself is not a statement; the Python shell is kind enough to print the value, while a script simply evaluates and discards it.
11.2 Precedence of Operators — Full Table
When one expression has more than one operator, Python evaluates them in a fixed order called precedence. Higher-precedence operators are applied first — just like how × is done before + in school arithmetic.
| Rank | Operators | Description |
|---|---|---|
| 1 | ** | Exponentiation (right-associative) |
| 2 | +x, -x | Unary plus and minus |
| 3 | * / // % | Multiplication, division, floor-division, modulus |
| 4 | + − | Addition, subtraction |
| 5 | < <= > >= == != | Comparisons (relational) |
| 6 | is is not in not in | Identity and membership |
| 7 | not | Logical NOT |
| 8 | and | Logical AND |
| 9 | or | Logical OR |
| 10 | = += -= *= /= … | Assignment (lowest) |
11.2.1 Associativity
When two operators have the same precedence, associativity decides the order — left-to-right for most, right-to-left for exponentiation and assignment.
print(100 - 40 - 20) # 40 — left-to-right: (100-40)-20 print(2 ** 3 ** 2) # 512 — right-to-left: 2 ** (3 ** 2) = 2**9 print((2 ** 3) ** 2) # 64 — parentheses override
11.3 Evaluating an Expression — Step by Step
When Python meets an expression, it performs the following steps:
- Scan from left to right.
- Find the highest-precedence operator first.
- If two have the same precedence, use associativity rules.
- Replace each sub-expression with its value, repeat until a single value remains.
3 + 4 * 2 ** 3 − 5:
Step 1 — ** has highest precedence: 3 + 4 * 8 - 5 Step 2 — * next: 3 + 32 - 5 Step 3 — + and - are left-associative: 35 - 5 Step 4 — final: 30
(10 > 5) and (3 == 3) or False:
Step 1 — comparisons first: True and True or False
Step 2 — 'and' has higher precedence than 'or':
(True) or False
Step 3 — final: True
11.4 Type Conversion
- Implicit — Python converts automatically when it is safe.
- Explicit — you call a conversion function such as
int(),float(),str().
11.4.1 Implicit Conversion (Type Coercion)
When Python finds mixed types in an arithmetic expression, it widens the "smaller" type to match the "larger" — without data loss. The promotion chain is:
bool → int → float → complex
print(True + 1) # 2 — bool promoted to int print(5 + 2.5) # 7.5 — int promoted to float print(3.0 + (1 + 2j)) # (4+2j) — float promoted to complex print(type(5 + 2.5)) # <class 'float'>
print("hello " + 42) # ❌ TypeError — you must cast 42 to str
11.4.2 Explicit Conversion (Type Casting)
When you know exactly what you want, you ask Python for the conversion. Each built-in type has a function with the same name.
| Function | Converts to | Example | Result |
|---|---|---|---|
int(x) | integer | int("42"), int(3.9), int(True) | 42, 3, 1 |
float(x) | floating-point | float("3.14"), float(5) | 3.14, 5.0 |
str(x) | string | str(42), str(3.14) | "42", "3.14" |
bool(x) | boolean | bool(0), bool("hi"), bool([]) | False, True, False |
list(x) | list | list("abc") | ['a', 'b', 'c'] |
tuple(x) | tuple | tuple([1, 2, 3]) | (1, 2, 3) |
print(int(3.9)) # 3 (not 4) print(int(-3.9)) # -3 (truncates toward zero) print(round(3.9)) # 4 — use round() if you want banker's roundingPassing a non-numeric string raises
ValueError: int("3.14") fails, but int(float("3.14")) works.
11.5 Input from the Console — input()
The built-in function input() pauses the program, waits for the user to type a line and press Enter, and returns the typed text as a string.
name = input("What is your name? ") print("Hello,", name)
A sample run in the terminal:
What is your name? Aarav Hello, Aarav
11.5.1 Always a string — remember to convert
Whatever the user types, input() always returns a str. If you need a number, you must cast it.
age = input("Your age? ") print(age + 1) # ❌ TypeError — str + int not allowed age = int(input("Your age? ")) # ✓ wrap in int() print(age + 1) # ✓ works
length = float(input("Length (m)? ")) breadth = float(input("Breadth (m)? ")) area = length * breadth print("Area =", area, "square metres")Run:
Length (m)? 3.5 Breadth (m)? 2.0 Area = 7.0 square metres
11.5.2 Reading several numbers on one line
A common pattern: user types numbers separated by spaces, you split and convert each one.
line = input("Enter 3 numbers: ") # e.g., 10 20 30 a, b, c = map(int, line.split()) print("Sum =", a + b + c)
11.6 Output to the Console — print()
The built-in print() function writes a message to the screen. It is more flexible than it first appears.
11.6.1 Multiple arguments
You can pass several values; print() puts a space between them and adds a newline at the end.
name = "Aarav" age = 16 print("Name:", name, "| Age:", age) # Output: Name: Aarav | Age: 16
11.6.2 The sep and end parameters
Two keyword arguments control what print() puts between values and at the end.
| Parameter | Default | Purpose |
|---|---|---|
sep | " " (single space) | String placed between the arguments |
end | "\n" (newline) | String placed after the last argument |
print(10, 20, 30, sep=" - ") # 10 - 20 - 30 print("Python", "CS", sep="/") # Python/CS print("Loading", end="...") print("done") # Loading...done # Three statements on separate lines → three outputs on one line: print("A", end="") print("B", end="") print("C") # ABC
11.6.3 Formatted Output — f-strings
The cleanest way to mix text and variables is a formatted string literal (f-string) — a string prefixed with f in which expressions inside { } are evaluated and substituted.
name = "Kavya" marks = 91 pct = marks / 100 print(f"{name} scored {marks}/100 = {pct:.2%}") # Kavya scored 91/100 = 91.00%
Inside the braces you can place any expression, and after a colon you can give a format specifier (:.2f for 2-decimal float, :.2% for percentage, :>10 for 10-wide right-aligned, etc.).
# % operator (C-style) print("%s scored %d/100" % (name, marks)) # .format() method print("{} scored {}/100".format(name, marks))For new code, prefer f-strings — they are faster, easier to read, and harder to get wrong.
11.7 A Tiny Interactive Program
Let us combine everything from this chapter — expression, statement, type conversion, input and output — in one short script.
# gst_price.py — asks for a base price and prints the GST-included price price = float(input("Enter base price (₹): ")) # ← input + explicit conversion rate = 18 # ← integer literal (an expression) gst = price * rate / 100 # ← arithmetic expression with precedence total = price + gst # ← another expression print(f"Base : ₹{price:.2f}") # ← f-string output print(f"GST {rate}% : ₹{gst:.2f}") print(f"Total : ₹{total:.2f}")Sample run:
Enter base price (₹): 500 Base : ₹500.00 GST 18% : ₹90.00 Total : ₹590.00
📌 Quick Revision — Chapter 11 at a Glance
- Expression = produces a value. Statement = complete instruction. A statement can contain expressions.
- Operator precedence (high → low):
**→ unary+/−→* / // %→+ −→ comparisons →is/in→not→and→or→ assignment. - Associativity is left-to-right for most operators; right-to-left for
**and assignments. - Evaluation: scan for the highest-precedence operator, reduce, repeat. Use parentheses to override.
- Type conversion = changing a value's type.
- Implicit (coercion) — Python widens automatically:
bool → int → float → complex. Never loses data. - Explicit (casting) — you call
int(),float(),str(),bool(),list(),tuple(). May truncate or raise errors.
- Implicit (coercion) — Python widens automatically:
int(3.9)→3(truncates). Useround()for proper rounding.- Strings and numbers do not mix implicitly —
"x" + 5is aTypeError; you must cast. - Input:
input(prompt)returns astr. Cast withint()/float()for numeric data. - Output:
print(a, b, c, sep=" ", end="\n").sepgoes between args;endgoes after the last. - f-strings are the modern way to format:
f"Hello {name}, total = {price:.2f}". Expressions and format specifiers go inside{ }. - Read several numbers on one line:
a, b, c = map(int, input().split()).