Week 2 syllabus map
L2.1: IntroductionL2.2: Variables - a programmer’s perspectiveL2.3: Variables revisited - dynamic typingL2.4: More on variables, operators, and expressionsL2.5: Escape characters and types of quotesL2.6: String methodsL2.7: An interesting cipher - more on stringsL2.8: Introduction toifL2.9: Tutorial onif,else, andelifL2.10: Introduction to import libraryL2.11: Different ways to import a libraryL2.12: Conclusion and revision
Week 2 chapter pages (30 minutes each)
00:00-00:30: Chapter 1 - A Quick Introduction to Variables00:30-01:00: Chapter 2 - Variables and Input Statement01:00-01:30: Chapter 3 - Variables and Literals01:30-02:00: Chapter 4 - Data Types 102:00-02:30: Chapter 5 - Data Types 202:30-03:00: Chapter 6 - Operators and Expressions 103:00-03:30: Chapter 7 - Operators and Expressions 203:30-04:00: Chapter 8 - Introduction to Strings04:00-04:30: Chapter 9 - More on Strings04:30-05:00: Chapter 10 - Conclusion: FAQs
Critical quiz fixes (read before MCQs)
int()truncates toward zero:int(4.9)->4int(-4.9)->-4(not-5)
//is floor division:-4.9 // 1->-5.0
- Chained assignment:
x = y = zassigns the current value ofztoxandytoo
- Multi-assignment unpacking:
x, y, z = a, b, cmeansx=a,y=b,z=c
Coverage map for Week 2 quiz patterns
- Assignment and unpacking:
a, b = "56"stylex, y, z = a, b, cthenx = y = z
- Type conversion:
input()returnsstrint()truncation toward zerobool(input())truthiness trap
- Operators:
- precedence
- floor division sign behavior
and/oroperand return behavior
- String method chains:
- return type tracking (
str,list,bool,int) - missing-argument errors (
TypeError) - wrong-method-name errors (
AttributeError)
- return type tracking (
- Formatting:
- zero padding (
:06) - alignment (
:9,:^9,:>9)
- zero padding (
- Branching logic:
if/elifsingle-branch outputs- nested
ifmulti-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
- 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.- Left side (
age) is variable name. - Right side (
19) is value. =in Python means assignment, not mathematical equality.
- Think of variable as a label attached to data.
- Value can be replaced by assigning again.
- Allowed: letters, digits,
_(underscore) - Must not start with a digit
- Case-sensitive:
marksandMarksare different - Avoid keywords like
if,for,class
- 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
type() to inspect:
- Variable does not permanently own one type.
- Current value decides current type.
- fast prototyping
- less boilerplate code
- type bugs if you assume wrong type
L2.4 More on variables, operators, and expressions
Expression:- combination of values, variables, and operators that produces a result
- Arithmetic:
+ - * / // % ** - Relational:
== != > < >= <= - Logical:
and or not - Assignment:
= += -= *= /= - Identity:
is,is not - Membership:
in,not in
()**- unary
+ - * / // %+ -- comparisons (
<,<=,>,>=,==,!=,in,not in,is,is not) notandor
- using
=instead of==in conditions - confusion between
/and// - confusion between
int(-x)and floor behavior - assuming
ismeans same as==
== vs is:
==checks value equalityischecks object identity (same object in memory)
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"""
\ lets you include special chars:
\nnew line\ttab\'single quote in single-quoted string\"double quote in double-quoted string\\backslash
- use prefix
rwhen you want backslashes as normal text
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)andjoin(iterable)
find() behavior:
- returns first index if found
- returns
-1if not found
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.- loop over characters
- ASCII code conversion:
ord()andchr() - modulo
%to wrap around alphabet
L2.8 Introduction to the if statement
if lets program decide based on condition.
Syntax:
- condition ends with
: - block must be indented
- Python uses indentation to define block scope
False,0,0.0,"",[],{},Noneare falsey- most other values are truthy
L2.9 Tutorial on if, else, and elif
Use if-else for two-way choice.
if-elif-else for multiple choices.
Output-set trap: if / elif chain
abc- no output
- printing two lines like
athenb - printing
athenc
if/elif picks at most one branch.
Output-set trap: nested if
- no output
aathenbathenbthenc
- only
b - only
c athenc(withoutb)
Equivalence trap (boolean algebra)
Code:- 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:
- saves development time
- provides tested functions
- improves code organization
mathfor mathematicsrandomfor random valuesdatetimefor date/timeosandpathlibfor files/paths
L2.11 Different ways to import a library
1) Import whole module
2) Import with alias
3) Import selected names
4) Import selected name with alias
5) Wildcard import (avoid in beginner projects)
- 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
=vs==/vs//==vsis- string immutability
- indentation in conditions
- clean import style (
import moduleorfrom module import name)
Week 2 MCQ drill (with answers)
Questions
- What is the type of value returned by
input()? - Output?
- Which is true?
- A)
int(-2.9) == -3 - B)
int(-2.9) == -2
- A)
- Output?
- Which operator checks object identity?
- Output?
- Which option is immutable?
- A)
list - B)
set - C)
tuple
- A)
- Output?
find()returns what if substring is absent?- Which import style is clean for selected names?
- Output?
- Which is better for value comparison?
- A)
== - B)
is
- 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"
- What is
s?
- Type of
s[:3].upper().split()? - Type of
s.startswith()? - Type of
s.startswith("hello")? - Type of
s.lowercase().isalpha()? - Type of
s.isalpha().upper()? - Type of
s.replace('h').index("3")? - Type of
s.join(s.split('-'))? - Type of
s.join(s[0], s[1], s[3])? - Value of
x?
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:
- For this code, select possible outputs:
- Which code is equivalent to:
- In slicing puzzle:
zwtqnkheb for all 5 lines?
32. Sandwich-number implementation trap:
- Why does
num = int(input())withnum[0]fail? - Why does plain
num = input()withfirst + last == middlefail logic?
- Match string operators:
+,*,[],[:],in,\\
- Given:
tacit, trumpet, ease, TrumpeT, which are valid?
Answer key with quick explanation
str(input()always returns text).6and-6(int()truncates toward zero).- B is true.
3 3 3(chained assignment copies currentzvalue).is.-3(floor division for negatives).tuple.yth(endindex excluded).-1.from module import name1, name2.FalseandTrue(non-empty string is truthy).- A (
==for value equality). - A and E.
- A zero-pads to width 6, so
"000500". - E is string repetition + concatenation.
- B gives
"500"; C and D raiseTypeError.
'555 | 66666 | 5555555'.
a, b = "56"unpacks characters.:9(string default left),:^9(center),:>9(right).
list.- Raises
TypeError(missing required argumentprefix). bool.- Raises
AttributeError(lowercaseis not a valid string method). - Raises
AttributeError(isalpha()returnsbool, which has noupper). - Raises
TypeError(replaceneeds botholdandnew). str.- Raises
TypeError(joinexpects one iterable argument).
- if
sis shorter than 4 chars,s[3]may raiseIndexErrorfirst.
True.
input()gives"False"(non-empty string), andbool("False")isTrue.
True.False.True.
1 and 2->2;2 or 0->2;bool(2)->True.
None.- Possible outputs:
a,b,c, or no output. - Possible outputs: no output,
a,athenb,athenbthenc. - Equivalent:
if a and b: print('ab')andif a and c: print('ac')- De Morgan form
if not (not a or not b): ...andif not (not a or not c): ...
a, b, c, d, e = 1, 3, 25, 26, 0.- First fails because
intis not subscriptable (num[0]invalid on int). Second fails because string addition/compare is lexical ('1' + '3' == '4'is false). - Correct mapping:
+-> concatenation*-> repetition[]-> indexing[:]-> slicingin-> membership\\-> escape character
- Valid words:
tacit,trumpet,ease.
TrumpeTfails because first character is uppercase, so'a' <= word[0] <= 'z'is false.
Week 2 final mixed practice
- Take user name and age as input and print a welcome message.
- Check whether entered number is positive, negative, or zero.
- Take a sentence and print:
- character count (without spaces)
- uppercase version
- whether it starts with
A
- Use
mathmodule to print square root of a number. - Write a small Caesar cipher with shift
2.
