VM-LEARNING /class.xi ·track.cs ·ch-2-5 session: 2026_27
$cd ..

~/Expressions, Statements, Type Conversion & I/O

root@vm-learning ~ $ open ch-2-5
UNIT 2 ▪ CHAPTER 5
11
Expressions, Statements, Type Conversion & I/O
Expression · Statement · Precedence · Type casting · input() · print()
A program is built from expressions (things that produce a value) and statements (things the program does). When values of different types meet in one expression, Python may perform type conversion automatically (implicit) or only when you ask (explicit). Finally, a program needs to talk to the outside world — 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.
Learning Outcome 1: Distinguish expressions from statements and evaluate expressions using operator precedence.

11.1 Expression vs. Statement

ExpressionStatement
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 > 0Examples: x = 5, print("hi"), if x > 0:, for i in range(10):, return value
Every statement can contain expressions — a statement like 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.

Operator precedence — highest (1) to lowest (10)
RankOperatorsDescription
1**Exponentiation (right-associative)
2+x, -xUnary plus and minus
3*   /   //   %Multiplication, division, floor-division, modulus
4+   −Addition, subtraction
5<   <=   >   >=   ==   !=Comparisons (relational)
6is   is not   in   not inIdentity and membership
7notLogical NOT
8andLogical AND
9orLogical 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:

  1. Scan from left to right.
  2. Find the highest-precedence operator first.
  3. If two have the same precedence, use associativity rules.
  4. Replace each sub-expression with its value, repeat until a single value remains.
Worked example — evaluate 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
A trickier one — evaluate (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
When precedence gets murky, use parentheses. They cost nothing, remove ambiguity, and make the intent obvious to anyone reading your code tomorrow (including you).
Learning Outcome 2: Apply implicit and explicit type conversion.

11.4 Type Conversion

Type conversion is the process of changing a value from one data type to another. Python supports two flavours:
  • Implicit — Python converts automatically when it is safe.
  • Explicit — you call a conversion function such as int(), float(), str().
Implicit vs Explicit — two ways to convert: Implicit Conversion (Coercion) Python converts automatically — always widens int 5 + float 2.5 float (7.5) int widened to float No data lost · Never needs float(…) int → float → complex Explicit Conversion (Type Casting) You call a function: int(), float(), str() … str "42" int(x) int 42 float 3.9 int(x) int 3 (decimal dropped!) Data can be lost (float→int truncates). Fails if the string isn't a valid number — e.g., int("abc") → ValueError

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'>
Python will never do implicit conversion from a number to a string (or vice versa):
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.

FunctionConverts toExampleResult
int(x)integerint("42"), int(3.9), int(True)42, 3, 1
float(x)floating-pointfloat("3.14"), float(5)3.14, 5.0
str(x)stringstr(42), str(3.14)"42", "3.14"
bool(x)booleanbool(0), bool("hi"), bool([])False, True, False
list(x)listlist("abc")['a', 'b', 'c']
tuple(x)tupletuple([1, 2, 3])(1, 2, 3)
Float → int truncates (it does not round):
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 rounding
Passing a non-numeric string raises ValueError: int("3.14") fails, but int(float("3.14")) works.
Learning Outcome 3: Accept input from the console and display output using print().

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
Mini program — area of a rectangle:
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.

ParameterDefaultPurpose
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.).

Legacy alternatives — still valid and occasionally seen:
# % 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.

Program — calculate GST-inclusive price
# 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/innotandor → 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.
  • int(3.9)3 (truncates). Use round() for proper rounding.
  • Strings and numbers do not mix implicitly — "x" + 5 is a TypeError; you must cast.
  • Input: input(prompt) returns a str. Cast with int()/float() for numeric data.
  • Output: print(a, b, c, sep=" ", end="\n"). sep goes between args; end goes 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()).
🧠Practice Quiz — test yourself on this chapter