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

Python Learning Notes For Beginners

These Python learning notes are designed for beginners, providing clear explanations, examples, and tips for understanding Python programming. The document covers various topics including Python basics, features, syntax, data types, operators, and more, all aimed at making the learning process simple and engaging. Each section includes mini summaries to reinforce key concepts.

Uploaded by

kitaf63696
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views94 pages

Python Learning Notes For Beginners

These Python learning notes are designed for beginners, providing clear explanations, examples, and tips for understanding Python programming. The document covers various topics including Python basics, features, syntax, data types, operators, and more, all aimed at making the learning process simple and engaging. Each section includes mini summaries to reinforce key concepts.

Uploaded by

kitaf63696
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Learning Notes for Beginners

Welcome to Python! These notes are made for school students and beginners. We use very
simple words. Each topic has clear steps, real-life examples, and code you can try. Let's start
learning Python step by step!

1. Python Basics

Python – Overview
Definition: Python is a simple programming language. It is like English words to tell the
computer what to do.

Why it is used: To make programs fast and easy. Good for websites, games, and data work.

Syntax: No special syntax needed to start.

Example 1:

print("Python is fun!")

Output:

Python is fun!

Example 2:

name = "Alice"
print("Hello, " + name)

Output:

Hello, Alice

Example 3:

age = 12
print("I am " + str(age) + " years old.")
Output:

I am 12 years old.

Explanation:

Example 1: Prints a message. Like saying hello on paper.


Example 2: Uses a name variable. Like writing your friend's name.
Example 3: Mixes number and text. Real life: Telling your age.
Tips / Common mistakes:

Tip: Python does not need semicolons like other languages.


Mistake: Forget quotes around text. Fix: Always use " " for words.
Mini Summary: Python is easy like talking. Use it for quick programs.

Python – History
Definition: Python started in 1991 by Guido van Rossum. Named after a funny TV show.

Why it is used: To know why Python is simple and popular today.

No code examples. (History topic)

Tips / Common mistakes: Tip: Guido made it for easy reading, like a book.

Mini Summary: Born in 1991, Python grew because it is friendly.

Python – Features
Definition: Python has easy rules, free to use, works on all computers.

Why it is used: Makes coding fast without hard work.

Example 1: Easy to read code.

# Simple addition
a = 5
b = 3
print(a + b)

Output:

Example 2: Short loops (later topic preview).


for i in range(3):
print(i)

Output:

0
1
2

Example 3: No need for main function.

print("Runs right away!")

Output:

Runs right away!

Explanation:

Like writing a shopping list: short and clear.


Real life: Features save time, like a bike vs walking.
Tips / Common mistakes:

Tip: Indent with spaces (4 spaces best).


Mistake: Mix tabs and spaces. Fix: Use only spaces.
Mini Summary: Python is simple, free, and powerful.

Python vs C++
Definition: Python is easy like English. C++ is hard like math formulas.

Why it is used: Choose Python for quick start, C++ for speed in games.

No code, comparison table:

Feature Python C++

Easy to learn Yes, very easy No, hard

Speed Slow Very fast

Lines of code Few Many

Tips: Start with Python, learn C++ later.

Mini Summary: Python for beginners, C++ for experts.


Python - Hello World Program
Definition: First program to say "Hello, World!".

Why it is used: Tests if Python works. Like first "hi" in class.

Syntax:

print("Hello, World!")

Example 1:

print("Hello, World!")

Output:

Hello, World!

Example 2:

print("Hello, India!")

Output:

Hello, India!

Example 3:

message = "Hello, Surat!"


print(message)

Output:

Hello, Surat!

Explanation:

print() shows text on screen.


Real life: Like shouting in a room, everyone hears.
Tips / Common mistakes:

Tip: Save file as .py.


Mistake: No brackets in print. Fix: print("text")
Mini Summary: print() is your first friend in Python.
Python - Application Areas
Definition: Python used in web (Instagram), data (Netflix), games (Eve Online).

Why it is used: One language for many jobs.

No code examples.

Tips: Real life: Python like a multi-tool knife.

Mini Summary: Python everywhere – web, AI, science.

Python – Interpreter
Definition: Interpreter reads Python code line by line, like a teacher explaining book.

Why it is used: No need to compile. Run code fast.

Example 1: In terminal:

python -c "print('Hi')"

Output:

Hi

Example 2 (save as [Link], run python [Link]):

print("Interpreter runs me!")

Output:

Interpreter runs me!

Explanation:

Type code, run instantly.


Real life: Like talking to a friend, answer comes quick.
Tips: Tip: Use IDLE or online like Replit.

Mini Summary: Interpreter makes Python instant.


Python - Environment Setup
Definition: Install Python on computer.

Why it is used: To write and run code.

Steps:

1. Go to [Link]
2. Download for Windows/Mac
3. Install, check "Add to PATH"
4. Open terminal, type python --version
Example: Test setup.

print("Setup done!")

Output:

Setup done!

Tips / Common mistakes:

Mistake: Forget PATH. Fix: Reinstall with checkbox.


Mini Summary: Download from [Link], test with print.

Python - Virtual Environment


Definition: Separate folder for projects, like different rooms for different games.

Why it is used: Avoid mix-up of tools between projects.

Syntax:

python -m venv myenv


myenv\Scripts\activate # Windows
source myenv/bin/activate # Mac/Linux

Example 1: Create and test.

python -m venv testenv

Then in activated env:

print("Virtual env works!")


Output:

Virtual env works!

Example 2: Deactivate with deactivate.

Explanation:

Real life: Like school bag for each subject.


Tips: Tip: Always use for big projects.

Mini Summary: venv keeps projects clean.

Python - Basic Syntax


Definition: Rules for writing code, like grammar in English.

Why it is used: Computer understands correctly.

Syntax: Indent with 4 spaces, no braces.

Example 1:

if True:
print("Yes")

Output:

Yes

Example 2:

name = "Bob"
print(name)

Output:

Bob

Example 3:

a, b = 1, 2
print(a + b)

Output:
3

Explanation:

Indent shows blocks.


Real life: Like paragraphs in a story.
Tips / Common mistakes:

Mistake: Wrong indent. Fix: 4 spaces.


Mini Summary: Simple rules: indent, no ; needed.

Python – Variables
Definition: Box to store data, like a name tag on a bag.

Why it is used: Reuse values easily.

Syntax: variable_name = value

Example 1:

age = 15
print(age)

Output:

15

Example 2:

name = "Riya"
print("Hi " + name)

Output:

Hi Riya

Example 3:

price = 100
price = 200 # Change it
print(price)

Output:
200

Explanation:

Change anytime.
Real life: Age changes each birthday.
Tips / Common mistakes:

Tip: Use small letters, _ for spaces.


Mistake: Start with number. Fix: letter first.
Mini Summary: Variables hold data like bags.

Python - Private Variables


Definition: Variables not for outside use, start with __ (double underscore).

Why it is used: Hide secret data, like private diary.

Syntax: self.__secret = 10

Example 1 (in class, simple):

class Box:
def __init__(self):
self.__age = 12 # Private

def show(self):
print(self.__age)

b = Box()
[Link]()

Output:

12

Example 2:

# Can't access directly


# print(b.__age) # Error!

Example 3: Simple function private-like.

def func():
_private = "secret"
print(_private)
func()

Output:

secret

Explanation:

__ makes it hard to touch from outside.


Real life: Lock your room.
Tips: Tip: Use for class secrets.

Mini Summary: Private vars protect data.

Python - Data Types


Definition: Types of data: int (numbers), str (text), float (decimal).

Why it is used: Computer knows how to handle.

Syntax: type(value)

Example 1:

x = 5
print(type(x))

Output:

<class 'int'>

Example 2:

y = "Hello"
print(type(y))

Output:

<class 'str'>

Example 3:

z = 3.14
print(type(z))
Output:

<class 'float'>

Explanation:

int: Whole fruits (5 apples).


str: Names.
Real life: Sort toys by type.
Tips / Common mistakes:

Mistake: Mix types in math. Fix: Check type().


Mini Summary: Know types: int, str, float.

Python - Type Casting


Definition: Change data type, like paint number to text.

Why it is used: To mix different data.

Syntax: int(), str(), float()

Example 1:

num = "10"
n = int(num)
print(n + 5)

Output:

15

Example 2:

age = 16
text = str(age)
print("Age: " + text)

Output:

Age: 16

Example 3:

f = float("3.5")
print(f + 1)

Output:

4.5

Explanation:

Real life: Change money to words for note.


Tips: Tip: Use when input is string.

Mini Summary: Cast to change types safely.

Python - Unicode System


Definition: Unicode lets Python use any language letters, like Hindi, emoji.

Why it is used: For world languages.

Syntax: Use any chars in strings.

Example 1:

print("नमस्ते") # Hindi

Output:

नमस्ते

Example 2:

print("😊 Python")

Output:

😊 Python

Example 3:

name = "कस्तूरी"
print("Hi " + name)

Output:

Hi कस्तूरी
Explanation:

Python handles all chars.


Real life: Write in your language.
Tips: Save file as UTF-8.

Mini Summary: Unicode for global text.

Python – Literals
Definition: Fixed values in code, like 5 or "hi".

Why it is used: Quick data without variables.

Example 1:

print(42) # Integer literal

Output:

42

Example 2:

print("Python") # String literal

Output:

Python

Example 3:

print(3.14) # Float literal

Output:

3.14

Explanation:

Real life: Write price directly on tag.


Tips: Don't change literals.

Mini Summary: Literals are fixed values.


2. Operators

Python – Operators
Definition: Symbols to do work on data, like + for add.

Why it is used: Math and checks fast.

Example 1:

a = 10 + 5
print(a)

Output:

15

Example 2:

print(20 > 10)

Output:

True

Example 3:

print("Hi" in "Hi Mom")

Output:

True

Explanation:

Real life: + like adding toys.


Tips: Know order (later precedence).

Mini Summary: Operators do actions.


Arithmetic Operators
Definition: Math signs: + - * / % ** //

Why it is used: Calculate numbers.

Syntax: a + b

Example 1:

print(10 + 5)

Output:

15

Example 2:

print(10 / 3) # Float divide

Output:

3.3333333333333335

Example 3:

print(2 ** 3) # Power

Output:

Explanation:

% remainder like candies after sharing.


Real life: Shop bill.
Tips / Common mistakes:

Mistake: / vs // (int divide). // gives 3 for 10//3.


Mini Summary: Basic math with operators.
Comparison Operators
Definition: == != > < >= <= to compare.

Why it is used: Check if true or false.

Example 1:

print(5 == 5)

Output:

True

Example 2:

print(10 > 7)

Output:

True

Example 3:

print("A" < "B")

Output:

True

Explanation:

Real life: Is my height > yours?


Tips: == not = .

Mini Summary: Compare for True/False.

Assignment Operators
Definition: = += -= etc to give values.

Why it is used: Short way to update.

Example 1:
x = 5
x += 3 # x = x + 3
print(x)

Output:

Example 2:

y = 10
y *= 2
print(y)

Output:

20

Example 3:

z = 20
z //= 3
print(z)

Output:

Explanation:

Short like score += goal.


Tips: Use for loops.

Mini Summary: Quick updates.

Logical Operators
Definition: and or not for True/False mix.

Why it is used: Multiple conditions.

Example 1:

print(True and False)


Output:

False

Example 2:

age = 18
print(age > 16 and age < 65)

Output:

True

Example 3:

print(not True)

Output:

False

Explanation:

and: Both true.


Real life: Eat if hungry and food ready.
Tips: Short-circuit: and stops if first False.

Mini Summary: Combine truths.

Bitwise Operators
Definition: & | ^ ~ << >> for binary bits.

Why it is used: Low-level number tricks.

Example 1:

print(5 & 3) # 101 & 011 = 001

Output:

Example 2:
print(5 | 3) # 101 | 011 = 111

Output:

Example 3:

print(5 << 1) # Shift left

Output:

10

Explanation:

Real life: Lights on/off switches.


Tips: For advanced, not daily.

Mini Summary: Bit magic for numbers.

Membership Operators
Definition: in not in to check if item inside.

Why it is used: Search in lists/strings.

Example 1:

print("a" in "cat")

Output:

True

Example 2:

nums = [1,2,3]
print(2 in nums)

Output:

True
Example 3:

print("x" not in "hi")

Output:

True

Explanation:

Real life: Is apple in fruit basket?


Tips: Fast for big lists.

Mini Summary: Check "inside".

Identity Operators
Definition: is is not to check same object.

Why it is used: See if two vars point same place.

Example 1:

a = 5
b = 5
print(a is b)

Output:

True

Example 2:

x = [1,2]
y = x
print(x is y)

Output:

True

Example 3:

z = [1,2]
print(x is z)
Output:

False

Explanation:

Real life: Same toy or copy?


Tips: is for objects, == for value.

Mini Summary: Check same memory.

Walrus Operator
Definition: := assign and use in one, new in Python 3.8.

Why it is used: Short code in if/while.

Example 1:

if (n := 10) > 5:
print(n)

Output:

10

Example 2:

print(x := "Hi")

Output:

Hi

Example 3:

while (count := count + 1) < 3:


print(count)

Output:

1
2

Explanation:
Real life: Measure and check height same time.
Tips: Use in loops.

Mini Summary: := saves lines.

Operator Precedence
Definition: Order of operators, like () first, then **, then + -.

Why it is used: Avoid wrong math.

Example 1:

print(2 + 3 * 4) # * first

Output:

14

Example 2:

print((2 + 3) * 4) # () first

Output:

20

Example 3:

print(10 / 2 + 1) # / and + left to right

Output:

6.0

Explanation:

Real life: PEMDAS in school.


Tips: Always use () for clear.

Mini Summary: () > ** > + -


3. Input, Output & Basics

Python – Comments
Definition: # lines ignored by computer, for notes.

Why it is used: Explain code to humans.

Syntax: # This is comment

Example 1:

# Add two numbers


print(2 + 3)

Output:

Example 2:

name = "Ana" # My friend


print(name)

Output:

Ana

Example 3:

"""
Multi-line
comment
"""
print("Code runs")

Output:

Code runs

Explanation:

Real life: Sticky notes on book.


Tips / Common mistakes:

Tip: Use for why, not what.


Mini Summary: # for notes.

Python - User Input


Definition: input() asks user for data.

Why it is used: Make program talk to user.

Syntax: name = input("Prompt: ")

Example 1:

name = input("Your name? ")


print("Hi " + name)

Output (if input "Bob"):

Your name? Bob


Hi Bob

Example 2:

age = int(input("Age? "))


print("Next year: " + str(age + 1))

Output (input 12):

Age? 12
Next year: 13

Example 3:

num1 = float(input("Num1: "))


num2 = float(input("Num2: "))
print(num1 + num2)

Output (3.5, 2.5):

Num1: 3.5
Num2: 2.5
6.0

Explanation:

input always string, cast to int/float.


Real life: Ask friend's name.
Tips: Use int() for numbers.

Mini Summary: input() for user chat.

Python – Numbers
Definition: int (whole) and float (decimal) numbers.

Why it is used: Count things.

Example 1:

x = 100 # int
print(x)

Output:

100

Example 2:

y = 3.14159 # float
print(y)

Output:

3.14159

Example 3:

print(10 + 2.5)

Output:

12.5

Explanation:

Real life: int for books, float for money.


Tips: Big ints ok in Python.

Mini Summary: Numbers for math.


Python – Booleans
Definition: True or False values.

Why it is used: Yes/no decisions.

Example 1:

print(True)

Output:

True

Example 2:

is_adult = 18 > 16
print(is_adult)

Output:

True

Example 3:

print(5 == "5") # False

Output:

False

Explanation:

Real life: Is light on? True/False.


Tips: Lowercase true/false wrong.

Mini Summary: True/False for checks.

Python - Floating Points


Definition: float for decimals, like 3.14.

Why it is used: Precise measures.

Example 1:
pi = 3.14
print(pi)

Output:

3.14

Example 2:

print(10 / 3)

Output:

3.3333333333333335

Example 3:

height = 5.9
print(height * 2)

Output:

11.8

Explanation:

Real life: Weight 50.5 kg.


Tips: Round with round(3.333, 1) = 3.3

Mini Summary: Floats for decimals.

4. Control Flow & Decision Making

Python - Control Flow


Definition: Path code takes, like roads with turns.

Why it is used: Decide what to do next.

(Examples in subtopics)

Mini Summary: Flow controls order.


Python - Decision Making
Definition: Choose based on True/False.

Why it is used: Smart programs.

(Details below)

Mini Summary: If for choices.

If Statement
Definition: Do something if True.

Syntax:

if condition:
code

Example 1:

age = 18
if age >= 18:
print("Adult")

Output:

Adult

Example 2:

score = 90
if score > 80:
print("Good!")

Output:

Good!

Example 3:

is_rain = False
if not is_rain:
print("Play outside")

Output:
Play outside

Explanation:

Real life: If hungry, eat.


Tips: Indent inside if.

Mini Summary: if for single check.

If-else
Definition: If True do this, else that.

Syntax:

if cond:
...
else:
...

Example 1:

age = 15
if age >= 18:
print("Vote")
else:
print("Wait")

Output:

Wait

Example 2:

mark = 75
if mark >= 60:
print("Pass")
else:
print("Fail")

Output:

Pass

Example 3:
temp = 25
if temp > 30:
print("Hot")
else:
print("Cool")

Output:

Cool

Explanation:

Real life: If win, cheer; else try again.


Tips: else no condition.

Mini Summary: Two paths.

Nested If
Definition: if inside if.

Why it is used: More choices.

Example 1:

age = 20
if age >= 18:
if age < 65:
print("Work age")

Output:

Work age

Example 2:

score = 85
if score >= 70:
if score >= 90:
print("A")
else:
print("B")

Output:

B
Example 3:

money = 100
if money > 50:
if money > 80:
print("Buy toy")
else:
print("Buy candy")

Output:

Buy toy

Explanation:

Real life: If school, then if exam, then grade.


Tips: Don't nest too deep, use and.

Mini Summary: if in if.

Conditional User Inputs


Definition: Use input with if.

Why it is used: User choices.

Example 1:

ans = input("Rain? (y/n): ")


if ans == "y":
print("Stay home")
else:
print("Go park")

Output (y):

Rain? (y/n): y
Stay home

Example 2:

num = int(input("Number: "))


if num % 2 == 0:
print("Even")
else:
print("Odd")

Output (4):
Number: 4
Even

Example 3:

color = input("Favorite color? ")


if [Link]() == "blue":
print("Cool choice!")

Output:

Favorite color? blue


Cool choice!

Explanation:

Real life: Ask mood, suggest game.


Tips: .lower() for case ignore.

Mini Summary: if + input = interactive.

Match-Case Statement
Definition: Like switch, new in 3.10. Match value to cases.

Why it is used: Clean many ifs.

Syntax:

match var:
case 1:
...

Example 1:

day = "Monday"
match day:
case "Monday":
print("Start week")
case _:
print("Other day")

Output:

Start week

Example 2:
grade = 2
match grade:
case 1:
print("A")
case 2:
print("B")
case _:
print("C")

Output:

Example 3:

fruit = input("Fruit? ")


match fruit:
case "apple":
print("Red")
case "banana":
print("Yellow")
case _:
print("Unknown")

Output (banana):

Fruit? banana
Yellow

Explanation:

_ means any other.


Real life: Menu order.
Tips: Use _ for default.

Mini Summary: match for many options.

5. Loops

Python – Loops
Definition: Repeat code, like cycling.

Why it is used: Do same task many times.

(Details in sub)

Mini Summary: Loops save typing.


for Loops
Definition: Loop over items, like count fruits.

Syntax:

for item in sequence:


code

Example 1:

for i in range(3):
print(i)

Output:

0
1
2

Example 2:

fruits = ["apple", "banana"]


for f in fruits:
print(f)

Output:

apple
banana

Example 3:

for i in range(1, 4):


print(i * 2)

Output:

2
4
6

Explanation:

range(3): 0,1,2
Real life: Count fingers.
Tips: range(start, stop, step)

Mini Summary: for each item.

for-else Loops
Definition: else if no break.

Why it is used: Know if loop finished normal.

Example 1:

for i in range(3):
print(i)
else:
print("Done!")

Output:

0
1
2
Done!

Example 2:

found = False
for i in range(5):
if i == 3:
found = True
break
else:
print("Not found")

Output (no print else)

Example 3:

nums = [1,2]
for n in nums:
print(n)
else:
print("All good")

Output:

1
2
All good
Explanation:

Real life: Search bag, if not found say so.


Tips: Rare, for full loop check.

Mini Summary: else after full for.

while Loops
Definition: Loop while True.

Syntax:

while cond:
code

Example 1:

i = 0
while i < 3:
print(i)
i += 1

Output:

0
1
2

Example 2:

count = 1
while count <= 5:
print(count)
count += 2

Output:

1
3
5

Example 3:

guess = 0
while guess != 5:
guess = int(input("Guess: "))
Output: Loops till 5.

Explanation:

Real life: Wait till bus comes.


Tips / Common mistakes:

Mistake: Infinite loop, no i+=1. Fix: Change cond.


Mini Summary: while condition true.

break Statement
Definition: Stop loop early.

Why it is used: Exit when done.

Example 1:

for i in range(5):
if i == 3:
break
print(i)

Output:

0
1
2

Example 2:

while True:
ans = input("Quit? ")
if ans == "y":
break

Output: Stops on y.

Example 3:

for n in [1,2,3,4]:
if n == 2:
break
print(n)

Output:
1

Explanation:

Real life: Stop game if win.


Tips: Use with if.

Mini Summary: break to escape.

continue Statement
Definition: Skip rest, next loop.

Why it is used: Ignore some steps.

Example 1:

for i in range(5):
if i == 2:
continue
print(i)

Output:

0
1
3
4

Example 2:

i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)

Output:

1
2
4
5

Example 3:
for n in range(10):
if n % 2 == 0:
continue
print(n) # Odds

Output:

1
3
5
7
9

Explanation:

Real life: Skip veggies if hate.


Tips: After if.

Mini Summary: continue skips.

pass Statement
Definition: Do nothing, placeholder.

Why it is used: Empty block.

Example 1:

for i in range(3):
pass # Later add code

Output: Nothing

Example 2:

if True:
pass
else:
print("No")

Output: Nothing

Example 3:

class Empty:
pass

Explanation:
Real life: "Wait here" sign.
Tips: For future code.

Mini Summary: pass = nothing.

Nested Loops
Definition: Loop in loop.

Why it is used: Grids, tables.

Example 1:

for i in range(3):
for j in range(2):
print(i, j)

Output:

0 0
0 1
1 0
1 1
2 0
2 1

Example 2:

for row in range(3):


for col in range(3):
print("*", end=" ")
print() # New line

Output:

* * *
* * *
* * *

Example 3:

nums = [1,2]
for outer in nums:
for inner in nums:
print(outer * inner)

Output:
1
2
2
4

Explanation:

Real life: Rows and seats in class.


Tips: Watch speed, O(n^2).

Mini Summary: Loops inside loops.

6. Functions & Modules

Python - Functions
Definition: Named code block to reuse, like recipe.

Why it is used: No repeat code.

Syntax:

def name(params):
code
return value

Example 1:

def greet():
print("Hello!")

greet()

Output:

Hello!

Example 2:

def add(a, b):


return a + b

print(add(3, 4))

Output:
7

Example 3:

def multiply(x, y=2): # Default


return x * y

print(multiply(5))

Output:

10

Explanation:

Real life: Call chef for food.


Tips: return ends function.

Mini Summary: def for reuse.

Default Arguments
Definition: Params with = value if no input.

Why it is used: Optional inputs.

Example 1:

def welcome(name="Friend"):
print("Hi " + name)

welcome()
welcome("Ravi")

Output:

Hi Friend
Hi Ravi

Example 2:

def power(base, exp=2):


return base ** exp

print(power(3))
print(power(3, 3))
Output:

9
27

Example 3:

def info(name, age=12):


print(name, age)

info("Mia")

Output:

Mia 12

Explanation:

Real life: Coffee with sugar (default).


Tips: Defaults last.

Mini Summary: = for optionals.

Keyword Arguments
Definition: Call with name= value.

Why it is used: Order no matter.

Example 1:

def person(name, age):


print(name, age)

person(age=15, name="Kim")

Output:

Kim 15

Example 2:

def car(color, speed=100):


print(color, speed)

car(speed=120, color="red")
Output:

red 120

Example 3:

def greet(name, msg="Hi"):


print(msg + " " + name)

greet(name="Lee", msg="Bye")

Output:

Bye Lee

Explanation:

Real life: Order pizza toppings any order.


Tips: After positional.

Mini Summary: name=value flexible.

Keyword-Only Arguments
Definition: Params only by keyword, use *.

Why it is used: Force names.

Syntax: def f(*, a): ...

Example 1:

def func(*, name):


print(name)

func(name="A")
# func("A") error

Output:

Example 2:

def info(*, age, city):


print(age, city)
info(age=16, city="Surat")

Output:

16 Surat

Example 3:

def power(base, *, exp=2):


return base ** exp

print(power(2, exp=3))

Output:

Explanation:

Real life: Must say full address.


Tips: After *.

Mini Summary: * forces keywords.

Positional Arguments
Definition: Params by order.

Why it is used: Simple calls.

Example 1:

def add(a, b):


print(a + b)

add(3, 5)

Output:

Example 2:

def full_name(first, last):


print(first + " " + last)
full_name("Ana", "Lee")

Output:

Ana Lee

Example 3:

def calc(op, x, y):


if op == "+":
return x + y

print(calc("+", 1, 2))

Output:

Explanation:

Order matters.
Tips: Match def order.

Mini Summary: Order-based params.

Positional-Only Arguments
Definition: Params only by position, use /.

Why it is used: Hide names.

Syntax: def f(a, /, b):

Example 1:

def div(a, /, b):


return a / b

print(div(10, 2))
# div(a=10, b=2) error

Output:

5.0

Example 2:
def greet(g, /, msg="Hi"):
print(msg + " " + g)

greet("Bob")

Output:

Hi Bob

Example 3:

def power(base, /, exp):


return base ** exp

print(power(2, 3))

Output:

Explanation:

Real life: Fixed slots.


Tips: / before keywords.

Mini Summary: / for position only.

Arbitrary Arguments (*args, **kwargs)


Definition: *args for many pos, **kwargs for keywords.

Why it is used: Unknown number params.

Example 1 (*args):

def sum_all(*args):
total = 0
for n in args:
total += n
return total

print(sum_all(1,2,3))

Output:

6
Example 2 (**kwargs):

def print_info(**kwargs):
for key, value in [Link]():
print(key, value)

print_info(name="Zoe", age=14)

Output:

name Zoe
age 14

Example 3 (both):

def func(*args, **kwargs):


print(args)
print(kwargs)

func(1,2, name="Hi")

Output:

(1, 2)
{'name': 'Hi'}

Explanation:

*args tuple, ** dict.


Real life: Invite any friends.
Tips: args first.

Mini Summary: * ** for many.

Variable Scope (local/global)


Definition: local inside func, global outside.

Why it is used: Avoid name clash.

Example 1:

x = 10 # Global
def func():
x = 5 # Local
print(x)
func()
print(x)

Output:

5
10

Example 2:

global_x = 100
def change():
global global_x
global_x = 200

change()
print(global_x)

Output:

200

Example 3:

def outer():
y = 1
def inner():
nonlocal y
y = 2
inner()
print(y)
outer()

Output:

Explanation:

Real life: Home vs room toys.


Tips: global keyword careful.

Mini Summary: local safe, global shared.


Function Annotations
Definition: : type hints on params/return.

Why it is used: Show expected types.

Syntax: def f(a: int) -> str:

Example 1:

def add(a: int, b: int) -> int:


return a + b

print(add(2, 3))

Output:

Example 2:

def greet(name: str) -> None:


print("Hi " + name)

greet("Eve")

Output:

Hi Eve

Example 3:

def power(base: float, exp: float = 2) -> float:


return base ** exp

Explanation:

Not enforced, for help.


Real life: Label on boxes.
Tips: Use IDE for check.

Mini Summary: : for type hints.


Modules
Definition: File with code, import to use.

Why it is used: Share code.

Syntax: import math

Example 1:

import math
print([Link](16))

Output:

4.0

Example 2:

from math import pi


print(pi)

Output:

3.141592653589793

Example 3: Make [Link] with def hello(): print("Hi")

import mymodule
[Link]()

Output:

Hi

Explanation:

Real life: Borrow friend's tools.


Tips: pip install for more.

Mini Summary: import for extras.


Packing and Unpacking
Definition: * pack to tuple, unpack to vars.

Why it is used: Group/split data.

Example 1 (unpack):

nums = [1,2,3]
a, b, c = nums
print(a, b, c)

Output:

1 2 3

Example 2 (*pack):

def pack(*args):
print(args)

pack(1, "hi", True)

Output:

(1, 'hi', True)

Example 3 (dict unpack):

d = {"a":1, "b":2}
def func(**kwargs):
print(kwargs)

func(**d)

Output:

{'a': 1, 'b': 2}

Explanation:

Real life: Pack lunchbox, unpack eat.


Tips: Match count or *other.

Mini Summary: * for pack/unpack.


Built-in Functions
Definition: Ready functions like print, len.

Why it is used: Common tasks.

Example 1:

print(len("Hello"))

Output:

Example 2:

print(max(1,5,3))

Output:

Example 3:

print(round(3.7))

Output:

Explanation:

Real life: Ready calculator buttons.


Tips: dir(builtins) to list.

Mini Summary: Use built-ins first.

7. Strings

Python Strings
Definition: Text in ' ' or " ".

Why it is used: Words, names.

Syntax: s = "text"
Example 1:

s = "Python"
print(s)

Output:

Python

Example 2:

multi = """Line1
Line2"""
print(multi)

Output:

Line1
Line2

Example 3:

s = 'Hi "friend"'
print(s)

Output:

Hi "friend"

Explanation:

Real life: Notes.


Tips: Triple for multi-line.

Mini Summary: Strings for text.

String Slicing
Definition: Get part [start🔚step]

Why it is used: Extract pieces.

Example 1:

s = "Hello"
print(s[1:4])

Output:

ell

Example 2:

print(s[:3]) # From start

Output:

Hel

Example 3:

print(s[::2]) # Every second

Output:

Hlo

Explanation:

[start:end] end not include.


Real life: Cut cake slice.
Tips: Negative: s[-1] last.

Mini Summary: [ ] for parts.

Modify Strings
Definition: Make new strings (can't change old).

Why it is used: Update text.

Example 1:

s = "hello"
print([Link]())

Output:

HELLO
Example 2:

print([Link]("h", "H"))

Output:

Hello

Example 3:

s = " hi "
print([Link]().title())

Output:

Hi

Explanation:

Strings immutable: new copy.


Tips: Methods return new.

Mini Summary: Methods make new strings.

String Concatenation
Definition: Join with + or join().

Why it is used: Build text.

Example 1:

a = "Hi "
b = "Mom"
print(a + b)

Output:

Hi Mom

Example 2:

words = ["Python", "is", "fun"]


print(" ".join(words))
Output:

Python is fun

Example 3:

name = "Ria"
print("Age " + str(12))

Output:

Age 12

Explanation:

Real life: Glue words.


Tips: str() for numbers.

Mini Summary: + or join.

String Formatting
Definition: Put vars in text: f-strings, format().

Why it is used: Clean text build.

Example 1 (f-string):

name = "Sam"
print(f"Hello {name}")

Output:

Hello Sam

Example 2:

age = 14
print(f"You are {age} years old.")

Output:

You are 14 years old.

Example 3 (format):
print("Pi is {:.2f}".format(3.14159))

Output:

Pi is 3.14

Explanation:

f"" new easy way.


Tips: f best.

Mini Summary: f"{}" easy.

Escape Characters
Definition: \ for special like \n new line.

Why it is used: Add quotes, lines.

Example 1:

print("She said \"Hi\"")

Output:

She said "Hi"

Example 2:

print("Line1\nLine2")

Output:

Line1
Line2

Example 3:

print("\tTabbed")

Output:

Tabbed
Explanation:

Real life: \n like enter key.


Tips: \ for backslash.

Mini Summary: \ for specials.

String Methods
Definition: Functions for strings like .split().

Why it is used: Process text.

Example 1:

s = "hello world"
print([Link]())

Output:

['hello', 'world']

Example 2:

print([Link]("he"))

Output:

True

Example 3:

print([Link]("world"))

Output:

Explanation:

Real life: Cut, search words.


Tips: dir(str) for list.

Mini Summary: .method() power.


String Exercises
Practice:

1. Reverse "abc" → "cba" with [::-1]


2. Count "a" in "banana"
3. Uppercase first letter.
Mini Summary: Practice strings!

8. Lists

Python Lists
Definition: Ordered collection [1, "a", True], changeable.

Why it is used: Store many items.

Syntax: lst = [item1, item2]

Example 1:

fruits = ["apple", "banana"]


print(fruits)

Output:

['apple', 'banana']

Example 2:

nums = [1, 2, 3]
print(len(nums))

Output:

Example 3:

mixed = [1, "hi", 3.14]


print(mixed)

Output:

[1, 'hi', 3.14]


Explanation:

Real life: Shopping list.


Tips: Changeable.

Mini Summary: [] for lists.

Access List Items


Definition: lst[index]

Why it is used: Get specific.

Example 1:

colors = ["red", "green", "blue"]


print(colors[0])

Output:

red

Example 2:

print(colors[-1]) # Last

Output:

blue

Example 3:

print(colors[1:3])

Output:

['green', 'blue']

Explanation:

Index 0 first.
Tips: Out range error.

Mini Summary: first.


Change List Items
Definition: lst[index] = new

Why it is used: Update.

Example 1:

cars = ["ford", "toyota"]


cars[0] = "honda"
print(cars)

Output:

['honda', 'toyota']

Example 2:

cars[1] = "bmw"
print(cars)

Output:

['honda', 'bmw']

Example 3:

nums = [10, 20]


nums[0:2] = [100]
print(nums)

Output:

[100]

Explanation:

Real life: Cross buy, write new.


Tips: Slice replace many.

Mini Summary: = to change.


Add List Items
Definition: append(), insert(), extend()

Why it is used: Grow list.

Example 1:

shop = ["milk"]
[Link]("bread")
print(shop)

Output:

['milk', 'bread']

Example 2:

[Link](0, "egg")
print(shop)

Output:

['egg', 'milk', 'bread']

Example 3:

more = ["rice"]
[Link](more)
print(shop)

Output:

['egg', 'milk', 'bread', 'rice']

Explanation:

append end, insert pos.


Tips: + for new list.

Mini Summary: append grows.


Remove List Items
Definition: remove(), pop(), del

Why it is used: Clean list.

Example 1:

items = ["a", "b", "a"]


[Link]("a")
print(items)

Output:

['b', 'a']

Example 2:

[Link]() # Last
print(items)

Output:

['b']

Example 3:

del items[0]
print(items)

Output:

[]

Explanation:

remove value, pop index.


Tips: pop returns value.

Mini Summary: remove clean.


Loop Lists
Definition: for item in list

Why it is used: Do for each.

Example 1:

for fruit in ["apple", "banana"]:


print(fruit)

Output:

apple
banana

Example 2:

with index:
for i, val in enumerate(["a", "b"]):
print(i, val)

Output:

0 a
1 b

Example 3:

nums = [1,2,3]
total = 0
for n in nums:
total += n
print(total)

Output:

Explanation:

Real life: Read each book.


Tips: enumerate for index.

Mini Summary: for each.


List Comprehension
Definition: Short loop to make list.

Why it is used: One line lists.

Example 1:

squares = [x**2 for x in range(3)]


print(squares)

Output:

[0, 1, 4]

Example 2:

evens = [n for n in range(10) if n % 2 == 0]


print(evens)

Output:

[0, 2, 4, 6, 8]

Example 3:

words = ["hi", "cat"]


caps = [[Link]() for w in words]
print(caps)

Output:

['HI', 'CAT']

Explanation:

Real life: Quick shopping summary.


Tips: if for filter.

Mini Summary: [ ] fast lists.


Sort Lists
Definition: sort(), sorted()

Why it is used: Order items.

Example 1:

nums = [3,1,2]
[Link]()
print(nums)

Output:

[1, 2, 3]

Example 2:

words = ["zebra", "apple"]


print(sorted(words, reverse=True))

Output:

['zebra', 'apple']

Example 3:

[Link](reverse=True)
print(nums)

Output:

[3, 2, 1]

Explanation:

sort changes, sorted new.


Tips: Strings by alphabet.

Mini Summary: sort orders.


Copy Lists
Definition: copy(), [:], [Link]

Why it is used: Duplicate without change original.

Example 1:

orig = [1,2]
cpy = [Link]()
cpy[0] = 10
print(orig)

Output:

[1, 2]

Example 2:

cpy2 = orig[:]
print(cpy2)

Output:

[1, 2]

Example 3 (nested):

nest = [[1]]
shallow = nest[:]
shallow[0][0] = 2
print(nest) # Changes!

Output:

[[2]]

Explanation:

= is reference.
Tips: Use copy().

Mini Summary: copy new list.


Join Lists
Definition: + , extend(), * repeat

Why it is used: Combine.

Example 1:

a = [1,2]
b = [3]
print(a + b)

Output:

[1, 2, 3]

Example 2:

[Link](b)
print(a)

Output:

[1, 2, 3]

Example 3:

print([0] * 3)

Output:

[0, 0, 0]

Explanation:

Real life: Merge teams.


Tips: + new list.

Mini Summary: + joins.

List Methods
Definition: append, pop, index, count etc.

Example 1:
lst = [1,2,2]
print([Link](2))

Output:

Example 2:

print([Link](1))

Output:

Example 3:

[Link]()
print(lst)

Output:

[]

Explanation:

Real life: List tools.


Tips: Help(lst)

Mini Summary: .method handy.

List Exercises
1. Make → sum
2. ["a","b"] → reverse
3. Filter >5 from
Mini Summary: Practice lists!

9. Tuples
Python Tuples
Definition: Ordered, unchangeable (1,2,"a")

Why it is used: Safe lists, can't edit.

Syntax: t = (1,2)

Example 1:

point = (3, 4)
print(point)

Output:

(3, 4)

Example 2:

t = 1, 2, "hi" # No ()
print(t)

Output:

(1, 2, 'hi')

Example 3:

colors = ("red", "blue")


print(colors)

Output:

('red', 'blue')

Explanation:

Real life: Fixed address.


Tips: Single: (5,)

Mini Summary: () fixed.


Access Tuple Items
Definition: t[index]

Example 1:

t = (10, 20, 30)


print(t[1])

Output:

20

Example 2:

print(t[-1])

Output:

30

Example 3:

print(t[0:2])

Output:

(10, 20)

Explanation:

Like lists.
Tips: No change.

Mini Summary: [ ] same as list.

Update Tuples
Definition: Can't change, make new.

Why it is used: Protect data.

Example 1:

t = (1,2)
t = t + (3,)
print(t)

Output:

(1, 2, 3)

Example 2:

lst = list(t)
lst[0] = 10
t = tuple(lst)
print(t)

Output:

(10, 2, 3)

Example 3:

# t[0] = 5 error!

Explanation:

Real life: Locked box.


Tips: Convert to list if need change.

Mini Summary: New tuple to update.

Unpack Tuples
Definition: a,b = t

Example 1:

t = (5, 10)
x, y = t
print(x, y)

Output:

5 10

Example 2:

r, g, b = (255, 0, 0)
print(r)

Output:

255

Example 3:

nums = (1,2,3,4)
*front, last = nums
print(front, last)

Output:

[1, 2, 3] 4

Explanation:

Real life: Share candies.


Tips: Match length.

Mini Summary: Unpack to vars.

Loop Tuples
Definition: for in tuple

Example 1:

for item in ("a", "b"):


print(item)

Output:

a
b

Example 2:

t = (1,2)
for i, v in enumerate(t):
print(i, v)

Output:
0 1
1 2

Example 3:

total = sum((1,2,3))
print(total)

Output:

Explanation:

Fast like list.


Tips: Same as list.

Mini Summary: Loop easy.

Join Tuples
Definition: + , tuple(range())

Example 1:

t1 = (1,2)
t2 = (3,)
t3 = t1 + t2
print(t3)

Output:

(1, 2, 3)

Example 2:

print((0,0) * 2)

Output:

(0, 0, 0, 0)

Example 3:
empty = ()
print(empty + (5,))

Output:

(5,)

Explanation:

Real life: Chain links.


Tips: New tuple.

Mini Summary: + joins.

Tuple Methods
Definition: Few: count, index

Example 1:

t = (1,2,2)
print([Link](2))

Output:

Example 2:

print([Link](1))

Output:

Example 3:

print(len(t))

Output:

Explanation:
Light methods.
Tips: Use built-ins.

Mini Summary: count, index only.

Namedtuple
Definition: Tuple with names, from collections.

Why it is used: Readable.

Example 1:

from collections import namedtuple


Point = namedtuple("Point", "x y")
p = Point(1, 2)
print(p.x)

Output:

Example 2:

Person = namedtuple("Person", ["name", "age"])


p = Person("Ana", 12)
print(p)

Output:

Person(name='Ana', age=12)

Example 3:

print([Link])

Output:

Ana

Explanation:

Real life: ID card.


Tips: Like class light.

Mini Summary: namedtuple named.


Tuple Exercises
1. (1,2,3) unpack
2. Join two tuples
3. Count in (a,a,b)
Mini Summary: Practice safe tuples!

10. Sets

Python Sets
Definition: Unordered unique {1,2,"a"}, no duplicates.

Why it is used: Unique items, fast check.

Syntax: s = {1,2}

Example 1:

fruits = {"apple", "banana", "apple"}


print(fruits)

Output:

{'banana', 'apple'}

Example 2:

empty = set()
print(empty)

Output:

set()

Example 3:

nums = set([1,2,2])
print(nums)

Output:

{1, 2}

Explanation:
Real life: Unique friends list.
Tips: No index.

Mini Summary: {} unique.

Access Set Items


Definition: No index, loop or 'in'.

Example 1:

s = {1,2,3}
print(2 in s)

Output:

True

Example 2:

print(len(s))

Output:

Example 3:
for x in s:
print(x)

**Output** (order random):

1
2
3

**Explanation**:
- Unordered.

**Tips**: Use in check.

**Mini Summary**: in for check.

### Add Set Items


**Definition**: add(), update()
**Example 1**:
```python
s = {"a"}
[Link]("b")
print(s)

Output:

{'a', 'b'}

Example 2:

[Link](["c", "a"])
print(s)

Output:

{'c', 'b', 'a'}

Example 3:

s |= {"d"} # Union
print(s)

Output:

{'a', 'b', 'c', 'd'}

Explanation:

No dups.
Tips: update many.

Mini Summary: add one, update many.

Remove Set Items


Definition: remove(), discard(), pop(), clear()

Example 1:

s = {"a", "b"}
[Link]("a")
print(s)

Output:
{'b'}

Example 2:

[Link]("x") # No error if not

Example 3:

[Link]() # Random
[Link]()
print(s)

Output:

set()

Explanation:

remove error if not.


Tips: discard safe.

Mini Summary: discard safe remove.

Loop Sets
Definition: for item in set

Example 1:

for fruit in {"apple", "banana"}:


print(fruit)

Output (random order):

apple
banana

Example 2:

s = {1,2,3}
for n in sorted(s):
print(n)

Output:
1
2
3

Example 3:

print(sum(s))

Output:

Explanation:

Order not fixed.


Tips: sorted() for order.

Mini Summary: for each unique.

Join Sets
Definition: union |, intersection &, difference -

Example 1:

a = {1,2}
b = {2,3}
print(a | b)

Output:

{1, 2, 3}

Example 2:

print(a & b)

Output:

{2}

Example 3:

print(a - b)
Output:

{1}

Explanation:

Real life: Common friends.


Tips: | new set.

Mini Summary: Set math.

Copy Sets
Definition: copy(), = new

Example 1:

s = {1,2}
cs = [Link]()
[Link](3)
print(s)

Output:

{1, 2}

Example 2:

cs2 = set(s)
print(cs2)

Output:

{1, 2}

Example 3:

# s2 = s # Same!

Explanation:

Like lists.
Tips: copy().

Mini Summary: copy duplicate.


Set Operators
Definition: Same as join: | & - ^ etc.

Example 1:

print({1,2} ^ {2,3}) # Symmetric diff

Output:

{1, 3}

Example 2:

a <= b # Subset

Example 3:

[Link](b)

Explanation:

Set power.
Tips: Read docs.

Mini Summary: Operators fast.

Set Methods
Definition: add, union, intersection etc.

Example 1:

s = {1,2}
s1 = {3}
print([Link](s1))

Output:

{1, 2, 3}

Example 2:

print([Link]({2}))
Output:

{2}

Example 3:

s.difference_update({1})
print(s)

Output:

{2}

Explanation:

Methods like ops.


Tips: _update changes self.

Mini Summary: Methods do set ops.

Set Exercises
1. {1,2,2} → unique
2. Common in two sets
3. Add/remove
Mini Summary: Sets for unique!

11. Dictionaries

Python Dictionaries
Definition: Key-value {key: value}, like phone book.

Why it is used: Fast lookup by name.

Syntax: d = {"name": "Ana"}

Example 1:

person = {"name": "Bob", "age": 12}


print(person)

Output:

{'name': 'Bob', 'age': 12}


Example 2:

empty = {}
print(type(empty))

Output:

<class 'dict'>

Example 3:

d = dict(name="Eve", age=14)
print(d)

Output:

{'name': 'Eve', 'age': 14}

Explanation:

Keys unique.
Tips: Keys hashable (str,int,tuple)

Mini Summary: {} key:value.

Access Dictionary Items


Definition: d[key], [Link](key)

Example 1:

print(person["name"])

Output:

Bob

Example 2:

print([Link]("age", "No"))

Output:

12
Example 3:

print([Link]())

Output:

dict_keys(['name', 'age'])

Explanation:

get no error.
Tips: get safe.

Mini Summary: [key] or get.

Change Dictionary Items


Definition: d[key] = new

Example 1:

person["age"] = 13
print(person)

Output:

{'name': 'Bob', 'age': 13}

Example 2:

person["city"] = "Surat"
print(person)

Output:

{'name': 'Bob', 'age': 13, 'city': 'Surat'}

Example 3:

[Link]({"age": 14})

**Output changes age.

Explanation:
Add if new key.
Tips: update many.

Mini Summary: = updates/adds.

Add Dictionary Items


Definition: Same as change.

Example 1:

d = {"a":1}
d["b"] = 2
print(d)

Output:

{'a': 1, 'b': 2}

Example 2:

[Link](a=10, c=3)
print(d)

Output:

{'a': 10, 'b': 2, 'c': 3}

Example 3:

d["list"] =

Explanation:

Any value.
Tips: Keys unique.

Mini Summary: New key adds.

Remove Dictionary Items


Definition: pop(), del, clear()

Example 1:
d = {"x":1, "y":2}
[Link]("x")
print(d)

Output:

{'y': 2}

Example 2:

del d["y"]
print(d)

Output:

{}

Example 3:

[Link]()

Explanation:

pop returns value.


Tips: pop safe.

Mini Summary: pop removes.

Dictionary View Objects


Definition: keys(), values(), items() views.

Why it is used: Live views.

Example 1:

d = {"a":1, "b":2}
print([Link]())

Output:

dict_keys(['a', 'b'])

Example 2:
print(list([Link]()))

Output:

Example 3:

for k, v in [Link]():
print(k, v)

Output:

a 1
b 2

Explanation:

Dynamic.
Tips: To list if need copy.

Mini Summary: Views of content.

Loop Dictionaries
Definition: for key in d, or items()

Example 1:

for key in d:
print(key)

Output:

a
b

Example 2:

for k, v in [Link]():
print(k + ":" + str(v))

Output:
a:1
b:2

Example 3:

for v in [Link]():
print(v)

Output:

1
2

Explanation:

Real life: Read phone book.


Tips: items() pairs.

Mini Summary: Loop keys/values.

Copy Dictionaries
Definition: copy(), dict()

Example 1:

orig = {"a":1}
cpy = [Link]()
cpy["b"] = 2
print(orig)

Output:

{'a': 1}

Example 2:

cpy2 = dict(orig)

Example 3:

import copy
deep = [Link]({"list": })

Explanation:
Shallow ok for simple.
Tips: deepcopy nested.

Mini Summary: copy new dict.

Nested Dictionaries
Definition: Dict in dict.

Why it is used: Complex data.

Example 1:

family = {
"mom": {"name": "Lia", "age": 40},
"kid": {"name": "Tim", "age": 10}
}
print(family["mom"]["name"])

Output:

Lia

Example 2:

print(family["kid"]["age"])

Output:

10

Example 3:

for role, info in [Link]():


print(role, info["name"])

Output:

mom Lia
kid Tim

Explanation:

Real life: Family tree.


Tips: Check keys.
Mini Summary: Dict of dicts.

Dictionary Methods
Definition: get, setdefault, fromkeys etc.

Example 1:

d = {"a":1}
print([Link]("b", 2))
print(d)

Output:

2
{'a': 1, 'b': 2}

Example 2:

keys = ["x","y"]
d2 = [Link](keys, 0)
print(d2)

Output:

{'x': 0, 'y': 0}

Example 3:

print([Link]()) # Last

Output:

('b', 2)

Explanation:

setdefault add if not.


Tips: Handy shortcuts.

Mini Summary: Methods smart.


Dictionary Exercises
1. {"a":1} add "b":2
2. Loop print keys:values
3. Nested access
Mini Summary: Dicts for lookups!

These notes are ready for class! Practice all examples on your computer. Python makes coding
fun like playing.

Would you like exercises for a specific topic or more advanced notes?

You might also like