0% found this document useful (0 votes)
2 views12 pages

Python Teaching Notes

The document provides comprehensive teaching notes on Python fundamentals, covering basic syntax, data types, operators, strings, lists, tuples, and sets. It includes sections for revision and problem-solving, along with practical examples and exercises for students to practice their skills. Key concepts such as indentation, data types, and list comprehensions are emphasized throughout the notes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

Python Teaching Notes

The document provides comprehensive teaching notes on Python fundamentals, covering basic syntax, data types, operators, strings, lists, tuples, and sets. It includes sections for revision and problem-solving, along with practical examples and exercises for students to practice their skills. Key concepts such as indentation, data types, and list comprehensions are emphasized throughout the notes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Fundamentals

Complete Teaching Notes


Covers: Basic Syntax · Data Types · Operators · Strings · Lists · Tuples · Sets · Dictionaries

🔄 REVISION TRACK 🧩 PROBLEM SOLVING TRACK

For students who learned Python before and For students who remember the concepts and are
want to quickly recall concepts with memory- ready to challenge themselves with problem-
jogging notes and examples. solving exercises.

1. Basic Syntax
Python uses indentation (spaces or tabs) to define blocks — no curly braces. Each line is a statement.

1.1 Your First Python Program


print("Hello, World!")
# This is a comment
name = "Vijay" # Variable assignment
print("Hello,", name)

🔄 Key Recall print() outputs text. # starts a comment. Indentation = 4 spaces (PEP8). No semicolons
needed.

1.2 Input from User


name = input("Enter your name: ")
age = int(input("Enter your age: ")) # input() always returns string
print(f"Hello {name}, you are {age} years old.")

💡 Tip input() always returns a string. Wrap it with int(), float() etc. to convert.

1.3 Indentation & Blocks


if age >= 18:
print("Adult") # 4 spaces indent
print("Can vote") # same block
else:

Python Fundamentals — Teaching Notes | Page 1


print("Minor")

⚠️Watch Out Python will throw IndentationError if you mix spaces and tabs. Stick to 4 spaces.

1.4 Variables & Naming Rules


Rule Example Valid?
Start with letter or _ my_var = 5 ✅
Can have numbers (not first) var2 = 10 ✅
No spaces my var = 5 ❌
No special chars my-var = 5 ❌
Case sensitive Name vs name Different vars
Cannot be keyword if = 5 ❌

🧩 Practice Problems
1. Write a program that asks user's name and age, then prints 'Hello [name], in 5 years you will
be [age+5].'
2. What happens if you type letters when int() expects a number? Try it and observe.
3. Write a program that calculates area of a rectangle (take length and breadth as input).
4. Fix this code: x = input('number: ') | print(x + 1) — Why does it fail?
5. CHALLENGE: Ask user for temperature in Celsius, convert and print in Fahrenheit. Formula:
F = C × 9/5 + 32

2. Data Types & Operators


2.1 Built-in Data Types
Type Example type() returns
Integer x = 42 int
Float pi = 3.14 float
String name = "Python" str
Boolean flag = True bool
NoneType val = None NoneType
Complex z = 3+4j complex

print(type(42)) # <class "int">


print(type(3.14)) # <class "float">
print(type(True)) # <class "bool">

Python Fundamentals — Teaching Notes | Page 2


🔄 Key Recall Python is dynamically typed — you don't declare types. Use type() to check.
True/False are capitalized.

2.2 Type Conversion


int("42") # → 42 (string to int)
float("3.14") # → 3.14 (string to float)
str(100) # → "100" (int to string)
bool(0) # → False (0, "", [], None are False-y)
list("abc") # → ["a","b","c"]

💡 Tip Falsy values in Python: 0, 0.0, '', [], {}, set(), None, False

2.3 Arithmetic Operators


Operator Meaning Example Result
+ Addition 7 + 3 10
- Subtraction 7 - 3 4
* Multiplication 7 * 3 21
/ Division (float) 7 / 2 3.5
// Floor Division 7 // 2 3
% Modulus 7 % 3 1
** Exponent 2 ** 8 256

💡 Tip // gives integer result (floor). % gives remainder — useful to check even/odd: n % 2 == 0

2.4 Comparison & Logical Operators


Comparison Meaning
== Equal to
!= Not equal to
< > Less / Greater than
<= >= Less or Equal / Greater or Equal

Logical Meaning Example


and Both must be True x > 0 and x < 10
or At least one True x < 0 or x > 100
not Inverts the result not(x == 5)

Python Fundamentals — Teaching Notes | Page 3


2.5 Assignment Operators (Shorthand)
x = 10
x += 5 # x = x + 5 → 15
x -= 3 # x = x - 3 → 12
x *= 2 # x = x * 2 → 24
x //= 4 # x = x // 4 → 6

🧩 Practice Problems
6. What is 17 % 5? Without running code, calculate it first.
7. Write a program that checks if a number is even or odd.
8. Find if a year is a leap year: divisible by 4, but not 100, unless also by 400.
9. Given a = 5, b = 3 — what is (a**b) % (a+b)?
10. CHALLENGE: Write a program that accepts a 3-digit number and prints the sum of its digits.
(Hint: use // and %)

3. Strings
Strings are sequences of characters, enclosed in single or double quotes. They are immutable in
Python.

3.1 Creating & Accessing Strings


s = "Hello, Python"
s[0] # "H" — indexing from 0
s[-1] # "n" — negative index from end
s[0:5] # "Hello" — slicing [start:end] (end excluded)
s[7:] # "Python" — from index 7 to end
s[::2] # "Hlo yhn" — every 2nd character (step)
s[::-1] # "nohtyP ,olleH" — reverse string

🔄 Key Recall Indexing starts at 0. Slicing: s[start:stop:step]. Negative index counts from end. Strings
are immutable.

3.2 String Methods — Quick Reference


Method What it does Example
upper() UPPERCASE "hello".upper() → "HELLO"
lower() lowercase "HELLO".lower() → "hello"
strip() Remove whitespace " hi ".strip() → "hi"
ends

Python Fundamentals — Teaching Notes | Page 4


split(sep) Split into list "a,b,c".split(",") → ["a","b","c"]
join(list) Join list into string "-".join(["a","b"]) → "a-b"
replace() Replace substring "cat".replace("c","b") → "bat"
find(sub) Index of first match "hello".find("ll") → 2
(-1)
count(sub) Count occurrences "banana".count("a") → 3
startswith() Check prefix "hello".startswith("he") → True
endswith() Check suffix "hello".endswith("lo") → True
isdigit() All chars digits? "123".isdigit() → True
isalpha() All chars letters? "abc".isalpha() → True
zfill(n) Pad with zeros left "7".zfill(3) → "007"

3.3 String Formatting


name, age = "Asha", 20

# f-strings (recommended, Python 3.6+)


print(f"Name: {name}, Age: {age}")
print(f"Pi = {3.14159:.2f}") # 2 decimal places → 3.14
print(f"{42:05d}") # padded → 00042

# .format() method
print("Name: {}, Age: {}".format(name, age))

# % formatting (older style)


print("Name: %s, Age: %d" % (name, age))

💡 Tip Prefer f-strings — they are fastest and most readable in Python 3.6+

3.4 Useful String Operations


len("hello") # 5 — length
"l" in "hello" # True — membership
"hello" + " world" # "hello world" — concatenation
"ha" * 3 # "hahaha" — repetition
"hello".title() # "Hello" — title case
" hello ".lstrip() # "hello " — strip left only

🧩 Practice Problems
11. Reverse the string 'python' without using any built-in reverse function. Use slicing.
12. Count how many vowels are in a user-given string.
13. Check if a given string is a palindrome (reads same forwards and backwards). Ignore case.
14. Take a sentence as input, print each word on a new line. Count total words.

Python Fundamentals — Teaching Notes | Page 5


15. CHALLENGE: Given 'hello world python', capitalize only the first letter of each word and print
'Hello World Python'. Do this without .title() method.

4. Lists
Lists are ordered, mutable collections. They can store mixed data types and allow duplicates.

4.1 Creating & Accessing Lists


fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
empty = []

fruits[0] # "apple" — first element


fruits[-1] # "cherry" — last element
fruits[0:2] # ["apple", "banana"] — slicing
fruits[1] = "mango" # modify — lists are mutable!

🔄 Key Recall Lists: ordered, mutable, allow duplicates, 0-indexed. Use [] to create.

4.2 List Methods — Quick Reference


Method What it does Example
append(x) Add item at end [Link](4)
insert(i,x) Insert at position i [Link](1,"hi")
extend(lst2) Add all items of [Link]([5,6])
lst2
remove(x) Remove first [Link](3)
occurrence
pop() Remove & return last [Link]()
pop(i) Remove & return [Link](0)
index i
sort() Sort in-place [Link]()
ascending
sort(reverse=True) Sort descending [Link](reverse=True)
sorted(lst) Return new sorted sorted(lst)
list
reverse() Reverse in-place [Link]()
index(x) First index of x [Link](3)
count(x) Count occurrences of [Link](2)
x
len(lst) Number of elements len(lst)

Python Fundamentals — Teaching Notes | Page 6


clear() Remove all items [Link]()
copy() Shallow copy lst2 = [Link]()

4.3 List Comprehensions


A compact way to create lists in one line.
squares = [x**2 for x in range(1, 6)]
# → [1, 4, 9, 16, 25]

evens = [x for x in range(20) if x % 2 == 0]


# → [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

upper = [[Link]() for w in ["hi","bye","ok"]]


# → ["HI", "BYE", "OK"]

💡 Tip [expression for item in iterable if condition] — condition part is optional.

4.4 Useful List Operations


3 in [1,2,3,4] # True — membership test
max([3,1,4,1,5]) # 5
min([3,1,4,1,5]) # 1
sum([1,2,3,4]) # 10
[1,2] + [3,4] # [1,2,3,4] — concatenation
[0] * 5 # [0,0,0,0,0] — repetition

🧩 Practice Problems
16. Create a list of squares of all odd numbers from 1 to 20 using list comprehension.
17. Write code to find the second largest element in a list without using sort().
18. Flatten this nested list: [[1,2],[3,4],[5,6]] into [1,2,3,4,5,6] using list comprehension.
19. Remove all duplicates from a list while preserving the original order.
20. CHALLENGE: Given a list of student marks, find the students above average. Input: marks =
[72, 45, 88, 91, 55, 67]. Print count and their scores.

5. Tuples
Tuples are ordered, immutable sequences. Once created, their elements cannot be changed.

5.1 Creating & Accessing Tuples


t = (10, 20, 30)
single = (42,) # comma required for single-element tuple!
coords = 3, 7 # parentheses optional — this is a tuple

Python Fundamentals — Teaching Notes | Page 7


t[0] # 10
t[-1] # 30
t[0:2] # (10, 20) — slicing works
# t[0] = 99 ← TypeError! Tuples are immutable

🔄 Key Recall Tuples: ordered, immutable. Use () or just commas. Single element needs trailing
comma: (x,)

5.2 Tuple Methods & Operations


t = (1, 2, 3, 2, 4, 2)
[Link](2) # 3 — count occurrences
[Link](3) # 2 — first index of value
len(t) # 6 — length
2 in t # True

# Unpacking
a, b, c = (10, 20, 30) # a=10, b=20, c=30
x, *rest = (1, 2, 3, 4) # x=1, rest=[2,3,4]

💡 Tip Tuple unpacking is powerful: a, b = b, a ← swaps two variables without a temp variable!

5.3 List vs Tuple — When to Use What?


Feature List Tuple
Syntax [ ] ( )
Mutable? ✅ Yes ❌ No
Speed Slightly slower Faster
Memory More Less
Can be dict key? ❌ No ✅ Yes
Use for Dynamic data Fixed/constant data
Example Shopping cart Coordinates, RGB

🧩 Practice Problems
21. Try assigning t[0] = 99 to a tuple. What error do you get? How would you 'modify' it?
22. Unpack the tuple ('Alice', 25, 'Engineer') into three variables and print each on a new line.
23. Write a function that returns multiple values (use tuple packing). Return min and max of a list.
24. Can you store a tuple inside a list? And a list inside a tuple? Try both and observe.
25. CHALLENGE: Given a list of (name, score) tuples: [('Alice',85),('Bob',92),('Carol',78)] — sort
them by score in descending order and print the ranking.

Python Fundamentals — Teaching Notes | Page 8


6. Sets
Sets are unordered collections of unique elements. Great for removing duplicates and math set
operations.

6.1 Creating & Using Sets


s = {1, 2, 3, 4, 5}
s2 = set([1, 2, 2, 3, 3]) # → {1, 2, 3} duplicates removed!
empty = set() # NOT {} — that makes an empty dict

# Sets are unordered — no indexing!


# s[0] ← TypeError
3 in s # True — fast membership test

🔄 Key Recall Sets: unordered, unique elements only. No indexing. Use set() for empty set (not {}).

6.2 Set Methods


Method What it does
add(x) Add single element
remove(x) Remove element (KeyError if not found)
discard(x) Remove element (no error if missing)
pop() Remove & return arbitrary element
clear() Remove all elements
union(s2) or | All elements from both sets
intersection(s2) or & Elements in BOTH sets
difference(s2) or - In s1 but NOT in s2
symmetric_difference(s2) or ^ In one but NOT both
issubset(s2) Is s1 inside s2?
issuperset(s2) Does s1 contain all of s2?
isdisjoint(s2) Do they share no elements?

6.3 Set Operations — Visual


A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}

A | B # {1,2,3,4,5,6,7} ← Union
A & B # {3,4,5} ← Intersection
A - B # {1,2} ← Difference (in A, not B)
A ^ B # {1,2,6,7} ← Symmetric Difference

Python Fundamentals — Teaching Notes | Page 9


🧩 Practice Problems
26. Given a list with many duplicates, use a set to remove them and count unique elements.
27. Find common elements between two lists using set intersection.
28. Given two student lists from two classes, find who is in only one class (not both).
29. You have sets A={1,2,3,4} and B={3,4,5,6}. Without running code, predict all four set
operations.
30. CHALLENGE: Given a string, use a set to check if all characters are unique (like checking for
anagram validity). Input: 'listen' vs 'silent' — are they anagrams?

7. Dictionaries
Dictionaries store data as key-value pairs. Keys must be unique and immutable; values can be
anything.

7.1 Creating & Accessing Dictionaries


student = {"name": "Ravi", "age": 20, "grade": "A"}
empty = {}

student["name"] # "Ravi" — access by key


[Link]("age") # 20 — safer (no KeyError)
[Link]("score", 0) # 0 — default if key missing

student["email"] = "r@[Link]" # add new key


student["age"] = 21 # update existing
del student["grade"] # delete key

🔄 Key Recall Dict: key-value pairs. Keys are unique. Use .get() to avoid KeyError. Keys must be
immutable (str, int, tuple).

7.2 Dictionary Methods — Quick Reference


Method What it does Returns
keys() All keys dict_keys view
values() All values dict_values view
items() All (key,value) pairs dict_items view
get(k, default) Value for key k Value or default
update(dict2) Merge dict2 into dict None (in-place)
pop(k) Remove key k, return Value
value
popitem() Remove last inserted (key, value) tuple
pair

Python Fundamentals — Teaching Notes | Page 10


setdefault(k,v) Get k; set to v if Value
missing
clear() Remove all pairs None
copy() Shallow copy New dict
len(d) Number of keys int

7.3 Iterating Over Dictionaries


d = {"a": 1, "b": 2, "c": 3}

for key in d: # iterates over keys


print(key)

for val in [Link](): # iterates over values


print(val)

for key, val in [Link](): # iterate key-value pairs


print(f"{key} → {val}")

7.4 Dictionary Comprehensions


squares = {x: x**2 for x in range(1, 6)}
# → {1:1, 2:4, 3:9, 4:16, 5:25}

even_sq = {x: x**2 for x in range(10) if x % 2 == 0}


# → {0:0, 2:4, 4:16, 6:36, 8:64}

# Invert a dictionary
orig = {"a": 1, "b": 2}
inverted = {v: k for k, v in [Link]()}
# → {1:"a", 2:"b"}

7.5 Nested Dictionaries


school = {
"student1": {"name": "Asha", "marks": 88},
"student2": {"name": "Bharat", "marks": 76}
}

school["student1"]["name"] # "Asha"
school["student2"]["marks"] # 76

💡 Tip For deeply nested dicts, consider using .get() at each level to avoid KeyError chaining.

Python Fundamentals — Teaching Notes | Page 11


🧩 Practice Problems
31. Build a word frequency counter: take a sentence as input, return a dict of {word: count}.
32. Given two dicts d1={'a':1,'b':2} and d2={'b':3,'c':4}, merge them so d2 values win on conflicts.
33. Invert a dictionary: {'a':1,'b':2,'c':3} should become {1:'a', 2:'b', 3:'c'}.
34. Given a list of student names and marks as separate lists, zip them into a dictionary.
35. CHALLENGE: Group a list of words by their first letter. Input: ['apple','ant','bat','ball','cat'].
Output: {'a':['apple','ant'], 'b':['bat','ball'], 'c':['cat']}

8. Master Comparison: All Data Structures


Feature List Tuple Set Dict
Syntax [ ] ( ) { } { k:v }
Ordered? ✅ Yes ✅ Yes ❌ No ✅ Yes (3.7+)
Mutable? ✅ Yes ❌ No ✅ Yes ✅ Yes
Duplicates? ✅ Yes ✅ Yes ❌ No Keys: ❌ No
Indexing? ✅ Yes ✅ Yes ❌ No By Key only
Slicing? ✅ Yes ✅ Yes ❌ No ❌ No
Use case Dynamic seq Fixed data Unique vals Key-value
map

🎯 Key Takeaways for Teaching

What to Emphasize in Class


• Strings, Lists, Tuples support indexing and slicing — Sets and Dicts do not.
• Lists are mutable; Tuples are immutable — use tuples for data that should not change.
• Sets automatically remove duplicates — use them for unique value problems.
• Dicts are the go-to for look-up tables and real-world structured data.
• f-strings are the modern, preferred way to format strings in Python 3.6+.
• List comprehensions are Pythonic and efficient — teach them after basic loops.
• int() fails on non-numeric strings — always handle this in real programs.

📌 Teaching Tip End each section by asking: 'When would you use this in a real program?' — it
anchors learning.

Python Fundamentals — Teaching Notes | Page 12

You might also like