Skip to main content

Week 2 syllabus map

  • L2.1: Introduction
  • L2.2: Variables - a programmer’s perspective
  • L2.3: Variables revisited - dynamic typing
  • L2.4: More on variables, operators, and expressions
  • L2.5: Escape characters and types of quotes
  • L2.6: String methods
  • L2.7: An interesting cipher - more on strings
  • L2.8: Introduction to if
  • L2.9: Tutorial on if, else, and elif
  • L2.10: Introduction to import library
  • L2.11: Different ways to import a library
  • L2.12: Conclusion and revision

Week 2 chapter pages (30 minutes each)

Critical quiz fixes (read before MCQs)

  1. int() truncates toward zero:
    • int(4.9) -> 4
    • int(-4.9) -> -4 (not -5)
  2. // is floor division:
    • -4.9 // 1 -> -5.0
  3. Chained assignment:
    • x = y = z assigns the current value of z to x and y too
  4. Multi-assignment unpacking:
    • x, y, z = a, b, c means x=a, y=b, z=c

Coverage map for Week 2 quiz patterns

  • Assignment and unpacking:
    • a, b = "56" style
    • x, y, z = a, b, c then x = y = z
  • Type conversion:
    • input() returns str
    • int() truncation toward zero
    • bool(input()) truthiness trap
  • Operators:
    • precedence
    • floor division sign behavior
    • and/or operand return behavior
  • String method chains:
    • return type tracking (str, list, bool, int)
    • missing-argument errors (TypeError)
    • wrong-method-name errors (AttributeError)
  • Formatting:
    • zero padding (:06)
    • alignment (:9, :^9, :>9)
  • Branching logic:
    • if/elif single-branch outputs
    • nested if multi-line output combinations

L2.1 Introduction

Python is a high-level programming language focused on readability. In Week 2, you move from basic values to real program flow:
  • storing data in variables
  • processing text with strings
  • making decisions with conditions
  • reusing existing code using modules
Why this week is important:
  • Almost every Python program needs variables, strings, and conditions.
  • Importing modules saves time and avoids reinventing code.

L2.2 Variables: a programmer’s perspective

A variable is a name that refers to a value.
age = 19
name = "Riya"
Key points:
  • Left side (age) is variable name.
  • Right side (19) is value.
  • = in Python means assignment, not mathematical equality.
Programmer perspective:
  • Think of variable as a label attached to data.
  • Value can be replaced by assigning again.
score = 72
score = 85   # updated value
Naming rules:
  • Allowed: letters, digits, _ (underscore)
  • Must not start with a digit
  • Case-sensitive: marks and Marks are different
  • Avoid keywords like if, for, class
Good naming style:
  • use snake_case: total_marks, user_name
  • keep names meaningful and short

L2.3 Variables revisited: dynamic typing

Python is dynamically typed:
  • you do not declare type explicitly (int, str) before assignment
  • type is decided at runtime by value
x = 10        # int
x = "ten"     # now str
Use type() to inspect:
value = 3.14
print(type(value))   # <class 'float'>
Important clarity:
  • Variable does not permanently own one type.
  • Current value decides current type.
Dynamic typing benefits:
  • fast prototyping
  • less boilerplate code
Dynamic typing risk:
  • type bugs if you assume wrong type
amount = "100"
print(amount + 20)   # TypeError
Fix by conversion:
amount = "100"
print(int(amount) + 20)   # 120

L2.4 More on variables, operators, and expressions

Expression:
  • combination of values, variables, and operators that produces a result
total = 45 + 5 * 2
Operator categories:
  • Arithmetic: + - * / // % **
  • Relational: == != > < >= <=
  • Logical: and or not
  • Assignment: = += -= *= /=
  • Identity: is, is not
  • Membership: in, not in
Operator precedence (basic):
  1. ()
  2. **
  3. unary + -
  4. * / // %
  5. + -
  6. comparisons (<, <=, >, >=, ==, !=, in, not in, is, is not)
  7. not
  8. and
  9. or
Use parentheses for clarity:
result = (a + b) * c
Common beginner mistakes:
  • using = instead of == in conditions
  • confusion between / and //
  • confusion between int(-x) and floor behavior
  • assuming is means same as ==
== vs is:
  • == checks value equality
  • is checks object identity (same object in memory)
a = [1, 2]
b = [1, 2]
print(a == b)  # True
print(a is b)  # False
MCQ trap note:
x = 3.742
print(int(x))    # 3
print(int(-x))   # -3
int() truncates toward zero. It does not behave like math.floor() for negative values.

L2.5 Escape characters and types of quotes

Python string quotes:
  • single quote: 'hello'
  • double quote: "hello"
  • triple quote: '''multi line''' or """multi line"""
Escape character \ lets you include special chars:
  • \n new line
  • \t tab
  • \' single quote in single-quoted string
  • \" double quote in double-quoted string
  • \\ backslash
Examples:
print("Line1\nLine2")
print("Name:\tRiya")
print('It\'s fine')
print("He said \"hello\"")
print("Path: C:\\Users\\Riya")
Raw strings:
  • use prefix r when you want backslashes as normal text
path = r"C:\new\test\data"
print(path)

L2.6 String methods

Strings are immutable (cannot change in place). Methods return new strings. Common methods:
  • lower(), upper(), title()
  • strip(), lstrip(), rstrip()
  • replace(old, new)
  • find(sub)
  • count(sub)
  • startswith(prefix), endswith(suffix)
  • split(sep) and join(iterable)
Examples:
text = "  python programming  "
print(text.strip())                  # "python programming"
print(text.upper())                  # "  PYTHON PROGRAMMING  "
print(text.replace("python", "Py"))  # "  Py programming  "
find() behavior:
  • returns first index if found
  • returns -1 if not found
msg = "banana"
print(msg.find("na"))  # 2
print(msg.find("xy"))  # -1

L2.7 An interesting cipher: more on strings

A cipher transforms text using a rule. Simple example: Caesar cipher (shift letters by fixed number). If loops/functions feel new right now, treat this as a preview and revisit after those chapters.
def caesar_encrypt(text, shift):
    out = ""
    for ch in text:
        if 'a' <= ch <= 'z':
            out += chr((ord(ch) - ord('a') + shift) % 26 + ord('a'))
        elif 'A' <= ch <= 'Z':
            out += chr((ord(ch) - ord('A') + shift) % 26 + ord('A'))
        else:
            out += ch
    return out

print(caesar_encrypt("Hello, World!", 3))  # Khoor, Zruog!
Concepts used:
  • loop over characters
  • ASCII code conversion: ord() and chr()
  • modulo % to wrap around alphabet

L2.8 Introduction to the if statement

if lets program decide based on condition. Syntax:
if condition:
    # block
Example:
age = 20
if age >= 18:
    print("Eligible to vote")
Important syntax rules:
  • condition ends with :
  • block must be indented
  • Python uses indentation to define block scope
Truth values:
  • False, 0, 0.0, "", [], {}, None are falsey
  • most other values are truthy

L2.9 Tutorial on if, else, and elif

Use if-else for two-way choice.
marks = 34
if marks >= 35:
    print("Pass")
else:
    print("Fail")
Use if-elif-else for multiple choices.
score = 78
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "D"
print(grade)
Nested conditions:
age = 22
has_id = True

if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("Bring ID")
else:
    print("Not eligible")

Output-set trap: if / elif chain

if a:
    print('a')
elif b:
    print('b')
elif c:
    print('c')
Possible outputs:
  • a
  • b
  • c
  • no output
Not possible:
  • printing two lines like a then b
  • printing a then c
Reason: if/elif picks at most one branch.

Output-set trap: nested if

if a:
    print('a')
    if b:
        print('b')
        if c:
            print('c')
Possible outputs:
  • no output
  • a
  • a then b
  • a then b then c
Not possible:
  • only b
  • only c
  • a then c (without b)

Equivalence trap (boolean algebra)

Code:
if a:
    if b:
        print('ab')
    if c:
        print('ac')
Equivalent forms:
if a and b:
    print('ab')
if a and c:
    print('ac')
and using De Morgan:
if not (not a or not b):
    print('ab')
if not (not a or not c):
    print('ac')
Incorrect equivalent:
if a or b:
    print('ab')
if a or c:
    print('ac')
Best practices:
  • keep conditions readable
  • avoid very deep nesting
  • use parentheses when needed for clarity

L2.10 Introduction to import library

A module (library) is a file/package containing reusable code. import lets you use functions/constants from modules. Basic example:
import math
print(math.sqrt(49))   # 7.0
Why import modules:
  • saves development time
  • provides tested functions
  • improves code organization
Common standard modules:
  • math for mathematics
  • random for random values
  • datetime for date/time
  • os and pathlib for files/paths

L2.11 Different ways to import a library

1) Import whole module

import math
print(math.pi)

2) Import with alias

import math as m
print(m.factorial(5))

3) Import selected names

from math import sqrt, pi
print(sqrt(16), pi)

4) Import selected name with alias

from math import factorial as fact
print(fact(6))

5) Wildcard import (avoid in beginner projects)

from math import *
Why avoid wildcard:
  • pollutes namespace
  • hard to know where names came from
  • can overwrite existing names

L2.12 Conclusion and revision checklist

By end of Week 2, you should be able to:
  • create and update variables safely
  • understand dynamic typing and conversions
  • write and evaluate expressions
  • process strings using methods and escapes
  • build logic using if, elif, else
  • import modules in clean ways
High-value exam points:
  • = vs ==
  • / vs //
  • == vs is
  • string immutability
  • indentation in conditions
  • clean import style (import module or from module import name)

Week 2 MCQ drill (with answers)

Questions

  1. What is the type of value returned by input()?
  2. Output?
x = 6.91
print(int(x))
print(int(-x))
  1. Which is true?
    • A) int(-2.9) == -3
    • B) int(-2.9) == -2
  2. Output?
x, y, z = 1, 2, 3
x = y = z
print(x, y, z)
  1. Which operator checks object identity?
  2. Output?
print(-7 // 3)
  1. Which option is immutable?
    • A) list
    • B) set
    • C) tuple
  2. Output?
s = "python"
print(s[1:4])
  1. find() returns what if substring is absent?
  2. Which import style is clean for selected names?
  3. Output?
print(bool(""))
print(bool("0"))
  1. Which is better for value comparison?
  • A) ==
  • B) is
  1. Select expression(s) equal to "000500":
  • A) f"{500:06}"
  • B) f"{500:03}"
  • C) "0"*3 + 500
  • D) 0*3 + "500"
  • E) "0"*3 + "500"
  1. What is s?
a, b = "56"
s = f'{a*3:9}|{b*5:^9}|{a*7:>9}'
  1. Type of s[:3].upper().split()?
  2. Type of s.startswith()?
  3. Type of s.startswith("hello")?
  4. Type of s.lowercase().isalpha()?
  5. Type of s.isalpha().upper()?
  6. Type of s.replace('h').index("3")?
  7. Type of s.join(s.split('-'))?
  8. Type of s.join(s[0], s[1], s[3])?
  9. Value of x?
x = bool(input())
Input: False 24. Value of bool(1)? 25. Value of bool(0.0)? 26. Value of bool(1 and 2 or 0)? 27. Value of "2" and 4 and None? 28. For this code, select possible outputs:
if a:
    print('a')
elif b:
    print('b')
elif c:
    print('c')
  1. For this code, select possible outputs:
if a:
    print('a')
    if b:
        print('b')
        if c:
            print('c')
  1. Which code is equivalent to:
if a:
    if b:
        print('ab')
    if c:
        print('ac')
  1. In slicing puzzle:
s = "abcdefghijklmnopqrstuvwxyz"
print(s[-a:-len(s):-3])
print(s[::-b])
print(s[c:0:-3])
print(s[len(s):-d:-3])
print(s[:e:-3])
which one gives zwtqnkheb for all 5 lines? 32. Sandwich-number implementation trap:
  • Why does num = int(input()) with num[0] fail?
  • Why does plain num = input() with first + last == middle fail logic?
  1. Match string operators:
  • +, *, [], [:], in, \\
  1. Given:
word = input()
valid = False
if 'a' <= word[0] <= 'z':
    if word[0] == word[-1]:
        valid = True
print(valid)
From tacit, trumpet, ease, TrumpeT, which are valid?

Answer key with quick explanation

  1. str (input() always returns text).
  2. 6 and -6 (int() truncates toward zero).
  3. B is true.
  4. 3 3 3 (chained assignment copies current z value).
  5. is.
  6. -3 (floor division for negatives).
  7. tuple.
  8. yth (end index excluded).
  9. -1.
  10. from module import name1, name2.
  11. False and True (non-empty string is truthy).
  12. A (== for value equality).
  13. A and E.
  • A zero-pads to width 6, so "000500".
  • E is string repetition + concatenation.
  • B gives "500"; C and D raise TypeError.
  1. '555 | 66666 | 5555555'.
  • a, b = "56" unpacks characters.
  • :9 (string default left), :^9 (center), :>9 (right).
  1. list.
  2. Raises TypeError (missing required argument prefix).
  3. bool.
  4. Raises AttributeError (lowercase is not a valid string method).
  5. Raises AttributeError (isalpha() returns bool, which has no upper).
  6. Raises TypeError (replace needs both old and new).
  7. str.
  8. Raises TypeError (join expects one iterable argument).
  • if s is shorter than 4 chars, s[3] may raise IndexError first.
  1. True.
  • input() gives "False" (non-empty string), and bool("False") is True.
  1. True.
  2. False.
  3. True.
  • 1 and 2 -> 2; 2 or 0 -> 2; bool(2) -> True.
  1. None.
  2. Possible outputs: a, b, c, or no output.
  3. Possible outputs: no output, a, a then b, a then b then c.
  4. Equivalent:
  • if a and b: print('ab') and if a and c: print('ac')
  • De Morgan form if not (not a or not b): ... and if not (not a or not c): ...
  1. a, b, c, d, e = 1, 3, 25, 26, 0.
  2. First fails because int is not subscriptable (num[0] invalid on int). Second fails because string addition/compare is lexical ('1' + '3' == '4' is false).
  3. Correct mapping:
  • + -> concatenation
  • * -> repetition
  • [] -> indexing
  • [:] -> slicing
  • in -> membership
  • \\ -> escape character
  1. Valid words: tacit, trumpet, ease.
  • TrumpeT fails because first character is uppercase, so 'a' <= word[0] <= 'z' is false.

Week 2 final mixed practice

  1. Take user name and age as input and print a welcome message.
  2. Check whether entered number is positive, negative, or zero.
  3. Take a sentence and print:
    • character count (without spaces)
    • uppercase version
    • whether it starts with A
  4. Use math module to print square root of a number.
  5. Write a small Caesar cipher with shift 2.
Mini integrated example:
import math

name = input("Enter name: ").strip().title()
num = int(input("Enter a number: "))

if num > 0:
    sign = "positive"
elif num < 0:
    sign = "negative"
else:
    sign = "zero"

root = math.sqrt(abs(num))
print(f"Hello {name}")
print(f"Number type: {sign}")
print(f"Square root of absolute value: {root}")