Python Learning Notes For Beginners
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.
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:
Python – History
Definition: Python started in 1991 by Guido van Rossum. Named after a funny TV show.
Tips / Common mistakes: Tip: Guido made it for easy reading, like a book.
Python – Features
Definition: Python has easy rules, free to use, works on all computers.
# Simple addition
a = 5
b = 3
print(a + b)
Output:
Output:
0
1
2
Output:
Explanation:
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.
Syntax:
print("Hello, World!")
Example 1:
print("Hello, World!")
Output:
Hello, World!
Example 2:
print("Hello, India!")
Output:
Hello, India!
Example 3:
Output:
Hello, Surat!
Explanation:
No code examples.
Python – Interpreter
Definition: Interpreter reads Python code line by line, like a teacher explaining book.
Example 1: In terminal:
python -c "print('Hi')"
Output:
Hi
Output:
Explanation:
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!
Syntax:
Explanation:
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:
Python – Variables
Definition: Box to store data, like a name tag on a bag.
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:
Syntax: self.__secret = 10
class Box:
def __init__(self):
self.__age = 12 # Private
def show(self):
print(self.__age)
b = Box()
[Link]()
Output:
12
Example 2:
def func():
_private = "secret"
print(_private)
func()
Output:
secret
Explanation:
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:
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:
Example 1:
print("नमस्ते") # Hindi
Output:
नमस्ते
Example 2:
print("😊 Python")
Output:
😊 Python
Example 3:
name = "कस्तूरी"
print("Hi " + name)
Output:
Hi कस्तूरी
Explanation:
Python – Literals
Definition: Fixed values in code, like 5 or "hi".
Example 1:
Output:
42
Example 2:
Output:
Python
Example 3:
Output:
3.14
Explanation:
Python – Operators
Definition: Symbols to do work on data, like + for add.
Example 1:
a = 10 + 5
print(a)
Output:
15
Example 2:
Output:
True
Example 3:
Output:
True
Explanation:
Syntax: a + b
Example 1:
print(10 + 5)
Output:
15
Example 2:
Output:
3.3333333333333335
Example 3:
print(2 ** 3) # Power
Output:
Explanation:
Example 1:
print(5 == 5)
Output:
True
Example 2:
print(10 > 7)
Output:
True
Example 3:
Output:
True
Explanation:
Assignment Operators
Definition: = += -= etc to give values.
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:
Logical Operators
Definition: and or not for True/False mix.
Example 1:
False
Example 2:
age = 18
print(age > 16 and age < 65)
Output:
True
Example 3:
print(not True)
Output:
False
Explanation:
Bitwise Operators
Definition: & | ^ ~ << >> for binary bits.
Example 1:
Output:
Example 2:
print(5 | 3) # 101 | 011 = 111
Output:
Example 3:
Output:
10
Explanation:
Membership Operators
Definition: in not in to check if item inside.
Example 1:
print("a" in "cat")
Output:
True
Example 2:
nums = [1,2,3]
print(2 in nums)
Output:
True
Example 3:
Output:
True
Explanation:
Identity Operators
Definition: is is not to check same object.
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:
Walrus Operator
Definition: := assign and use in one, new in Python 3.8.
Example 1:
if (n := 10) > 5:
print(n)
Output:
10
Example 2:
print(x := "Hi")
Output:
Hi
Example 3:
Output:
1
2
Explanation:
Real life: Measure and check height same time.
Tips: Use in loops.
Operator Precedence
Definition: Order of operators, like () first, then **, then + -.
Example 1:
print(2 + 3 * 4) # * first
Output:
14
Example 2:
print((2 + 3) * 4) # () first
Output:
20
Example 3:
Output:
6.0
Explanation:
Python – Comments
Definition: # lines ignored by computer, for notes.
Example 1:
Output:
Example 2:
Output:
Ana
Example 3:
"""
Multi-line
comment
"""
print("Code runs")
Output:
Code runs
Explanation:
Example 1:
Example 2:
Age? 12
Next year: 13
Example 3:
Num1: 3.5
Num2: 2.5
6.0
Explanation:
Python – Numbers
Definition: int (whole) and float (decimal) numbers.
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:
Example 1:
print(True)
Output:
True
Example 2:
is_adult = 18 > 16
print(is_adult)
Output:
True
Example 3:
Output:
False
Explanation:
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:
(Examples in subtopics)
(Details below)
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:
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:
Nested If
Definition: if inside if.
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:
Example 1:
Output (y):
Rain? (y/n): y
Stay home
Example 2:
Output (4):
Number: 4
Even
Example 3:
Output:
Explanation:
Match-Case Statement
Definition: Like switch, new in 3.10. Match value to cases.
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:
Output (banana):
Fruit? banana
Yellow
Explanation:
5. Loops
Python – Loops
Definition: Repeat code, like cycling.
(Details in sub)
Syntax:
Example 1:
for i in range(3):
print(i)
Output:
0
1
2
Example 2:
Output:
apple
banana
Example 3:
Output:
2
4
6
Explanation:
range(3): 0,1,2
Real life: Count fingers.
Tips: range(start, stop, step)
for-else Loops
Definition: else if no break.
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")
Example 3:
nums = [1,2]
for n in nums:
print(n)
else:
print("All good")
Output:
1
2
All good
Explanation:
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:
break Statement
Definition: Stop loop early.
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:
continue Statement
Definition: Skip rest, next loop.
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:
pass Statement
Definition: Do nothing, placeholder.
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.
Nested Loops
Definition: Loop in loop.
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:
Output:
* * *
* * *
* * *
Example 3:
nums = [1,2]
for outer in nums:
for inner in nums:
print(outer * inner)
Output:
1
2
2
4
Explanation:
Python - Functions
Definition: Named code block to reuse, like recipe.
Syntax:
def name(params):
code
return value
Example 1:
def greet():
print("Hello!")
greet()
Output:
Hello!
Example 2:
print(add(3, 4))
Output:
7
Example 3:
print(multiply(5))
Output:
10
Explanation:
Default Arguments
Definition: Params with = value if no input.
Example 1:
def welcome(name="Friend"):
print("Hi " + name)
welcome()
welcome("Ravi")
Output:
Hi Friend
Hi Ravi
Example 2:
print(power(3))
print(power(3, 3))
Output:
9
27
Example 3:
info("Mia")
Output:
Mia 12
Explanation:
Keyword Arguments
Definition: Call with name= value.
Example 1:
person(age=15, name="Kim")
Output:
Kim 15
Example 2:
car(speed=120, color="red")
Output:
red 120
Example 3:
greet(name="Lee", msg="Bye")
Output:
Bye Lee
Explanation:
Keyword-Only Arguments
Definition: Params only by keyword, use *.
Example 1:
func(name="A")
# func("A") error
Output:
Example 2:
Output:
16 Surat
Example 3:
print(power(2, exp=3))
Output:
Explanation:
Positional Arguments
Definition: Params by order.
Example 1:
add(3, 5)
Output:
Example 2:
Output:
Ana Lee
Example 3:
print(calc("+", 1, 2))
Output:
Explanation:
Order matters.
Tips: Match def order.
Positional-Only Arguments
Definition: Params only by position, use /.
Example 1:
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:
print(power(2, 3))
Output:
Explanation:
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):
func(1,2, name="Hi")
Output:
(1, 2)
{'name': 'Hi'}
Explanation:
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:
Example 1:
print(add(2, 3))
Output:
Example 2:
greet("Eve")
Output:
Hi Eve
Example 3:
Explanation:
Example 1:
import math
print([Link](16))
Output:
4.0
Example 2:
Output:
3.141592653589793
import mymodule
[Link]()
Output:
Hi
Explanation:
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)
Output:
d = {"a":1, "b":2}
def func(**kwargs):
print(kwargs)
func(**d)
Output:
{'a': 1, 'b': 2}
Explanation:
Example 1:
print(len("Hello"))
Output:
Example 2:
print(max(1,5,3))
Output:
Example 3:
print(round(3.7))
Output:
Explanation:
7. Strings
Python Strings
Definition: Text in ' ' or " ".
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:
String Slicing
Definition: Get part [start🔚step]
Example 1:
s = "Hello"
print(s[1:4])
Output:
ell
Example 2:
Output:
Hel
Example 3:
Output:
Hlo
Explanation:
Modify Strings
Definition: Make new strings (can't change old).
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:
String Concatenation
Definition: Join with + or join().
Example 1:
a = "Hi "
b = "Mom"
print(a + b)
Output:
Hi Mom
Example 2:
Python is fun
Example 3:
name = "Ria"
print("Age " + str(12))
Output:
Age 12
Explanation:
String Formatting
Definition: Put vars in text: f-strings, format().
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:
Example 3 (format):
print("Pi is {:.2f}".format(3.14159))
Output:
Pi is 3.14
Explanation:
Escape Characters
Definition: \ for special like \n new line.
Example 1:
Output:
Example 2:
print("Line1\nLine2")
Output:
Line1
Line2
Example 3:
print("\tTabbed")
Output:
Tabbed
Explanation:
String Methods
Definition: Functions for strings like .split().
Example 1:
s = "hello world"
print([Link]())
Output:
['hello', 'world']
Example 2:
print([Link]("he"))
Output:
True
Example 3:
print([Link]("world"))
Output:
Explanation:
8. Lists
Python Lists
Definition: Ordered collection [1, "a", True], changeable.
Example 1:
Output:
['apple', 'banana']
Example 2:
nums = [1, 2, 3]
print(len(nums))
Output:
Example 3:
Output:
Example 1:
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.
Example 1:
Output:
['honda', 'toyota']
Example 2:
cars[1] = "bmw"
print(cars)
Output:
['honda', 'bmw']
Example 3:
Output:
[100]
Explanation:
Example 1:
shop = ["milk"]
[Link]("bread")
print(shop)
Output:
['milk', 'bread']
Example 2:
[Link](0, "egg")
print(shop)
Output:
Example 3:
more = ["rice"]
[Link](more)
print(shop)
Output:
Explanation:
Example 1:
Output:
['b', 'a']
Example 2:
[Link]() # Last
print(items)
Output:
['b']
Example 3:
del items[0]
print(items)
Output:
[]
Explanation:
Example 1:
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:
Example 1:
Output:
[0, 1, 4]
Example 2:
Output:
[0, 2, 4, 6, 8]
Example 3:
Output:
['HI', 'CAT']
Explanation:
Example 1:
nums = [3,1,2]
[Link]()
print(nums)
Output:
[1, 2, 3]
Example 2:
Output:
['zebra', 'apple']
Example 3:
[Link](reverse=True)
print(nums)
Output:
[3, 2, 1]
Explanation:
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().
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:
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:
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")
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:
Output:
('red', 'blue')
Explanation:
Example 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.
Update Tuples
Definition: Can't change, make new.
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:
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:
Loop Tuples
Definition: for in tuple
Example 1:
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:
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:
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.
Namedtuple
Definition: Tuple with names, from collections.
Example 1:
Output:
Example 2:
Output:
Person(name='Ana', age=12)
Example 3:
print([Link])
Output:
Ana
Explanation:
10. Sets
Python Sets
Definition: Unordered unique {1,2,"a"}, no duplicates.
Syntax: s = {1,2}
Example 1:
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.
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)
1
2
3
**Explanation**:
- Unordered.
Output:
{'a', 'b'}
Example 2:
[Link](["c", "a"])
print(s)
Output:
Example 3:
s |= {"d"} # Union
print(s)
Output:
Explanation:
No dups.
Tips: update many.
Example 1:
s = {"a", "b"}
[Link]("a")
print(s)
Output:
{'b'}
Example 2:
Example 3:
[Link]() # Random
[Link]()
print(s)
Output:
set()
Explanation:
Loop Sets
Definition: for item in set
Example 1:
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:
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:
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().
Example 1:
Output:
{1, 3}
Example 2:
a <= b # Subset
Example 3:
[Link](b)
Explanation:
Set power.
Tips: Read docs.
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:
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.
Example 1:
Output:
empty = {}
print(type(empty))
Output:
<class 'dict'>
Example 3:
d = dict(name="Eve", age=14)
print(d)
Output:
Explanation:
Keys unique.
Tips: Keys hashable (str,int,tuple)
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.
Example 1:
person["age"] = 13
print(person)
Output:
Example 2:
person["city"] = "Surat"
print(person)
Output:
Example 3:
[Link]({"age": 14})
Explanation:
Add if new key.
Tips: update many.
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:
Example 3:
d["list"] =
Explanation:
Any value.
Tips: Keys unique.
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:
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.
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:
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.
Nested Dictionaries
Definition: Dict in dict.
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:
Output:
mom Lia
kid Tim
Explanation:
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:
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?