[go: up one dir, main page]

0% found this document useful (0 votes)
6 views26 pages

Remaining Note

The document provides an overview of various Python programming concepts including f-strings for string formatting, docstrings for documentation, PEPs for coding standards, recursion, Fibonacci numbers, sets, dictionaries, and error handling techniques. It explains the differences between docstrings and comments, illustrates the use of recursion in functions, and demonstrates set operations and dictionary methods. Additionally, it covers control flow with if-else statements and error handling using try-except blocks, including the use of the finally keyword.

Uploaded by

manu.bscs
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)
6 views26 pages

Remaining Note

The document provides an overview of various Python programming concepts including f-strings for string formatting, docstrings for documentation, PEPs for coding standards, recursion, Fibonacci numbers, sets, dictionaries, and error handling techniques. It explains the differences between docstrings and comments, illustrates the use of recursion in functions, and demonstrates set operations and dictionary methods. Additionally, it covers control flow with if-else statements and error handling using try-except blocks, including the use of the finally keyword.

Uploaded by

manu.bscs
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
You are on page 1/ 26

🌀F STRINGS

⭐Powerful way to create strings that include the values of variables or expressions.
⚡Eg-
-(without f-string) #method 1

letter = "Respected sir, My self {} and I am studying in {} in your college {} and I want leave for
{}.Thankyou"
name ="Manu M"
class = " class 1st year AIML"
college = "SMMV"
days = "2 Days "
print(letter.format(name,class,college,days))

⚡Eg-
-(without f-string) #method 2

letter = "Hey my name is {1} and I am from {0}"


country ="India"
name="Manu"
print(letter.format(country,name))

⚡Eg-
-(using f-string)

name = "Manu"
country = "India"
print(f"Hey my name is {name} and I am from {country}")

⚡Eg-
print(f"Hi this is the answer{2*30}")

🍁Rounding off
⚡Eg-
-(without f-string)

txt="For only {price:.2f} dollars!!" 📌it tells python to take only 2 decimal point
print(txt.format(price=49.0999))

⚡Eg-
-(with f-string)

price=49.099999
txt=f"for only {price:.2f} dollars!"
print(txt)

🍁-To show actual sentence


⚡Eg-
print(f"we use f string like this: Hey my name is {{name}} and I am from {{country}}")

🌀DOCSTRING
⭐Taking a notes for our code
⭐Python Docstrings are the string iterables that appear right after the definition of a
function,method,class or module.

➖ The exact difference between Multiline Commenting and DocString


✅ Docstring
Python will read it and remember and tells when someone asks about it
Stored in memory → func.__doc__
Used in professional tools (IDEs, help(), Sphinx docs)
Always the first line inside a function/class/module
Purpose: Explain code officially

❌ Multiline comment (with triple quotes)


Not stored in memory
Not used by any tool
Can be placed anywhere
Just ignored by Python if not assigned
Purpose: Disable or explain code temporarily

🔥 Final truth:
They look the same ("""...""") but Python handles them differently.
Think of it like:
Docstring = ID proof
Comment = Casual note
Both can look alike, but only docstring is recognized officially.

⚡Eg-
def square(n):
""" Takes in a number n, returns the square of n"""
print(n**2)
square(5)

🍁To put docstring in output


Use - function.__doc__

⚡Eg-
print(square._ _ doc _ _)

🌀PEPs ( Python Enhancement Proposal)


⭐this is mostly for Developers
Official style guide for python code.It tells How to write clean, readable , and consistent code -
just like proper grammar for English.

🌀THE ZEN
📌
OF PYTHON
import this gives a poem in output

🌀RECURSION IN PYTHON
⭐It means a function calling itself to solve smaller parts of a problem.
💥Note:
▫️factorial(7) = 7*6*5*4*3*2*1
▫️factorial(0) = 1
▫️factorial(n) = n*factorial(n-1)

⚡Eg-
def factorial(n):📌 calling a function
if (n==0 or n==1):
return 1

📌
else:
return n*factorial(n-1) recursive step(The function calls itself with n-1, and
Multiplies it by n-1)
print(factorial(3))
How it works-
factorial(5)

📌
= 5 * factorial(4) #now call function for 4 and so on
= 5 * 4 * factorial(3) now for 3
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
=5*4*3*2*1
= 120

💥Note-
If we don’t write n-1, Python keeps calling the function with the same value again and again,
leading to infinite recursion. Python thinks: “I need the answer, so I’ll call the same function
again until I get it.” This is like iteration—Python keeps scanning repeatedly.

But when we write n-1, Python reduces the value step by step (5 → 4 → 3 → 2 → 1). Each time
the function is called, the number gets smaller. Python stores each call like layers. When the
smallest value is reached (base case), Python starts solving from bottom to top, multiplying
each number and finally giving the correct answer.

It’s like climbing down stairs till 1, then climbing back up multiplying.

🍁FIBONACCI NUMBERS
⭐ adding the last 2 digit to get next digit
⭐How it works:
▫️ 0,1,1,2,3,5,8,13...........

Starts with 0 and 1


next is: 0 +1 =1
next is : 1+1=2
So on......

f0 =0
f1 = 1
f2 = f0 +f1
f(n) = f(n-1) + f(n-2)

def fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
else:

📌
return fibonacci(n-1) + fibonacci(n-2)
n=6 asking python to generate first 6 fibonacci numbers
fibinlist =[]
for i in range(n):
fibinlist.append(fibonacci(i))
print(fibinlist)

✅How python thinks recursively;


f(5)
├─ f(4)
│ ├─ f(3)
│ │ ├─ f(2)
│ │ │ ├─ f(1) → 1
│ │ │ └─ f(0) → 0
│ │ └─ f(1) → 1
│ └─ f(2)
│ ├─ f(1) → 1
│ └─ f(0) → 0
└─ f(3)
├─ f(2)
│ ├─ f(1) → 1
│ └─ f(0) → 0
└─ f(1) → 1

✅Step-by-step:
i=0
→ fibonacci(0) → returns 0#ac to function
→ List becomes [0]

i=1
→ fibonacci(1) → returns 1#again ac to function
→ List becomes [0, 1]

i=2
→ fibonacci(2)
→ = fibonacci(1) + fibonacci(0)#ac to function
→=1+0=1
→ List becomes [0, 1, 1]

i=3
→ fibonacci(3)
→ = fibonacci(2) + fibonacci(1)#now it again calculates the value for fibonacci 2 as previous
→=1+1=2
→ List becomes [0, 1, 1, 2]

i=4
→ fibonacci(4)
→ = fibonacci(3) + fibonacci(2)#same, once it enters fib4 it gives fib 3 and 2 and again it will
calculate ac to function
→=2+1=3
→ List becomes [0, 1, 1, 2, 3]

🌀SETS #advanced

📌 class dict
s={}
print(type(s))

📌class set
s= set()
print(type(s))

s1={1,2,3}

📌
s2={4,5,6}
print(s1.union(s2)) no changes in s1 and return new set by combing both set

📌
print(s1,s2)
s1.update(s2) make changes in s1, here new set is not formed instead s1 updates with s2

📌
print(s1,s2)

📌
print(s1.intersection(s2)) gives common from both set but no changes in sets

📌
print(s1.intersection_update(s2)) same function but now it changes the set 1

📌
print(s2.symmetric_difference(s1)) removes common from both set
print(s1.difference(s2)) only prints s1 but removes any character which is present in s2

📌
(s1-s2)
print(s1.isdisjoint(s2)) tell whether any common exists between the sets

🍁issubset()
⭐Checks if all elements of set A are present inside set B.
"""

It asks:


> “Am I fully inside the other set?”
Example:
A = {1, 2}
B = {1, 2, 3}
print(A.issubset(B)) 📌asking whether A is fully inside B # True ✅
"""

🍁 issuperset()
⭐Checks if all elements of set B are present inside set A.
"""

It asks:


> “Do I fully contain the other set?”
Example:
A = {1, 2, 3}

📌 ✅
B = {1, 2}
print(A.issuperset(B)) A asking do i fully contain B # True

🔥 Exact Difference:
Method​ Who is asking?​ Question asked
issubset()​ Smaller set​ "Am I inside that bigger set?"
issuperset()​ Bigger set​ "Do I fully contain that smaller set?"

Both return True or False.


They don't modify the sets.
"""

🍁Adding extra elements


1)By add method

📌
s1={1,2,3}
s1.add(4) we can only add only 1 element
print(s1)

2)By update method

👉 Updating with another set


s1 = {1, 2, 3}

📌
s1.update({4, 5})
print(s1) {1, 2, 3, 4, 5}

👉 Updating with a list


print(s1) 📌{1, 2, 3, 4, 5, 6, 7}
s1.update([6, 7])

👉Updating with a string


s1.update("AB")
print(s1) 📌 {1, 2, 3, 4, 5, 6, 7, 'A', 'B'}
🍁Remove
⚡Eg-
s1={1,2,3}
s1.remove(2)
print(s1)

⚡Eg-
s1={1,2,3}

📌
s1.remove(9)
print(s1) gives error

🍁Same with Discard(but it does not give any error)


⚡Eg-
s1={1,2,3}

📌
s1.discard(5)
print(s1) does not give error

🍁Popping the random element


s1={1,2,3}
s1.pop()
print(s1)

🍁Deleting the whole set


num={1,2,3}

📌
del num
print(num) gives error because it is already deleted

🍁Clearing the Set


num={1,2,3,4}

📌
num.clear()
print(num) gives the empty set
🍁If Else
info = {'carla',19,False,5.9}
if 'carla' in info:
print('carla is present')
else:
print('carla is absent')

🌀DICTIONARIES
dic={"Harry":"human being",
"Spoon":"object"}

📌
print(dic["Harry"])
Here Harry and Spoon are the keys and human being and object are values

⚡Eg-
dic = {
344:'harry',
56:'shubham',
45:'zakir',
67:'neha'}
print(dic)

📌
print(dic[344])
print(dic.get(344)) this line do not give error in case if particular element does not present in
dict instead it will give None
print(dic.keys())
print(dic.values())

📌
for keys in dic.keys():
print(dic[keys]) dic[keys] always gives values

📌
for key in dic.keys():
print(key) prints keys
for key,value in dic.items():
print(key,value)
for keys in dic.keys():
print(f"The value corresponding to key {keys} is {dic[keys]}")
OR
for keys,values in info.items():
print(f"The value corresponding to the key{keys} is {values}")
🍁Updating
ep1 ={122:45,123:89,576:69}
ep2={22:45,566:65}
ep1.update(ep2)
print(ep1)

🍁Clearing
📌gives empty output
ep1.clear()
print(ep1)

🍁Popping
📌
ep1.pop(Any key) must pass at least 1 argument

📌
print(ep1)
To pop last item
ep1.popitem()
print(ep1)

🍁Deleting
📌 gives error
del ep1
print(ep1)

del ep1[particular key]


print(ep1)

💥Note-
Search python dictionary documentation in Google for latest update

🌀ELSE IN LOOP
⚡Eg-
for i in range(5):
print(i)
else:
print("sorry no i")
⚡Eg-
for i in range []:
print(i)
else:
print("sorry no i")

⚡Eg-
for i in range(5):
print(i)
if i==2:
break
else:
print('sorry no i')

⚡Eg-
i=0
while i<7:
print(i)
i += 1
if i==4:
break
else:
print('sorry no i')

⚡Eg-
for x in range(5):
print("iteration no {} in for loop".format(x+1))
else:
print("else block in loop")
print("out of loop")

⚡Eg-
a=input("Enter the number:")
print(f"Multiplication table of {a} is: ")

for i in range (1,11):


print(f'{int(a)} X {i} = {int(a)*i}')

🌀ERROR HANDLING(try and except )

⚡Method 1-(normal error)


a=input("Enter the number:")
print(f"Multiplication table of {a} is:")
try:
"""Starts a try block.
Python will now try to run the following indented lines.
If an error occurs (like invalid input), it will jump to the except block."""
for i in range(1,11):

📌
print(f"{int(a)} X {i} = {int(a)*i}")
except Exception as e: this line is known by python including the meaning of e as error.
print(e)
#print("some imp line of code")
#print("end of programme")

⚡Method 2-(custom error)


a=input("Enter the number:")
print(f"Multiplication table of {a} is:")
try:
for i in range(1,11):
print(f"{int(a)} X {i} = {int(a)*i}")
except :
print('invalid input')

⚡Method 3-(value error)


⭐ValueError = You gave a wrong value (e.g., text instead of number).
try:
num = int(input("Enter an integer:"))
except ValueError :
print("Number entered is not an integer.")

⚡Method 4-(Index error)


⭐You tried to access a position in a list that doesn’t exist.
try:
num=int(input("Enter an integer:"))
a=[0,3]
print(a[num])
except ValueError:
print("number entered is not an integer.")
except IndexError:
print("Index Error")
📌Python know the words like ValueError and IndexError
📌The above methods are handling the specific error

🌀FINALLY KEYWORD
try:
l=[1,2,3,4]

📌
i=int(input('enter the index:'))
print(l[i]) prints ac to the index of l
except:
print("some error occured")
finally:
print('I am always executed')

❓Reason why we need to use finally keyword


instead directly printing the string

⚡1)Without finally keyword-


def fun1():
try:
l=[1,2,3,4]
i=int(input('enter the index:'))
print(l[i])
return 1
except :
print('some error occured')

📌
return 0
print("I am always executed") this line i never executed
x=fun1()
print(x)

💥Note=return keyword only works inside the function


⚡2)With using the finally keyword-
def fun():
try:
l=[1,2,3,4]
i=int(input('enter the index:'))
print(l[i])
return 1
except:

📌
print('some error occured')
finally: must executed in output
print('I am always executed ')
x=fun()
print(x)

🌀RAISING CUSTOM ERROR


a=int(input('enter any value between 5 and 9'))
if(a<5 or a>9):
raise ValueError("Value should be bw 5 and 9")

📌There are different types of Errors ..check Python Error Classes

🌀 IF ELSE IN ONE LINE


a=330
b=3303

📌
print("A") if a>b else print("=") if a==b else print("B")
c=9 if a>b else 0 If a > b, then c = 9. Otherwise, c = 0.
print(c)

🌀ENUMERATE FUNCTION
🍁LONG CUT(Without Enumerating the function)
📌
marks=[12,56,32,98,12,45,1,4]
index=0 Here index is just a variable and it is not connected to the marks automatically, it
is just a separate counter alongside the loop.
for mark in marks:
print(mark)
index +=1
if (index==3):
print("Hi hello")
📌Anything inside the loop runs once per iteration.So your counter grows with the loop, even if
📌therefore the counter we created is indirectly connected to the for loop.
it's not built-in.

🍁SHORT CUT(With Enumerating the function)


👉 enumerate(marks) returns a sequence of (index, value) pairs like:
"""First variable → gets the index (0, 1, 2, ...)
Second variable → gets the value from the list"""

⚡Eg-
📌
marks=[12,56,32,98,12,45,1,4]
for index,mark in enumerate(marks): enumerate() connects your loop directly with the index,

📌
no need for manual index += 1.
index is just a variable.Python doesn’t treat it as special. You could name it anything.
print(mark)
if(index==3):
print("Harry,awesome!")

🍁CHANGING THE START INDEX


marks=[1,2,3,4,5]
for index,mark in enumerate(marks,start=1):
print(mark)
if(index ==3):
print('awesome manu!')

🌀HOW IMPORTING IN PYTHON WORKS


⚡Eg-
📌 there are diff functions in math(module), we have to choose ac to our
import math
math.floor(4.2343)
need

⚡Eg-
import math
result = math.sqrt(9)
print(result)
⚡Eg-
from math import sqrt,pi
result =sqrt(9)*pi
print(result)

⚡Eg-
📌
from math import* (*) imports all function under math and it is not recommended to use this
because python gets confused
result =sqrt(9)*pi
print(result)


from

📌
Eg-
using function in code using shortcut by using (as)

📌
from math import pi, sqrt as s
it implies only only sqrt is s
result=s(9)*pi
print(result)

⚡Eg-
import math as m
result=m.sqrt(9)*m.pi
print(result)

⚡Eg-
📌
import math

📌
print(dir(math)) gives all the function in the math in the output
print(math.nan,type(math.nan)) gives the type of the function

🌀HOW IMPORTING FILE WORKS


1)make a new file .Eg- manu.py


2) Write your function
Eg- def welcome():
print('Hey you are welcome my friend')
Harry='A good boy'
3)Go to the old file. Eg- main.py
4)Write this:
from manu import welcome, Harry
OR
from manu import *
welcome()
print(Harry)

OR
import manu as m
m.welcome()
print(m.harry)

🌀LOCAL AND GLOBAL VARIABLE


1)Local Variable: Variable inside the function and cannot be used outside.
2)Global Variable: Variable outside the function and also can be used inside the function

⚡Eg- Global Variable


x=4
print(x)

📌
def hello():
print(x) The variable formed outside the function could be used
print(“hello Manu”)
hello()

⚡Eg-Local Variable
x=4
print(x)

📌
def hello():
x=5 this is local variable and can not be used outside thew function
print(x)
print("hello Manu")
hello()

⚡Eg-
x=4
print(x)
def hello():
x=5
print(f"the local x is {x}")
print("hello Manu")
print(f"The global x is {x}")
hello()
print(f"The global x is {x}")

⚡Eg-
x=10
def my_function():
y=5
print(y)
my_function()

📌
print(x)
print(y) gives error as it is local variable cannot print outside the function

🍁Then How to change x value(global variable) in function


x=10
def my_function():
global x
x=4
y=5
print(y)

📌
my_function()
print(x) now it will not print 10 because we made x=4 global which is inside the function.

✏️Suggestion- Avoid modifying global variables from within the function.

🌀FILE IO IN PYTHON
1) Make a new file(my file.txt)
-write
Hey manu awesome bro!

2)Open main.py
-write

📌
f=open('myfile.txt','r')
print(f) not gives actual content

💥Note
r=reading
w=writing
a=append

3)To get actual content 📌for reading


📌here you can skip ('r') because by default it will take 'r'
write-
f=open('myfile.txt','r')
text = f.read()
print(text)
f.close()

🍁To Open a new file


f= open('myfile2.txt,'w') 📌opens a new file if the mentioned file does not exist
text =f.read()
print(text)
f.close()

💥Note-
1)In 'write' mode if you write something new,the old content will get erased
2)So by using 'append' mode you can write new things along with the old content
3)create(x) - This mode creates a file and gives an error ,if the file already exists.
't' mode - this is used to handle text files.
4) f= open('myfile,txt','rt'),, here r (or) rt - same
w (or) wt - same - by default it opens text
5)binary(b) - this is used to handle binary files(images,pdfs,etc..) f= open('myfile.txt','rb')

🍁WRITING A FILE
📌
-in main.py

📌
f=open('myfile.txt','w') opens a new empty file
f.write('Hello, world') adds hello world to it, but if that file exists before with some content that
content would be replaced by this.

📌
f.close()
now in place of 'w' add 'a' - it goes on adding - the more times you run the more times it will
get print'

💥Note: f.close() is necessary but we can skip it by using (with):


⚡Eg-
-main.py:
with open('myfile.txt,'a') as f:
📌
f.write('hey I am inside with')
the above line is printed on the that file

🌀 read(), readlines() and other method


⚡Eg-
-myfile.txt
Harry Bhai python course is great

-main.py

📌
f=open('myfile.txt','r')
while True: creating an infinite loop until break
line=f.readlines()
print(line)
if not line:
print(line,type(line))

📌
break
first prints the line present in that liners once finished it will print empty line and type of the
line ac to function we mentioned

⚡Eg-
f=open('myfile.txt','r')
while True:
line=f.readline()
if not line:

📌
break
print(line) print every line of my file.txt

⚡Eg-
-my file.txt
56,45,67
12,34,63
13,64,23

-main.py

📌
with open('myfile.txt', 'r') as f:
i=0 Initialize a counter for student number

📌
while True:
i += 1 Increment student count for each line
line = f.readline() 📌 Read one line from the file

📌
if not line:
break Stop the loop if there are no more lines

📌Split the line by comma and extract marks


m1 = line.split(',')[0].strip() # Maths marks
m2 = line.split(',')[1].strip() # Science marks
m3 = line.split(',')[2].strip() # Kannada marks

📌 Display marks for the current student


print(f"Marks of student {i} in Maths is : {m1}")
print(f"Marks of student {i} in Science is : {m2}")
print(f"Marks of student {i} in Kannada is : {m3}")
print(line) # Optional: Print the full line (with newline character)with open('myfile.txt', 'r') as
f:

⚡Eg-
-main.py
f=open('myfile2.txt','w')
lines=['line1\n','line2\n','line3\n']
f.writelines(lines)

📌
f.close()
automatically open the new file

-myfile2.txt
line1
line2
line3

🌀seek() & tell() function


📌this functions are used to work with file objects and their positions within a file __ this are part
of the built-in io module
1)file.tell() - It returns the current position of the file cursor (in bytes) from the start of the file.
2)file.seek() - It moves the file cursor to a specific position.

⚡Eg-
-file.txt
Manu is good boy
-main.py
with open('file.txt','r') as f:

📌
print(type(f))

📌
f.seek(10) move cursor to the 10th byte in the file

📌
print(f.tell() tells where the cursor is located now
data = f.read(5) read the next 5 bytes
print(data)

🌀truncate()
⚡Eg-
-main.py
with open('samlple.txt',w,)as f:

📌
f.write('hello world!')
f.truncate(5) by this we can adjust the index to be printed
with open('sample.txt','r') as f
print(f.read())

📌
-sample.txt
Hello only prints 0-4 ac to command by using truncate

🌀LAMBDA FUNCTIONS IN PYTHON


⭐Used to create small, one-time functions without using def.
⚡Eg-(without using lambda function)
def double(x):
return(x*2)
print(double(5))

⚡Eg-(by using lambda function)


double = lambda x:x*2
print(double(5))

⚡Eg-
avg = lambda x,y:(x+y)/2
print(avg(4,6))
⚡Eg-
-method 1
cube = lambda x:x*x*x
def appl(fx,value):
return 6+ fx(value)
print(appl(cube,2))

⚡Eg-
method 2
def appl(fx,value):
return 6+ fx(value)
print(appl(lambda x:x*x*x,2))

🌀MAP, FILTER AND REDUCE


🍁map
⚡Eg-
👉long cut
def cube(x):
return x*x*x
print(cube(2))
l=[1,2,3,4]
newl=[]
for item in l:
newl.append(cube(item))
print(newl)

👉short cut(by using map)📌but not getting the actual content


def cube(x):
return x*x*x

📌
l=[1,2,3,4]

📌
newl=map(cube,l) here we can use lambda without defining a function
print(newl) prints some other content

👉to get actual content


def cube(x):
return(x*x*x)
l=[1,2,3,4]
newl=list(map(cube,l)) 📌you must convert into list to get actual content
print(newl)

🍁filter
filter() in Python is used to pick out only those items from an iterable (like list,
tuple, etc.) that satisfy a condition.

⚡Eg-
📌
l=[1,2,3,4]

📌
def greaterthan2(a): here a is each element in the loop
return(a>2) gives only number which is greater than 2
newl=list(filter(greaterthan2,l))
print(newl)

🍁reduce
It’s used to reduce a list (or iterable) into a single value by repeatedly applying a function.
It comes from the functools module.

⚡Eg-
📌
from functools import reduce imports reduce function from module functools

📌
numbers=[1,2,3,4,5]
sum=reduce(lambda x,y:x+y,numbers) It reduces the list into a single value by applying the

📌
function cumulatively.

📌
print(sum) 15
1+2=3,3+3=6,6+4=10,10+5=15

map() → transforms every element (output length = input length).

filter() → selects only elements that pass condition (output ≤ input length).

reduce() → combines all elements into one single value.

🌀'is' vs '=='
⭐both are comparing operators and they compare the objects
⚡Eg-
a=4

📌 ⚡
b='4'
print(a is b) compares the exact location of objects in memory. Eg- If I buy a Vivo phone
and my friend also buy the same model vivo phone , in terms of model(value) both are same but

📌
they are different (one phone is mine and another phone couldn't be mine it belongs to him)
print(a==b) compares the value

⚡Eg-
a=[1,2,3]

📌python saves in different location in its memory


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

💥Python behaves differently with strings and small integers due to interning.
⚡Eg-
a=3

📌Python reuses some objects (like short strings and small integers) to save
b=3
print( a is b)
memory.
print( a==b)

⚡Eg-
📌
a='harry'

📌
b='harry' Interning done here
print(a is b) True only for short strings
print( a==b)

📌Interning means > Storing only one copy of a value (like a string or small int) in memory
and reusing it.

⚡Eg-
a = "this is a long sentence with many words"


b = "this is a long sentence with many words"


print(a == b) # True (values same)

📌
print(a is b) # Likely False (not same object)
we can do 'is' as True by particular code

⚡Eg-
a=(1,2)
📌
📌
b=(1,2) tuples are immutable
print( a is b) True
print( a== b)

⚡Eg-
a=None
b=None
print(a is b)
print( a==b)
print(a is None)

You might also like