Python Notes
Python Notes
NOTES:
1. Variables
A variable in Python is a named memory loca on used to store data. It acts as a reference to a value
in memory.
Input: Python uses the input() func on to accept user input from the keyboard. The input is always
returned as a string.
Output: Python uses the print() func on to display data to the user. Output can be forma ed using f-
strings or the .format() method.
3. Calcula ons
Python allows arithme c opera ons (+, -, *, /, %, **, //) for performing calcula ons. It supports
integers, floa ng-point numbers, and complex numbers for these opera ons.
Python allows representa on and manipula on of binary, octal, and hexadecimal numbers:
5. Strings
Strings in Python are sequences of characters enclosed within single (') or double (") quotes. Strings
are immutable
LENGTH OF STRING- refers to calculate the length of string (in length special characters , gap and
digits are also included)
INDEXING- refers to the coun ng of posi on of any word which is present in string (in indexing gaps
or empty spaces are also include)
SLICING- refers to the accessing parts of a string between any star ng and ending index of string
its syntax is : str[staring_index : ending_index] # ending index is not included in the output
STRING FUNCTIONS
1 - ends with func on which tells that the string ends with that func on or not
its syntax is : str.endswith("ending words") // if it is ending with that words that its output will be
true if not then its output will be false
2-CAPITALIZE FUNCTION which capitalizes the ist char of the string // this func on creates a new
string with desired changes but do not make any changes in the old string
3 - REPLACE FUNCTION refers to the replacing of old value in func on with new value
4 - FIND FUNCTION refers to finding any word which exists in the string or not and if it exists then the
index of first le er of it gets printed
6. Lists
A list is an ordered, mutable collec on of items. Items in a list can be of different types. Lists are
created using square brackets []. Lists support various methods such as append(), pop(), and sort().
IN ANY LIST OUTPUT CAN BE ACCESSED FOR PARTICULAR INDEX THAT ARE PRESENT ELSE IT WILL
GIVE ERROR
LIST SLICING : SYNTAX IS : list_name[star ng_idx : ending_idx]
LIST METHODS
MUTATION IS ALLOWED IN A LIST (MODIFICATION)
7. Tuples
A tuple is an ordered, immutable collec on of items. Tuples are similar to lists but cannot be
modified a er crea on. They are created using parentheses ().
METHOD - INDEX METHOD : IT TELLS AT WHICH INDEX A NUMBER HAS OCCURRECED FIRST WHICH
IS REPEATING IN A TUPLE
SYNTAX : tup.index(element)
METHOD - COUNT METHOD : IT COUNTS THAT HOW MANY TIME AN ELEMENT HAS OCCURRED
INSIDE A TUPLE
SYNTAX : tup.count(element)
8. Dic onaries
A dic onary is an unordered collec on of key-value pairs. Keys must be unique and immutable, while
values can be of any type. Dic onaries are created using curly braces {}. They support methods like
get(), update(), and keys().
METHODS IN DICTIONARY
1 - TO PRINT ALL THE KEYS OF DICTIONARY
SYNTAX : dict.keys
5- UPDATE METHOD : INSERT A SPECIFIED VALUE TO A DICTIONARY , A NEW KEY VALUE SET , A
DICTIONARY CAN ALSO BE ADDED
SYNTAX : dict.update(new dict)
9. Sets
A set is an unordered collec on of unique items. Sets are used to store dis nct elements and support
opera ons like union, intersec on, and difference. They are created using curly braces {} or the set()
func on.
METHODS IN SETS
4 - POP METHOD : REMOVES ANY RANDOM VALUE(any value gets removed) DO NOT MAKE THE SET
EMPTY SET SYNTAX: set.pop()
SYNTAX: set.union(set2)
SYNTAX: SET.INTERSECTION(SET2)
10. Operators
Operators are special symbols used to perform opera ons on values and variables.
Func ons are reusable blocks of code that perform a specific task. Func ons are defined using the
def keyword, followed by the func on name and parentheses. Func ons can take arguments and
return values using the return statement.
FUNCTIONS IN PYTHON
1- BUILT IN FUNCTIONS 2-USER DEFINED FUNCTIONS
print() len() type() range() : THESE ARE BUILT IN FUNCTIONS IN PYTHON
USER DEFINED FUNCTIONS : are those func ons which are not already defined there logic is wri en
by programmers
A lambda func on is a small anonymous func on defined using the lambda keyword. It can have any
number of arguments but only one expression.
Example: lambda x, y: x + y
LAMBDA FUNCTIONS : LAMBDA FUNCTIONS ARE SINGLE EXPRESSIONS ; THEY DON'T HAVE ANY
NAME : ANONYMOUS FUNCTIONS : WRITTEN IN ONE LINE
SYNTAX = FUNCTION NAME = lambda INPUTS:func on expression INPUTS CAN BE ANY
NUMBERS ( X,Y,Z)
13. Loops
For Loop: Used for itera ng over a sequence (e.g., list, string).
PASS STATEMENT - PASS IS A NULL STATEMENT THAT DOES NOTHING . IT IS USED AS A PLACEHOLDER
FOR FUTURE CODE
Con nue: Terminates execu on in the current itera on and con nues execu on of the loop with the
next itera on
Variable scope refers to the region of the code where a variable is accessible.
Global Scope: Variables declared outside func ons are globally scoped.
Local Scope: Variables declared inside func ons are locally scoped and not accessible outside.
16. Object-Oriented Programming (OOP)
OOP is a programming paradigm based on the concept of objects, which can contain data (a ributes)
and methods (func ons).
Key features:
Inheritance: Allows one class to inherit the a ributes and methods of another.
Map: Applies a func on to all elements in a sequence. 1 - MAP FUNCTION - IN A MAP FUNCTION
OPERATION CAN BE PERFORMED ON EACH AND EVERY ELEMENT OF ITERABLE
SYNTAX - map(func on,iterables) ( iterable can BE A SET , LIST ,TUPLE, DICTIONARY ON
WHICH ANY LOOP IS PERFORMED)
18. Decorators
Decorators are func ons that modify the behavior of other func ons. They are applied using the
@decorator_name syntax and allow for extending func onality without modifying the original
func on.
Linear equa ons represen ng electrical circuits can be solved using matrix opera ons in Python. The
numpy library provides methods like np.linalg.inv() (for matrix inversion) and np.matmul() (for matrix
mul plica on) to solve circuits efficiently.
Codes
#Variable assignments
a = 10
b = 100
d = 'thirty'
#Sum of a and b
c=a+b
print('c') # Output: c
print('The sum of', a, 'and', b, 'is', c) # Output: The sum of 10 and 100 is 110
#Favorite color
color = 'blue'
c = int(a) + int(b)
print('The sum of the two numbers is:', c) # Output: The sum of the two numbers is:
40
a = 100
b = 2.45
c = 5 + 23j
# Calcula ng age
birth_year = 2003
weight_lb = weight_kg * 2
# Strings
course = 'PYTHON PROGRAMMING'
print(course[3]) # Output: H
k = 0B1001
l = hex(10)
q = 0O12
# Comparison operators
# Lists
# Crea ng a list
# Output: lst repeated 3 mes: [22, 4, 'awesome', 23, 2, 22, 4, 'awesome', 23, 2, 22, 4, 'awesome', 23,
2]
lst.append(200)
lst.remove('awesome')
lst.clear()
# Inser ng elements
lst1.insert(2, 76)
lst1.insert(2, 'e')
print("A er inser ng 'e' at index 2:", lst1) # Output: A er inser ng 'e' at index 2: [23,
2, 'e', 76, 34, 54, 78]
# Sor ng a list
lst2.sort()
print("Sorted lst2:", lst2) # Output: Sorted lst2: [2, 23, 34, 54, 78]
lst2.sort(reverse=True)
print("lst2 in descending order:", lst2) # Output: lst2 in descending order: [78, 54, 34, 23,
2]
# Duplicates in a list
print("List with duplicates:", lst3) # Output: List with duplicates: [30, 30, 34,
30, 45, 6, 3, 23, 6]
# Tuples (Read-only)
# Output: tpl repeated 3 mes: (12, 3, 'Shivam', 43, 12, 3, 'Shivam', 43, 12, 3, 'Shivam', 43)
# Coun ng and indexing in tuples
tpl3 = (2, 2, 2, 2, 3, 3, 3, 4)
# Slicing a tuple
tpl0 = tpl3[0:3]
tpl4 = tuple(lst5)
print("Converted list to tuple tpl4:", tpl4) # Output: Converted list to tuple tpl4: (34, 3,
24, 53, 53)
# Sets
print("Set a er update:", s) # Output: Set a er update: {1, 'Shivam', 34, 45, 20,
22, 23}
s.remove(20)
print("Frozen set f:", f) # Output: Frozen set f: frozenset({1, 'Shivam', 34, 45,
22, 23})
# Ques on 1: Country List Opera ons
cnt.append('USA')
cnt.remove('Japan')
cnt.insert(2, 'UAE')
# Range
print(i) # Output: 0 1 2 3 4
print(i) # Output: 1 3 5 7 9
b1 = bytes(lst1)
b2 = bytearray(b1)
# Dic onary
dict = {1: 'Shivam', 2: 'Sahil', 3: 'Shishir'}
# Output: Dic onary items: dict_items([(1, 'Shivam'), (2, 'Sahil'), (3, ‘Shishir')])
print("Value for key 3:", dict[3]) # Output: Value for key 3: Shishir
del(dict[2])
# Arithme c Operators
print("Floor division (integer result):", a // b) # Output: Floor division (integer result): 3.0
# Compound Operators
a += b
a *= b
print("Mul plica on assignment (a *= b):", a) # Output: Mul plica on assignment (a *= b): 39.0
a **= b
a /= b
a, b = 10, 23
print("Is a less than or equal to b?", a <= b) # Output: Is a less than or equal to b? True
# Logical Operators
print("Not (a == 10 and b == 2):", not (a == 10 and b == 2)) # Output: Not (a == 10 and b == 2): True
# Escape Characters
import math
a = 10
b = 20
grade = 'A'
name = 'Shivam'
marks = 67
print('Name is', name, 'and Marks are', marks) # Output: Name is Shivam and Marks are
67
print('Name is %s, and marks are %.2f' % (name, marks)) # Output: Name is Shivam, and
marks are 67.00
print('Name is {} and marks are {}'.format(name, marks)) # Output: Name is Shivam and
marks are 67
print('Name is {0} and marks are {1}'.format(name, marks)) # Output: Name is Shivam and
marks are 67
print('My name is {0}, I got {1} marks and secured {2} grade'.format(name, marks, grade))
prices = {'apple': 20, 'banana': 10, 'milk': 50, 'bread': 60, 'eggs': 100}
item1_name = input('Enter the name of the 1st item: ').lower() # Example Input: apple
item2_name = input('Enter the name of the 2nd item: ').lower() # Example Input: banana
item3_name = input('Enter the name of the 3rd item: ').lower() # Example Input: milk
item4_name = input('Enter the name of the 4th item: ').lower() # Example Input: bread
item5_name = input('Enter the name of the 5th item: ').lower() # Example Input: eggs
item2_price = prices.get(item2_name, 0)
item3_price = prices.get(item3_name, 0)
item4_price = prices.get(item4_name, 0)
item5_price = prices.get(item5_name, 0)
print('\nReceipt')
r=4
area = math.pi * r ** 2
if a == 0:
elif a % 2 == 0:
print("The number is even") # Example Output: The number is even (if input is 4)
else:
p = 41
C = 56
M = 78
else:
print("Student is pass")
x=1
# Q3: Print all odd numbers from lower bound to higher bound
x=a
while x <= b:
x += 1
print(x) # Output: 2, 4, 5, 6, 10
lst = [23, 3, 5, 2]
prod = 1
for x in lst:
x=5
b=x*a
print(x, "*", a, "=", b)
lst = [23, 3, 5, 2]
# Using break
for i in lst:
if i == 3:
print(i) # Output: 23
for i in lst:
if i == 3:
return (a + b) / 2
x=a+b
y=a-b
z=a*b
return x, y, z
result = calci(10, 20)
a = 100
def display():
y = 20
print(a, y) # Output: 90 20
z = display()
def displaying(name):
def message():
return "Hello"
return result
Nameit = "Shivam"
# IMPORT STATEMENTS
import keyword
# LAMBDA EXPRESSIONS
y = lambda x: x * x
numbers = (1, 2, 3, 4)
# FILTER FUNCTION
print("Filtered even numbers:", result) # Output: Filtered even numbers: [10, 20,
40]
# MAP FUNCTION
print("Doubled values:", result_map) # Output: Doubled values: [20, 40, 80, 10]
# REDUCE FUNCTION
lst = [1, 5, 6, 3, 5]
# DECORATOR FUNCTION
def decor(fun):
result = fun() * 2
return result
def num():
return 15
def hello(name):
def decor(func):
result = func('Shivam')
return result
answer = decor(hello)
# OBJECT-ORIENTED PROGRAMMING
# 1. Class Product
class Product:
def __init__(self):
self.name = 'iPhone'
self.descrip on = 'Expensive'
self.price = '80000'
p1 = Product()
class Course:
self.name = name
self.ra ng = ra ng
self.name = name
self.ra ng = ra ng
def average(self):
class Student:
s1 = Student(1, "John")
s2 = Student(2, "Shivam")
class Programmer:
self.name = name
def getName(self):
return self.name
self.salary = salary
def getSalary(self):
return self.salary
self.technologies = technologies
def getTechnologies(self):
return self.technologies
p1 = Programmer()
p1.setName("John")
p1.setSalary(100)
p1.setTechnologies(["Python", "JavaScript"])
# Line Plot
# Defining x and y points for a line plot
xpoints = np.array([1, 2, 3, 4, 5])
ypoints = np.array([10, 2, 30, 50, 25])
# Sca er Plot
# Sca er plot for GDP data
plt.sca er(xdata, ydata, color='blue')
plt.grid(color='blue', linewidth=1.7, linestyle='--')
plt. tle('Sca er Plot: GDP of India')
plt.xlabel('Years')
plt.ylabel('GDP Growth (%)')
plt.show()
# Output: A sca er plot with points represen ng GDP data
# Bar Plot
# Bar chart for GDP data
plt.bar(xdata, ydata, color='green')
plt.grid(color='blue', linewidth=1.7, linestyle='--')
plt. tle('Bar Plot: GDP of India')
plt.xlabel('Years')
plt.ylabel('GDP Growth (%)')
plt.show()
# Output: A green bar plot showing GDP growth for the years
# Plo ng histogram
plt.hist(student_marks, rwidth=0.8, bins=5, color='purple')
plt. tle('Histogram: Student Marks Distribu on')
plt.xlabel('Marks')
plt.ylabel('Frequency')
plt.show()
# Output: A histogram showing the distribu on of student marks
# Subplots
# Data for subplots
xpoints = np.array([1, 2, 3, 4])
ypoints = np.array([10, 20, 30, 40])
# Crea ng subplots
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))
plt.show()
# Output: Two subplots side by side with green and blue lines,
respec vely
# Voltage vector
V = np.array([0, 5, 7])