Python Lab File
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.
2. Input and Output
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.
4. Binary, Hexadecimal, and Octal Numbers
Python allows representa on and manipula on of binary, octal, and hexadecimal numbers:
Conversion func ons:
bin(): Converts an integer to a binary string.
oct(): Converts an integer to an octal string.
hex(): Converts an integer to a hexadecimal string.
5. Strings
Strings in Python are sequences of characters enclosed within single (') or double (") quotes. Strings
are immutable
CONCATENATION refers two joining of two string
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
5 - COUNT FUNCTION refers to the count of occurence of any le er or word in a string
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)
1 - ADDITION OF ANYTHING IN A LIST AT THE END
SYNTAX : list.append()
2 - SORTING METHOD : THIS METHOD INCLUDES THE ARRANGEMENT OF DATA IN ASCENDING
ORDER
SYNTAX : list.sort()
3 - REVERSE : IT INCLUDE THE REVERSAL OF ANY LIST # LIST IN DESCENDING ORDER
SYNTAX : list.sort(reverse=True)
4 - REVERSE METHOD - ISME PURI LIST ULTI HO JATI H
SYNTAX : list.reverse() # REVERSAL IS DONE IN A ORIGINAL LIST
5 - INSERT METHOD : INVOLVES INSERTING OF ANYTHING AT A PARTICULAR INDEX
SYNTAX : list.insert(index,element which is to be added)
6 - REMOVE METHOD : IT INVOLVES REMOVAL OF FIRST OCCURENCE OF ELEMENT
SYNTAX : list.remove()
7 - POP METHOD - REMOVAL OF VALUE AT A PARTICULAR INDEX
SYNTAX : list.pop(index)
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
2 - RETURN COLLECTION OF ALL VALUES
3 - DICT.ITEMS : IT RETURNS ALL (key,val) pairs as tuples
4 - GET METHOD : IT RETURNS THE KEY ACCORDING TO THE VALUE
SYNTAX : dict.get("key")
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
1 -ADD METHOD TO ADD SOMETHING IN A SET # SYNTAX: set.add(ele)
2- REMOVE METHOD : SYNTAX: set.remove(ele)
3-CLEAR METHOD : USE TO EMPTY ANY LIST # SYNTAX: set.clear()
4 - POP METHOD : REMOVES ANY RANDOM VALUE(any value gets removed) DO NOT MAKE THE SET
EMPTY SET SYNTAX: set.pop()
5-UNION METHOD : COMBINED VALUES OF TWO SETS
SYNTAX: set.union(set2)
6- INTERSECTION : GIVES OUT COMMON ELEMENTS
SYNTAX: SET.INTERSECTION(SET2)
10. Operators
Operators are special symbols used to perform opera ons on values and variables.
Arithme c Operators: +, -, *, /, %, **, //
Rela onal Operators: ==, !=, <, >, <=, >=
Logical Operators: and, or, not
Bitwise Operators: &, |, ^, ~, <<, >>
Assignment Operators: =, +=, -=, etc.
11. Func ons
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
DEFAULT PARAMETERS : ASSUMING A DEFAULT VALUE TO PARAMETERS , WHICH IS USED WHEN NO
ARGUMENT IS PASSED
PROCESS OF ASSIGNING DEFAULT PARAMETER ALWAYS STARTS FROM END
12. Lambda Expressions
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)
DIFFERENCES BETWEEN LAMBDA AND NORMAL FUNCTION
1 - LAMBDA HAS NO RETURN VALUE
2 - LAMBDA IS A ONE LINE FUNCTION
3 - LAMBDA FUNCTION CAN NOT BE USED AGAIN AND AGAIN (NO CODE REUSABILITY)
4 - LAMBDA FUNCTION HAS NO NAME
13. Loops
For Loop: Used for itera ng over a sequence (e.g., list, string).
While Loop: Repeats as long as a condi on is True.
PASS STATEMENT - PASS IS A NULL STATEMENT THAT DOES NOTHING . IT IS USED AS A PLACEHOLDER
FOR FUTURE CODE
14. Break and Con nue
Break: Exits the nearest enclosing loop prematurely.
Con nue: Terminates execu on in the current itera on and con nues execu on of the loop with the
next itera on
15. Variable Scope
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:
Class: A blueprint for crea ng objects.
Object: An instance of a class.
Inheritance: Allows one class to inherit the a ributes and methods of another.
Encapsula on: Restricts direct access to some components.
Polymorphism: Allows different classes to define the same methods.
17. Filter, Map, and Reduce Func ons
Filter: Filters elements from a sequence based on a condi on.
SYNTAX : filter(lambda func on condi on,itera on)
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)
Reduce: Reduces a sequence to a single value using a func on.
THESE ARE NOT DIRECTLY PRESENT IN FUNCTION NEEDED TO BE IMPORTED
REDUCE REDUCES THE LIST
SYNTAX : functools.reduce(lambda x,y: x>y else y,itera on)
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.
19. Plo ng Graphs
Python provides the matplotlib library for crea ng visualiza ons. Common plots include line plots,
bar charts, histograms, sca er plots, and subplots. Plots can be customized with tles, labels,
legends, and grids.
20. Electrical Circuit Solving Using Matrices
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: 110
print('c') # Output: c
print('The sum of', a, 'and', b, 'is', c) # Output: The sum of 10 and 100 is 110
print('The sum of a and b =', c) # Output: The sum of a and b = 110
print('The sum of a and b is ' + d) # Output: The sum of a and b is thirty
#Favorite color
color = 'blue'
print('My favorite color is', color) # Output: My favorite color is blue
# User input for name
name = input('What is my name? ') # Example Input: John
print(name) # Output: John
# User input for adding two numbers
a = input('Enter the first number: ') # Example Input: 15
b = input('Enter the second number: ') # Example Input: 25
# Convert inputs to integers and calculate sum
c = int(a) + int(b)
print('The sum of the two numbers is:', c) # Output: The sum of the two numbers is:
40
# Data types demonstra on
a = 100
b = 2.45
c = 5 + 23j
print(type(a)) # Output: <class 'int'>
print(type(b)) # Output: <class 'float'>
print(type(c)) # Output: <class 'complex'>
# Calcula ng age
birth_year = 2003
age = 2024 - birth_year
print('Age:', age) # Output: Age: 21
print(type(age)) # Output: <class 'int'>
# Weight conversion from kg to pounds
weight_kg = float(input('Enter weight in kg: ')) # Example Input: 50
weight_lb = weight_kg * 2
print('Weight in pounds is', weight_lb) # Output: Weight in pounds is 100.0
# Strings
course = 'PYTHON PROGRAMMING'
print(course[0:3]) # Output: PYT
print(course[:]) # Output: PYTHON PROGRAMMING
print(course[3]) # Output: H
# Binary, hexadecimal, and octal numbers
k = 0B1001
print('Binary 0B1001 in decimal is', k) # Output: Binary 0B1001 in decimal is 9
l = hex(10)
print('Hexadecimal of 10 is', l) # Output: Hexadecimal of 10 is 0xa
q = 0O12
print('Octal 0O12 in decimal is', q) # Output: Octal 0O12 in decimal is 10
# Comparison operators
print(8 < 10) # Output: True
# Comparing input values
a = int(input('Enter the value of a: ')) # Example Input: 15
b = int(input('Enter the value of b: ')) # Example Input: 10
print(a > b) # Output: True
# Lists
# Crea ng a list
lst = [22, 4, 'awesome', 23, 2]
print("Original list:", lst) # Output: Original list: [22, 4, 'awesome', 23, 2]
# Crea ng an empty list
lst1 = []
print("Empty list:", lst1) # Output: Empty list: []
# Length of the list
print("Length of lst:", len(lst)) # Output: Length of lst: 5
# Prin ng the list mul ple mes
print("lst repeated 3 mes:", lst * 3)
# Output: lst repeated 3 mes: [22, 4, 'awesome', 23, 2, 22, 4, 'awesome', 23, 2, 22, 4, 'awesome', 23,
2]
# Accessing elements in the list
print("Element at index 2:", lst[2]) # Output: Element at index 2: awesome
print("Element at index 1:", lst[1]) # Output: Element at index 1: 4
# Adding and removing elements
lst.append(200)
print("A er appending 200:", lst) # Output: A er appending 200: [22, 4,
'awesome', 23, 2, 200]
lst.remove('awesome')
print("A er removing 'awesome':", lst) # Output: A er removing 'awesome': [22, 4, 23, 2,
200]
# Modifying the list
lst = [23, 2, 34, 54, 78, 'aws']
del(lst[2]) # element at index 2 is deleted
print(lst) # Output: [23, 2, 54, 78, 'aws']
# Clearing the list
lst.clear()
print("Cleared list:", lst) # Output: Cleared list: []
# Another list
lst1 = [23, 2, 34, 54, 78]
print("Maximum value in lst1:", max(lst1)) # Output: Maximum value in lst1: 78
# Inser ng elements
lst1.insert(2, 76)
print("A er inser ng 76 at index 2:", lst1) # Output: A er inser ng 76 at index 2: [23,
2, 76, 34, 54, 78]
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 = [23, 2, 34, 54, 78]
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
lst3 = [30, 30, 34, 30, 45, 6, 3, 23, 6]
print("List with duplicates:", lst3) # Output: List with duplicates: [30, 30, 34,
30, 45, 6, 3, 23, 6]
# Tuples (Read-only)
tpl = (12, 3, 'Shivam', 43)
tpl1 = (24,) # Tuple with a single item
print("Tuple tpl:", tpl) # Output: Tuple tpl: (12, 3, 'Shivam', 43)
print("Tuple tpl1:", tpl1) # Output: Tuple tpl1: (24,)
print("tpl repeated 3 mes:", tpl * 3)
# 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)
print("Count of 2 in tpl3:", tpl3.count(2)) # Output: Count of 2 in tpl3: 4
print("Index of first occurrence of 3 in tpl3:", tpl3.index(3))
# Output: Index of first occurrence of 3 in tpl3: 4
# Slicing a tuple
tpl0 = tpl3[0:3]
print("Sliced tuple tpl0:", tpl0) # Output: Sliced tuple tpl0: (2, 2, 2)
# Conver ng list to tuple
lst5 = [34, 3, 24, 53, 53]
tpl4 = tuple(lst5)
print("Converted list to tuple tpl4:", tpl4) # Output: Converted list to tuple tpl4: (34, 3,
24, 53, 53)
# Sets
s = {20, 23, 1, 45, 'Shivam'}
print("Set s:", s) # Output: Set s: {1, 'Shivam', 45, 20, 23}
s.update([34, 22]) # Adding elements
print("Set a er update:", s) # Output: Set a er update: {1, 'Shivam', 34, 45, 20,
22, 23}
s.remove(20)
print("Set a er removing 20:", s) # Output: Set a er removing 20: {1,
'Shivam', 34, 45, 22, 23}
# Frozen set (Immutable)
f = frozenset(s) # you cannot modify it a er freezing
print("Frozen set f:", f) # Output: Frozen set f: frozenset({1, 'Shivam', 34, 45,
22, 23})
# Ques on 1: Country List Opera ons
cnt = ['India', 'Nepal', 'Japan']
print("Ini al countries list:", cnt) # Output: Ini al countries list: ['India',
'Nepal', 'Japan']
cnt.append('USA')
print("A er adding 'USA':", cnt) # Output: A er adding 'USA': ['India',
'Nepal', 'Japan', 'USA']
cnt.remove('Japan')
print("A er removing 'Japan':", cnt) # Output: A er removing 'Japan': ['India', 'Nepal',
'USA']
cnt.insert(2, 'UAE')
print("A er inser ng 'UAE' at index 2:", cnt)
# Output: A er inser ng 'UAE' at index 2: ['India', 'Nepal', 'UAE', 'USA']
# Range
print("Range from 0 to 4:")
for i in range(0, 5): # or range(5)
print(i) # Output: 0 1 2 3 4
print("Range from 1 to 9 with step of 2:")
for i in range(1, 10, 2):
print(i) # Output: 1 3 5 7 9
# Bytes and Bytearray
lst1 = [2, 23, 4, 234]
b1 = bytes(lst1)
print("Bytes object b1:", b1) # Output: Bytes object b1: b'\x02\x17\x04\xea'
b2 = bytearray(b1)
print("Bytearray object b2:", b2) # Output: Bytearray object b2:
bytearray(b'\x02\x17\x04\xea')
# Dic onary
dict = {1: 'Shivam', 2: 'Sahil', 3: 'Shishir'}
print("Dic onary items:", dict.items())
# 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])
print("Dic onary a er dele ng key 2:", dict)
# Output: Dic onary a er dele ng key 2: {1: 'Shivam', 3: 'Shishir'}
# Arithme c Operators
a = float(input("Enter a: ")) # Example Input: 10
b = float(input("Enter b: ")) # Example Input: 3
# Arithme c opera ons
print("Floor division (integer result):", a // b) # Output: Floor division (integer result): 3.0
print("Exponen al (a^b):", a ** b) # Output: Exponen al (a^b): 1000.0
print("Division:", a / b) # Output: Division: 3.3333333333333335
# Compound Operators
a += b
print("Addi on assignment (a += b):", a) # Output: Addi on assignment (a += b):
13.0
a *= b
print("Mul plica on assignment (a *= b):", a) # Output: Mul plica on assignment (a *= b): 39.0
a **= b
print("Exponen a on assignment (a **= b):", a) # Output: Exponen a on assignment (a **= b):
59319.0
a /= b
print("Division assignment (a /= b):", a) # Output: Division assignment (a /= b): 19773.0
# Rela onal Operators
a, b = 10, 23
print("Is a equal to b?", a == b) # Output: Is a equal to b? False
print("Is a greater than or equal to b?", a >= b) # Output: Is a greater than or equal to b? False
print("Is a less than or equal to b?", a <= b) # Output: Is a less than or equal to b? True
print("Is a not equal to b?", a != b) # Output: Is a not equal to b? True
print("Is a greater than b?", a > b) # Output: Is a greater than b? False
# Logical Operators
print("Is a == 10 and b == 2?", a == 10 and b == 2) # Output: Is a == 10 and b == 2? False
print("Is a == 10 or b == 2?", a == 10 or b == 2) # Output: Is a == 10 or b == 2? True
print("Not (a == 10 and b == 2):", not (a == 10 and b == 2)) # Output: Not (a == 10 and b == 2): True
# Escape Characters
print('This is "Python" lab') # Output: This is "Python" lab
print("This is \"Python\" lab") # Output: This is "Python" lab
# Input and Output Func ons
import math
# Print func on with different formats
a = 10
b = 20
grade = 'A'
print("Using separator '||':", a, b, sep='||') # Output: Using separator '||':10||20
# Forma ng output with different methods
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))
# Output: My name is Shivam, I got 67 marks and secured A grade
# Input from user and list comprehension
lst = [x for x in input('Enter three numbers separated by space: ').split()]
# Example Input: 1 2 3 | Output: ['1', '2', '3']
# Taking input as integers
lst = [int(x) for x in input('Enter three numbers separated by space: ').split()]
# Example Input: 4 5 6 | Output: [4, 5, 6]
# Grocery Checkout Receipt Assignment
prices = {'apple': 20, 'banana': 10, 'milk': 50, 'bread': 60, 'eggs': 100}
# Taking item names as input and conver ng to lowercase
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
# Taking quan ty of each item
item1_qty = int(input(f'Enter the quan ty of {item1_name}: ')) # Example Input: 2
item2_qty = int(input(f'Enter the quan ty of {item2_name}: ')) # Example Input: 3
item3_qty = int(input(f'Enter the quan ty of {item3_name}: ')) # Example Input: 1
item4_qty = int(input(f'Enter the quan ty of {item4_name}: ')) # Example Input: 2
item5_qty = int(input(f'Enter the quan ty of {item5_name}: ')) # Example Input: 5
# Fetching prices and calcula ng totals for each item
item1_price = prices.get(item1_name, 0)
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)
item1_total = item1_price * item1_qty # Example: 40
item2_total = item2_price * item2_qty # Example: 30
item3_total = item3_price * item3_qty # Example: 50
item4_total = item4_price * item4_qty # Example: 120
item5_total = item5_price * item5_qty # Example: 500
# Calcula ng subtotal, tax, and final total
sub_total = item1_total + item2_total + item3_total + item4_total + item5_total # Example: 740
tax = (5 * sub_total) / 100 # Example: 37.0
final_total = tax + sub_total # Example: 777.0
# Prin ng the receipt
print('\nReceipt')
print(f'{item1_name.capitalize()} {item1_qty} @ ${item1_price} each = ${item1_total}') # Example:
Apple 2 @ $20 each = $40
print(f'{item2_name.capitalize()} {item2_qty} @ ${item2_price} each = ${item2_total}') # Example:
Banana 3 @ $10 each = $30
print(f'{item3_name.capitalize()} {item3_qty} @ ${item3_price} each = ${item3_total}') # Example:
Milk 1 @ $50 each = $50
print(f'{item4_name.capitalize()} {item4_qty} @ ${item4_price} each = ${item4_total}') # Example:
Bread 2 @ $60 each = $120
print(f'{item5_name.capitalize()} {item5_qty} @ ${item5_price} each = ${item5_total}') # Example:
Eggs 5 @ $100 each = $500
print('Total price is:', final_total) # Example: Total price is: 777.0
# Math Library - Calcula ng area of a circle
r=4
area = math.pi * r ** 2
print("Area of circle with radius", r, "is:", area)
# Output: Area of circle with radius 4 is: 50.26548245743669
# Flow Control / Func ons
# Q1: Check for even or odd
a = int(input("Enter the number: ")) # Example Input: 5
if a == 0:
print("The number is Zero") # Output: The number is Zero
elif a % 2 == 0:
print("The number is even") # Example Output: The number is even (if input is 4)
else:
print("The number is odd") # Example Output: The number is odd
# Q2: Student Result
p = 41
C = 56
M = 78
if p <= 40 or C <= 40 or M <= 40:
print("Student is fail") # Output: Student is pass (since all
scores > 40)
else:
print("Student is pass")
# While Loop to print even numbers from 1 to 20
x=1
while x <= 20:
if x % 2 == 0: # Check for even numbers
print(x) # Output: 2, 4, 6, ..., 20
x += 1
# Q3: Print all odd numbers from lower bound to higher bound
a = int(input("Enter lower number: ")) # Example Input: 3
b = int(input("Enter higher number: ")) # Example Input: 10
x=a
while x <= b:
if x % 2 != 0: # Check for odd numbers
print(x) # Example Output: 3, 5, 7, 9
x += 1
# For Loop Examples
tpl = (2, 4, 5, 6, 10)
for x in tpl: # Iterate through the tuple
print(x) # Output: 2, 4, 5, 6, 10
for x in range(5, 50):
print(x) # Output: 5, 6, 7, ..., 49
# Calculate the product of all numbers in a list
lst = [23, 3, 5, 2]
prod = 1
for x in lst:
prod *= x # Mul ply each element
print("Product of all the numbers in the list:", prod) # Output: 690
# Q4: Print the mul plica on table of 5
x=5
for a in range(1, 11):
b=x*a
print(x, "*", a, "=", b)
# Output: 5 * 1 = 5, 5 * 2 = 10, ..., 5 * 10 =
50
# Break and Con nue Examples
lst = [23, 3, 5, 2]
# Using break
for i in lst:
if i == 3:
break # Exit loop when i == 3
print(i) # Output: 23
# Using con nue
for i in lst:
if i == 3:
con nue # Skip the itera on when i == 3
print(i) # Output: 23, 5, 2
# Func on to calculate average
def avg(a, b):
return (a + b) / 2
print("Average of 10 and 20:", avg(10, 20)) # Output: Average of 10 and 20:
15.0
# Func on to perform mul ple calcula ons
def calci(a, b):
x=a+b
y=a-b
z=a*b
return x, y, z
result = calci(10, 20)
print("Calcula ons result:", result) # Output: Calcula ons result: (30, -
10, 200)
# Variable scope example
a = 100
def display():
y = 20
a = 90 # Local variable 'a'
print(a, y) # Output: 90 20
return a # Return local 'a'
z = display()
print("Returned value from display():", z) # Output: Returned value from
display(): 90
print("Global a:", a) # Output: Global a: 100
# Q5: Func on with nested func on
def displaying(name):
def message():
return "Hello"
result = message() + " " + name # Fixed concatena on
return result
Nameit = "Shivam"
print(displaying(Nameit)) # Output: Hello Shivam
# IMPORT STATEMENTS
from tkinter import Variable
from tkinter.font import names
from functools import reduce
import keyword
# LAMBDA EXPRESSIONS
# Square of a number using lambda
y = lambda x: x * x
print("Square of 10:", y(10)) # Output: Square of 10: 100
# Check if a number is even or odd using lambda with if-else
f = lambda x: 'Yes' if x % 2 == 0 else 'No'
print("Is 6 even?:", f(6)) # Output: Is 6 even?: Yes
# Doubling each element in a tuple
numbers = (1, 2, 3, 4)
doubled = tuple(map(lambda x: x * 2, numbers))
print(doubled) # Output: (2, 4, 6, 8)
# FILTER FUNCTION
lst1 = [10, 20, 40, 5]
result = list(filter(lambda x: x % 2 == 0, lst1))
print("Filtered even numbers:", result) # Output: Filtered even numbers: [10, 20,
40]
# MAP FUNCTION
result_map = list(map(lambda x: x * 2, lst1))
print("Doubled values:", result_map) # Output: Doubled values: [20, 40, 80, 10]
# REDUCE FUNCTION
lst = [1, 5, 6, 3, 5]
result_reduce = reduce(lambda x, y: x + y, lst)
print("Sum of all elements:", result_reduce) # Output: Sum of all elements: 20
# DECORATOR FUNCTION
# Basic decorator example
def decor(fun):
result = fun() * 2
return result
def num():
return 15
print("Result using decorator:", decor(num)) # Output: Result using decorator: 30
# Example with personalized gree ng decorator
def hello(name):
return 'Hello ' + name
def decor(func):
result = func('Shivam')
result += ', How are you?'
return result
answer = decor(hello)
print(answer) # Output: Hello Shivam, How are you?
# WORKING WITH KEYWORDS
print("List of Python keywords:", keyword.kwlist)
print("Total number of keywords:", len(keyword.kwlist))
# OBJECT-ORIENTED PROGRAMMING
# 1. Class Product
class Product:
def __init__(self):
self.name = 'iPhone'
self.descrip on = 'Expensive'
self.price = '80000'
p1 = Product()
print("Product name:", p1.name) # Output: Product name: iPhone
# 2. Class Course with mul ple instances
class Course:
def __init__(self, name, ra ng):
self.name = name
self.ra ng = ra ng
c1 = Course("Java course", [1, 2, 3, 4, 5])
c2 = Course("C++ course", [1, 2, 3, 4, 5])
print("Course 1 - Name:", c1.name, "Ra ngs:", c1.ra ng)
# Output: Course 1 - Name: Java course Ra ngs: [1, 2, 3, 4, 5]
print("Course 2 - Name:", c2.name, "Ra ngs:", c2.ra ng)
# Output: Course 2 - Name: C++ course Ra ngs: [1, 2, 3, 4, 5]
# 3. Course class with average ra ng calcula on
class Course:
def __init__(self, name, ra ng):
self.name = name
self.ra ng = ra ng
def average(self):
number_of_ra ngs = len(self.ra ng)
avg = sum(self.ra ng) / number_of_ra ngs
print("Average ra ng for", self.name, "is", avg)
c1 = Course("Java course", [1, 2, 3, 4, 5])
print("Course name:", c1.name) # Output: Course name: Java
course
c1.average() # Output: Average ra ng for Java course is
3.0
# STATIC FIELD / CLASS LEVEL FIELD
class Student:
major = "CSE" # Class variable
def __init__(self, rollno, name):
self.rollno = rollno # Instance variable
self.name = name # Instance variable
s1 = Student(1, "John")
s2 = Student(2, "Shivam")
print("Student 1 - Major:", s1.major, "Name:", s1.name)
# Output: Student 1 - Major: CSE Name: John
print("Student 2 - Major:", s2.major, "Name:", s2.name)
# Output: Student 2 - Major: CSE Name: Shivam
# GETTER AND SETTER METHODS (ENCAPSULATION)
class Programmer:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setSalary(self, salary):
self.salary = salary
def getSalary(self):
return self.salary
def setTechnologies(self, technologies):
self.technologies = technologies
def getTechnologies(self):
return self.technologies
p1 = Programmer()
p1.setName("John")
p1.setSalary(100)
p1.setTechnologies(["Python", "JavaScript"])
print("Programmer - Name:", p1.getName()) # Output: Programmer - Name: John
print("Programmer - Salary:", p1.getSalary()) # Output: Programmer - Salary: 100
print("Programmer - Technologies:", p1.getTechnologies())
# Output: Programmer - Technologies: ['Python', 'JavaScript']
# Impor ng required libraries
import numpy as np
import matplotlib.pyplot as plt
# 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])
# Plo ng the line graph
plt.plot(xpoints, ypoints)
plt. tle('Simple Line Plot')
plt.xlabel('X Points')
plt.ylabel('Y Points')
plt.show()
# Output: A line plot of given x and y points
# GDP of India Plot
# Data represen ng years and GDP growth
xdata = np.array([2020, 2021, 2022, 2024])
ydata = np.array([6.6, 7.7, 4.6, 5.8])
# Plo ng GDP with customiza ons
plt.plot(xdata, ydata, color='red', linewidth=2.5, alpha=0.8)
plt.grid(color='brown', linewidth=1.7, linestyle='--')
plt. tle('The GDP of India for the Given Years')
plt.xlabel('Years')
plt.ylabel('GDP Growth (%)')
plt.show()
# Output: A red line plot showing GDP growth vs years with a grid
# 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
# Histogram: Frequency Distribu on
# Data represen ng student marks
student_marks = np.array([22, 23, 4, 43, 56, 232, 5, 3])
# 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))
# Plo ng on first subplot
ax[0].plot(xpoints, ypoints, color='green')
ax[0].set_ tle('Subplot 1')
# Plo ng on second subplot
ax[1].plot(xpoints, ypoints, color='blue')
ax[1].set_ tle('Subplot 2')
plt.show()
# Output: Two subplots side by side with green and blue lines,
respec vely
# Electrical Circuit Calcula on
# Matrix represen ng the circuit
R = np.array([[1, -1, -1], [10, 20, 20], [0, 20, -30]])
# Voltage vector
V = np.array([0, 5, 7])
# Calcula ng current using matrix inversion
try:
Rinv = np.linalg.inv(R) # Inverse of resistance matrix
I = np.matmul(Rinv, V) # Current calcula on
print("Current through the circuit:", I)
except np.linalg.LinAlgError:
print("Matrix inversion failed. Circuit matrix may be singular.")
# Output: Current values through the circuit (Example: [0.42857143, 0.21428571, -
0.07142857])