Python Note Book
Python Note Book
Python is popular for several reasons. Here's a deeper look at what makes it versatile and
easy for coders to use.
It has a simple syntax that mimics natural language, so it’s easier to read and understand.
This makes it quicker to build projects and faster to improve on them.
It’s versatile. Python can be used for many different tasks, from web development to
machine learning.
It’s beginner friendly, making it popular for entry-level coders.
It’s open source, which means it’s free to use and distribute, even for commercial
purposes.
Python’s archive of modules and libraries—bundles of code that third-party users have
created to expand Python’s capabilities—is vast and growing.
Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming
languages, which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.
Unicode. By default, Python 3 encodes strings using Unicode rather than ASCII.
Range functions. Python 3’s range() function replaced Python 2’s xrange()
function, improving performance when iterating over sequences.
Exception handling. Python 3’s exceptions are enclosed in parentheses, while Python
2’s exceptions are enclosed in notations.
Integer division. In Python 3, the result of an integer division is a float value. In Python
2, the decimals are truncated.
Annotations. Python 3 supports type annotations, whereas Python 2 does not. This
feature can help with reading and maintaining code.
Print statement. Python 3 replaces the print statement with a print() function.
Syntax. Python 3’s syntax is considered easier to understand and more readable than
Python 2’s, which uses more complex syntax.
Backward compatibility. Python 3 is not backward compatible with Python 2, whereas
Python 2 is backward compatible with previous versions of Python.
Install Python
Step 1
Step 2
After the installer is downloaded, double-click the .exe file (e.g., python-3.11.8-
amd64.exe) to run the Python installer.
Select the Install launcher for all users checkbox.
Select the Add python.exe to PATH checkbox.
Step 3
Pythonpath environment variable in Python allows you to include paths to other Python
files in your scripts and Python's import mechanism to determine where to search for
modules and files that use it. This is useful to avoid typing out full paths every time.
https://www.digitalocean.com/community/tutorials/install-python-windows-10
Python Syntax
python test.py
Variables
x = 50
y = "Learntek"
print(x)
print(y)
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for Python variables:
Examples:
myvar = "Learntek"
my_var = "Learntek"
_my_var = "Learntek"
myVar = "Learntek"
MYVAR = "Learntek"
myvar2 = "Learntek"
Global Variable
Variables that are created outside of a function (as in all of the examples above) are
known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Python Datatypes
Numeric Datatype
X = 3
Y = 56.3
Z = 23 + 65j
String Datatype
print("Hello")
print('Python 3.0')
b = "Hello, World!"
print(b[2:5]) # "llo"
s[0] # 'l'
s[0:5] # 'lets '
s[11:21] # 'databricks'
s[-1] # 'n'
s[-6:] # 'Python'
s[-6:][2] # 't'
s.split('databricks')
# ['lets learn ', ' with Python']
'|'.join(s.split())
# 'lets|learn|databricks|with|Python'
Here’s the textual content extracted from your slides and screenshots:
Interview Questions
Format String
age = 30
txt = "My name is Jiten, My age is " + str(age)
print(txt)
# Using f-string
print(f"My name is Jiten, My age is {age}")
age = 30
name = "FGS"
for age in range(30, 40):
txt = "my name is {} and my age is {}"
print(txt.format(name, age))
age = 30
name = "FGS"
for age in range(30, 40):
txt = f"my name is {name} and my age is {age}"
print(txt)
Here is the text content extracted and organized from the provided images:
Interview Questions
How to split a string
string.split()
Format String
# Using .format()
txt = "My name is Jiten, My age is {}"
print(txt.format(age))
# Using f-string
print(f"My name is Jiten, My age is {age}")
Example in Loop:
age = 30
name = 'FGS5'
for age in range(30, 40):
txt = 'my name is {} and my age is {}'
print(txt.format(name, age))
for age in range(30, 40):
txt = f'my name is {name} and my age is {age}'
print(txt)
Python Operators
= : Assignment
+= : Add and assign
-= : Subtract and assign
/ : Division
// : Floor division
% : Modulus
* : Multiplication
** : Exponentiation
Example:
age = 49
age += 10 # 59
59 % 5 # 4
2 ** 4 # 16
List
Items are:
o Ordered
o Changeable
o Allow duplicate values
Indexed (starting from 0)
Here is the text summary from the screenshots you shared regarding Python Lists and their
methods, as well as list copying concepts:
✅ List Basics
1. append()
Adds a single element at the end of the list.
2. l.append(False)
3. extend()
Adds elements of an iterable to the end of the list.
Note: Extending with an integer like l.extend(12) causes an error because integers
are not iterable.
4. insert(index, element)
Inserts an element at a specific position.
5. l.insert(5, 80)
6. pop(index)
Removes and returns element at the specified index.
7. l.pop() # Removes last element
8. remove(element)
Removes the first matching element.
9. l.remove([25,26]) # Works if such a sublist exists in `l`
10. clear()
Removes all elements from the list.
11. sort()
Sorts the list in place. Works only if elements are of the same type.
12. reverse()
Reverses the list in place.
13. Copying a list using copy()
14. l2 = l.copy() # deep copy
Using slicing:
reversed_list = l[::-1]
Or using a loop:
new_list = []
for i in range(len(l)-1, -1, -1):
new_list.append(l[i])
Shallow Copy: Copying a list such that changes in the new list affect the original list.
Deep Copy: Copying a list so that changes in the new list do not affect the original.
Using copy() creates a shallow copy for top-level elements but behaves like deep copy for
primitive data types. Use copy.deepcopy() from copy module for nested structures.
Would you like all of this in a downloadable .txt or .pdf format too?
In [32]: l1 = l
In [33]: l
Out[33]: [25, 8, 90, 80, 'X', 18, 6, 4]
In [34]: l1
Out[34]: [25, 8, 90, 80, 'X', 18, 6, 4]
In [35]: l1[4] = 16
In [36]: l1
Out[36]: [25, 8, 90, 80, 16, 18, 6, 4]
In [37]: l
Out[37]: [25, 8, 90, 80, 16, 18, 6, 4]
In [41]: l2
Out[41]: [25, 8, 90, 80, 16, 18, 6, 4]
✅ Explanation
Here is the extracted text content from the images you provided:
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a"
in the name.
Without list comprehension you will have to write a for statement with a conditional test
inside.
Example: [i**2 for i in range(10)]
Code Example:
l3 = []
for i in range(10):
l3.append(i**2)
print(l3)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Tuples are used to store multiple items in a single variable just like LIST.
Tuple is one of 4 built-in data types in Python used to store collections of data.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Unpack a Tuple
In Python, we are also allowed to extract the values back into variables. This is called
"unpacking".
Example:
F = ("A", "B", "C")
(x, y, z) = F
print(x)
print(y)
print(z)
# Tuple
t = (1, 2, 3, 4)
type(t)
# Output: <class 'tuple'>
Here is the extracted text content from the images you've provided:
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a"
in the name.
Without list comprehension, you will have to write a for statement with a conditional
test inside.
Example: [i**2 for i in range(10)]
Code Example:
l3 = []
for i in range(10):
l3.append(i**2)
print(l3) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Tuple
Tuples are used to store multiple items in a single variable just like LIST.
Tuple is one of 4 built-in data types in Python used to store collections of data.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Unpack a Tuple
In Python, we are also allowed to extract the values back into variables. This is called
"unpacking".
Example:
Code Example:
t = (1, 2, 3, 4)
type(t) # tuple
Methods in Tuple
T = tuple()
T.index()
T.count()
Questions
Set
Set is one kind of sequence datatype which is used to store multiple elements.
A set is a collection which is unordered, unchangeable*, and unindexed.
It is represented by curly braces {}.
Properties of SET
Unordered:
o The items in a set do not have a defined order.
o Set items can appear in a different order each time you use them, and cannot be
referred to by index or key.
Unchangeable:
o Set items are unchangeable, meaning that we cannot change the items after the set
has been created (we can add and remove elements but can’t change them).
Duplicates Not Allowed:
o Sets cannot have two items with the same value.
Methods of SET
add()
clear()
copy()
difference()
symmetric_difference()
intersection()
pop()
remove()
union()
update()
st1.difference(st2)
# Output: {12, 67}
st1.symmetric_difference(st2)
# Output: {12, 19, 67, 112, 167, 839}
st1.update(st2)
# st1 now includes all elements from st2, merged uniquely
st1.union(st2)
# Output: merged set, like update, but doesn’t modify st1
# Using frozenset
f1 = frozenset(st1)
f1[3] = 54 # Error: 'frozenset' object does not support item
assignment
Dictionary in Python
Example:
dic = {'A': 123, 'B': 'MNP'}
D = dict(A=123, B='MNP')
# Accessing elements
dic['A'] # Output: 123
d = dict(A=[3,2,6,1], B=['x','y','z','R'])
Add/update elements:
D = {'A': 987, 'B': 783, 'C': 'ASJGDK'}
D['B'] = 387
D.update({'B': 387})
Remove elements:
D.pop('key1') # Removes the specified key
D.popitem() # Removes the last inserted key-value
pair
Dictionary Comprehension
Basic format:
{dic[j]: i for i, j in dic.items()}
Comprehensions using keys or values:
{i for i in dic.keys()}
{j for j in dic.values()}
Comprehension Examples
Extract values from dictionary:
[i for i in d.values()]
Reorder or extract data:
[j*2 for i, j in d.items()]
Certainly! Here's the full Python code along with the corresponding output from the images
you provided:
1. Dictionary Creation
d = dict(A=[3,2,6,1], B=['x','y','z','R'])
Output:
d['A']
Output:
[3, 2, 6, 1]
d.keys(), d.values()
Output:
Output:
3. Adding Elements
Output:
4. Removing Elements
d.pop('D')
Output:
Output:
Output:
5. Dictionary Comprehension
[i for i in d.values()]
Output:
Output:
[['x', 'y', 'z', 'R', 'x', 'y', 'z', 'R'], [3, 20, 6, 1, 3, 20,
6, 1]]
Here is the text extracted from the images along with the outputs explained:
Explanation:
The enumerate() function returns indexes of all items in iterables (lists, dictionaries,
sets, etc.).
The zip() function is used to aggregate or combine multiple iterables.
Example usages:
Zip(l1, l2)
Enumerate(l1)
Output:
NAME XYZ
ID 123
AGE 29
Output:
Output:
Q1:
a = [1,2,3,4,5,6,7,8,9]
a[::2] = 10, 20, 30, 40, 50
print(a)
Output:
Explanation:
Assigns values to every second element starting from index 0.
Q2:
a = [1,2,3,4,5]
print(a[3:0:-1])
Output:
[4, 3, 2]
Explanation:
Slice from index 3 to 1 (excluding 0), stepping backwards.
Q3:
Output:
<class 'int'>
14
Explanation:
a is an integer, not a tuple.
Q5:
b = (3,)
print(type(b))
print(b * 3)
Output:
<class 'tuple'>
(3, 3, 3)
Explanation:
b is a tuple of one element, repeated 3 times.
Q6:
print(list(range(10)))
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Q7:
Output:
Q8:
my_dict = {}
my_dict[1] = 1
my_dict['1'] = 2
my_dict[1.0] = 4
print(my_dict)
Explanation:
1 and 1.0 are considered the same key in dictionary, so the value is overwritten.
Here is the extracted text and output from the images you shared:
Input:
Output:
Python program control flow is regulated by various types of conditional statements, loops, and
function calls. By default, the instructions in a computer program are executed in a sequential
manner, from top to bottom, or from start to end. However, such sequentially executing
programs can perform only simplistic tasks. We would like the program to have a decision-
making ability, so that it performs different steps depending on different conditions.
3. IF statement
It is helpful when we need some conditional workflow or execution.
Example:
l = input('enter a number')
if l % 3 == 0:
print('divisible by 3')
Output:
enter a number : 30
30 is divisible by 5
6. If Else statement
Along with the if statement, else keyword can also be optionally used. Python if else
statement provides an alternate block of statements to be executed if the boolean
expression (in if statement) is not true.
Syntax:
if expression True:
print()
else:
print()
7. If Else example
Output:
enter a number : 15
45 is not divisible by 3
a = int(input('enter a number : '))
if a:
print(f'{a} is not zero')
else:
print(f'{a} is zero')
Output:
enter a number : 0
0 is zero
8. Explanation comments
9. Nested if
Syntax:
if condition:
print()
elif condition:
print()
else:
print()
Error:
Sure! Here's the text extracted from the images you uploaded, along with the relevant code
outputs:
Match Case
Syntax:
match variable:
case var1: return 0
case var2: return 1
Example:
def check_number(x):
match x:
case 10:
print("It's 10")
case 20:
print("It's 20")
case _:
print("It's neither 10 nor 20")
check_number(10)
Output:
It's 10
Loop
Types:
While loop
For loop
Nested loop
n = 15
while n > 10:
print(n*10)
n = n - 1
Output:
150
140
130
120
110
l = list(range(1, 11))
print(l)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Control Statements
Control
Sr.No Description
Statement
break Terminates the loop statement and transfers execution to the statement
1
statement immediately following the loop.
continue Causes the loop to skip the remainder of its body and immediately retest
2
statement its condition prior to reiterating.
The pass statement in Python is used when a statement is required
3 pass statement
syntactically but you do not want any command or code to execute.
Examples
Break Statement
l1 = [3, 4, 5, 32, 4]
for i in l1:
print(i)
if i == 5:
break
Output:
3
4
5
Continue Statement
l1 = [3, 4, 5, 32, 4]
for i in l1:
print(i)
if i < 10:
continue
else:
break
print(i)
Output:
3
4
5
32
Pass Statement
if year:
df = df.filter(df.year > year)
else:
pass
Python
s1=['ABHD', 'JAG', 'ASSwx', 'TEW', 'AUYR', 'KUG']
l2=[]
for ele in s1:
if ele.startswith('A'):
l2.append(ele)
else:
continue
l2
Output 1:
Image 2:
Python
s1=['ABHD', 'JAG', 'ASSwx', 'TEW', 'AUYR', 'KUG']
l2=[]
for index in range(len(s1)):
if s1[index].startswith('A'):
l2.append(s1[index])
else:
continue
l2
Output 2:
A
U
U
I
E
O
Image 3:
Python
s2 = 'AHSUNUIEGJXKWSDYOGHjsgtw'
for j in s2:
if j not in ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o',
'u'):
print(j)
else:
continue
Output 3:
H
S
N
G
J
X
K
W
S
D
Y
G
H
j
s
g
t
w
Image 4:
This image describes a nested loop and provides an example:
Python
for i in range(0,100,3):
for j in range(i+1):
print(i+j)
This code would produce a long sequence of numbers, starting with: 1 3 4 6 7 8 ... and so on.
Image 5:
Python
for i in range(1,10,3): # i -> 1, 4, 7
for j in range(i):
print(i,j)
print(i+j)
Output 5:
1 0
1
4 0
4 1
4 2
4 3
4
7 0
7 1
7 2
7 3
7 4
7 5
7 6
7
What is a Function
1. A Python function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high degree
of code reusing.
2. A top-down approach towards building the processing logic involves defining blocks of
independent reusable functions. A Python function may be invoked from any other
function by passing required data (called parameters or arguments). The called function
returns its result back to the calling environment.
Python
In [21]: def string_match(s1):
l2=[]
for index in range(len(s1)):
if s1[index].startswith('A'):
l2.append(s1[index])
else:
continue
return l2
Python
def sum_1(l):
sum_1 = sum(l)
return sum_1
def mul(l):
l2=[]
for j in l:
l2.append(j**2)
return l2
Python
In [35]: from sum_list import mul
def function1():
...
function2()
...
return
def function2():
...
function1()
...
Return
Python
In [39]: def rev_string(s1):
return s1[::-1]
rev_string('JITEN')
Out[39]:
'NETIJ'
Image 2:
Python
In [47]: n1=[123,637,973]
[int(str(ele)[::-1]) for ele in n1 ]
Out[47]:
Image 3:
Function_1(param1,param2)
Image 4:
Python
In [41]: def rev_string(s1):
return s1[::-1]
rev_string('JITEN')
Out[41]:
'ET'
Image 5:
Pass by value vs Pass by reference
Image 6:
Python
Function
add_num(12,32)
Out[1]:
44
Python
In [3]: def add_num(n1,n2):
n1 = n1+2
n2 = n2+5
return n1+n2
x1=23
x2=73
add_num(x1,x2)
Out[3]:
103
Python
In [6]: add_num(x1,x2)
Out[6]: 103
7:
Python
In [9]: def add_num(n1,n2):
n1 = n1+2
n2 = n2+5
return n1+n2
Out[9]:
106
8:
• Default Arguments
• Keyword Arguments
• Arbitrary Arguments
• Required Arguments
9:
Python
In [21]: def add_num(n1,n2):
n1 = n1+2
n2 = n2+5
return n1+n2
x2=74
add_num(n1=12,n2=x2)
Out[21]:
93
10:
Python
In [44]: def add_num(n1=0,n2=34,n3=78):
return n1+n2+n3
n2=30
n1=20
n3=13
#x1=int(input('enter num1 : '))
add_num(n1,n2,n3)
Out[44]:
63
Types of Arguments in Python
• Default Arguments
• Keyword Arguments
• Arbitrary Arguments
• Required Arguments
2:
Python
In [54]: def add_num(n1,n2,n3,n4):
x = n1+n2
y = n3+n4
return x/y
n1,n2,n3,n4 = 23,534,12,78
n = n1,n2,n3,n4
add_num(*n)
Out[54]:
*args vs **kwargs
The special syntax *args in function definitions in Python is
used to pass a variable number of
arguments to a function. It is used to pass a non-keyworded,
variable-length argument list.
• The syntax is to use the symbol * to take in a variable number
of arguments; by convention, it is
often used with the word args.
• What *args allows you to do is take in more arguments than the
number of formal arguments
that you previously defined. With *args, any number of extra
arguments can be tacked on to your
current formal parameters (including zero extra arguments).
• For example, we want to make a multiply function that takes any
number of arguments and is
able to multiply them all together. It can be done using *args.
• Using the *, the variable that we associate with the * becomes
iterable meaning you can do things
like iterate over it, run some higher-order functions such as
map and filter, etc.
The special syntax **kwargs in function definitions in Python is
used to pass a keyworded, variable-
length argument list. We use the name kwargs with the double
star. The reason is that the double
star allows us to pass through keyword arguments (and any number
of them).
4:
Python
In [61]: def add_num(**y):
x = y['n1']
z = y['n2']
return x/z
x1=129
x2=43
add_num(n1=x1,n2=x2)
Out[61]:
3.0
5:
• def ABV(*a):
• if x>10:
• return x*=2
• else:
• return x*y
• print
• x=4
• y=8
• a = (x,y)
• ABV(*a)
• def abc(**a):
• for i,j in a.items():
• print(a[i])
• abc(x=11,y=12)
Image 2:
Anonymous function
Image 3:
Python
lambda function
Out[67]:
Image 5:
Python
x=[3,2,1,3]
list(map(lambda x: x*2,x))
x=[30,12,41,73]
list(filter(lambda x: x%2==0,x))
x=[3,2,1,3]
reduce(lambda x,y: x+y,x)
Image 6:
Python
x=[3,2,1,3]
list(map(lambda x: x*2,x))
x=[30,12,41,73]
list(filter(lambda x: x%2==0,x))
x=[3,2,1,3]
reduce(lambda x,y: x+y,x)
Python
map filter reduce
Out[6]:
Image 8:
Python
In [13]: s = ['ABC', 'TYY', 'RWQ', 'AYTEI']
list(filter(lambda x : x[0]=='A', s))
Out[13]:
['ABC', 'AYTEI']
Python
In [12]: s = ['ABC', 'TYY', 'RWQ', 'AUTRI']
list(map(lambda x : x[0]=='A', s))
Out[12]:
Image 9:
Python
In [16]: s = ['ABC', 'TYY', 'RWQ', 'AUTRI']
list(map(lambda x : x if x[0]=='A' else 'XXXX', s))
Out[16]:
Python
In [18]: from functools import reduce
Out[19]:
'ABCTYYRWQAUTRI'
Python
In [ ]: x = 'ABC'
y = x + y #'ABC'
y = 'ABC'
Python
x=[3,2,1,3]
list(map(lambda x: x*2,x))
x=[30,12,41,73]
list(filter(lambda x: x%2==0,x))
x=[3,2,1,3]
reduce(lambda x,y: x+y,x)
Image 2:
Nested Function
A function that is defined inside another function is known as a
nested
function. Nested functions are able to access variables of the
enclosing scope.
In Python, these non-local variables can be accessed only within
their
scope and not outside their scope.
def outerFunction(str1):
def innerFunction():
print(str1)
innerFunction()
OuterFunction('AJSJHD')
Image 4:
Python
nested function
outer_function('jbef',2)
Out[25]:
'jbefjbef'
Python
In [35]: def outer_function(s1):
def inner(s2):
s = s1*s2
return s
return inner
o = outer_function('jbef')
o(2)
Out[35]:
'jbefjbef'
Closure function
• A Closure in Python is a function object that remembers values
in
enclosing scopes(outer function) even if they are not present
in
memory.
• It is a record that stores a function together with an
environment: a
mapping associating each free variable of the function
(variables that
are used locally but defined in an enclosing scope) with the
value or
reference to which the name was bound when the closure was
created.
• A closure—unlike a plain function—allows the function to access
those captured variables through the closure's copies of their
values
or references, even when the function is invoked outside their
scope.
Image 6:
Python
Example
def num_add(num1):
def num_sub(num2):
return num1+num2
return num_sub
a=input('num1')
b=input('num2')
num_add(a)(b)
Decorator Function
Image 8:
Python
decorator function
In [60]: x = [2,3,4,5]
outer(add_list)(x)
Out[60]:
'EVEN'
Image 9:
Python
In [61]: @outer
def add_list(x):
return sum(x)
add_list(x)
Out[61]:
'EVEN'