PYTHON NOV 2023

Learn to Install Python from here: https://learn.swapnil.pw/python/pythoninstallation/

”’
print() – displays the content on the screen
functions have () after the name

python commands are case sensitive- Print is not same as print
”’

# idgjdsigjfigj
# comments mean that you are asking computer to ignore them

print(5)
print(5+3)
print(‘5+3’)
print(“5+3”)
print(‘5+2*3=’,5+2*3,“and 4*3=”,4*3)
print(“Hello How are you?”);print(‘Hello How are you?’)
# print always starts from a new line
# escape sequence: \n (newline) \t for tab spaces
print(“How are you doing? \nWhere are you \tgoing?”);
# What’s your name?
print(“What’s your name?”)
# He asked me,”What’s your name?”
print(“He asked me,\”What’s your name?\”,end=\n)

# He asked me,\”What’s your name?\”
print(“He asked me,\\\”What’s your name?\\\”,end=\n)
print(“Hello”,end=” – “)
print(“How are you?”)

print(“Basic data types in Python”)
# numeric – int (integer)- -99, -4,0,5,888: no decimal values
marks1 = 43

marks2 = 87
print(“Marks1 =”,marks1)
marks1 = 99
print(marks1)
# function: type() – it gives the datatype
print(type(marks1)) #<class ‘int’>

marks = 87.0 # <class ‘float’>
print(type(marks))

# complex: square root of -1: j
calc = 3j * 4j
print(calc) # 12 j-square = -12 + 0j
print(‘Data type of calc = ‘,type(calc))

# int float complex
a = –55
print(type(a))
a = –55.0
print(type(a))
a = –55j
print(type(a))

# str – string – text
print(“HELLO”)
name=“Sachin”
print(name)
print(“type = “,type(name))
name=‘Virat kohli leads \nbangalore team in IPL’
print(name)
print(“type = “,type(name))

name=”’Rohit is the captain
of Indian team
He opens in the ODIs”’
print(name)
print(“type = “,type(name))

name=“””Rohit led the Indian team
in 2023 ODI World cup and
reached finals”””
print(name)
print(“type = “,type(name))

#5th data type – Bool boolean – 2 values: True and False
val1 = True # False
print(type(val1))

# Formatting the print statement
quantity = 12
price = 39
total = quantity * price
print(“Total cost of”,quantity,“books which costs per copy Rs”,price,“will be Rs”,total)
# f – string is used to format the output
print(f”Total cost of {quantity} books which costs per copy Rs {price} will be Rs {total})

# f-string is used to format float values as well
quantity, total = 12, 231.35
price = total/quantity
print(f”Total cost of {quantity} books which costs per copy Rs {price:.1f} will be Rs {total})

# f-string for string values
name,country,title=“Rohit”,“India”,“Captain”
print(f”Player {name:<12} plays for {country:^10} and is the {title:>15} of the team”)
name,country,title=“Mangbwabe”,“Zimbabwe”,“Wicket-keeper”
print(f”Player {name:<12} plays for {country:^10} and is the {title:>15} of the team”)

### INPUT
## to take input from the user
## input can take no or at max 1 parameter
inp_val = int(input(“Enter first number: “))
print(inp_val)
print(“Datatype of input=”,type(inp_val))
inp_val2 = int(input(“Enter second number: “))
print(“Sum of two numbers=”,inp_val+inp_val2)

## change below programs to accept the values from the user using input

# 1. write a program to calculate area and perimeter of a rectangle
l=50
b=20
area = l*b
peri = 2*(l+b)
print(f”Area and perimeter of a rectangle with length {l} and breadth {b} is {area} and {peri} respectively”)
# 2. write a program to calculate area and perimeter of a square
#### Assignment ##
# 3. write a program to calculate volume and surface area of a cone
#### Assignment ##
# 4. write a program to calculate volume and surface area of a cylinder
#### Assignment ##
# 5. write a program to calculate area and circumference of a circle
r=50
pi = 3.12
area = pi*r**2
cir = 2*pi*r
print(f”Area and circumference of a circle with radius {r} is {area} and {cir} respectively”)
# input() – read input from the user
num1 = int(input(“Enter first number:”))
print(“type = “,type(num1))
num2 = int(input(“Enter second number:”))
print(“Sum is “,num1+num2)

# calculate area and perimeter for a rectangle
length=float(input(“Enter length of the rectangle:”))
breadth=float(input(“Enter breadth of the rectangle:”))
perimeter = (length+breadth)*2
print(“Perimeter of the rectangle is”,perimeter)

# int() -to convert to int
#similarly you can use float(), str() bool() complex()
# operators:
# Arithmatic operators: + – * / ** // % (modulo – remainder)
num1 = 11 #assignment operator = we are assigning value 11 to num1
num2 = 3
print(num1 + num2)
print(num1 – num2)
print(num1 * num2)
print(num1 / num2)
print(num1 ** num2) #power
print(num1 // num2) #integer division
print(num1 % num2) # remainder

## relational operators (comparision)
## > >= < <= == != (is it?)
## output is always bool (True or False)
num1,num2,num3 = 11,9,11
print(“Relational : “, num1 > num2) # T
print(“Relational : “, num1 >= num3) # T
print(“Relational : “, num1 < num2) # F
print(“Relational : “, num1 <= num3) # T
print(“Relational : “, num1 == num2) # F
print(“Relational : “, num1 == num3) # T
print(“Relational : “, num1 != num2) # T
print(“Relational : “, num1 != num3) # F
print(“Relational : “, num1 > num3) # F
print(“Relational : “, num1 < num3) # F

# Logical operators: and or not
# input and output are both bool values
”’
Prediction 1: Rohit and Ishan will open the batting
Prediction 2: Rohit or Ishan will open the batting
Actual: Rohit and Gill opened the batting
Prediction 1 False
Prediction 2 True

Truth Table: AND (*)
T and T = T
T and F = F
F and T = F
F and F = F

OR (+)
T or T = T
T or F = T
F or T = T
F or F = F

not T = F
not F = T
”’
num1,num2,num3 = 11,9,11
print( not(num1 > num2 and num1 >= num3 or num1 < num2 or num1 <= num3 and num1 == num2
and num1 == num3 or num1 != num2 or num1 != num3 and num1 > num3 or num1 < num3))
# T and T or F or T and F and T or T or F and F or F
# T or F or F or T or F or F
# T
# int to binary and vice-versa
num1 = 34
print(“Binary of num1=”,bin(34))
num2 = 0b100010
print(“Integer of num2=”,int(num2))
print(oct(34)) # 0o42
print(hex(34)) # 0x22

#Bitwise: & (bitwise and) | (bitwise or) >> (right shift) << (left shift)
num1 = 23 #0b10111
num2 = 31 #0b11111
print(bin(num1),“and”,bin(num2))
”’
bitwise &
10111
11111
——–
10111
”’
print(int(0b10111)) # 23
print(“23 & 31 = “,23 & 31) # 23

”’
bitwise |
10111
11111
——–
11111
”’
print(“23 | 31 = “,23 | 31) # 31

”’
THTO
54320
”’
print(“23 << 2:”,23 << 2) # 92
”’
1011100 << 2
”’
print(int(0b1011100))

print(“23 << 2:”,23 >> 2) # 5
”’
101
”’
print(int(0b101))

# conditions
”’
display message after checking if the student has passed or failed the exam
condition is avg >= 40 to pass

if command checks the condition is Python
syntax:
if condition :
# perform things when the condition is true


Title
* sub
o ss
i.
ii.
”’
avg =82
if avg >=40:
print(“Congratulations!”)
print(“You’ve passed!”)

print(“Thank you”)
”’
Check avg and print Pass or Fail
”’
avg = 19
if avg >=40:
print(“Pass”)
else:
print(“Fail”)
# IF – condition – will always result into True or False

num1 = 71.000000001
num2 = 71
# if num1 is greater than num2 then I want to print How are you? otherwise do nothing
if num1 > num2:
print(“How are you?”)
print(“Where are you going?”)

print(“Thank you”)

# if num1 is greater than num2 then I want to print How are you? otherwise print Do nothing
if num1 > num2:
print(“How are you?”)
print(“Where are you going?”)
else:
print(“Do Nothing”)

”’
Input a number from the user and check if its +ve, -ve or zero
”’
val = int(input(“Enter a number: “))
print(“Type of data =”,type(val))

# IF – ELIF – ELSE
if val==0: # == is to check the equality
print(“Its Zero”)
elif val <= 0:
print(“Its -ve number”)
else:
print(“Its +ve number”)

if val==0:
print(“Its Zero”)
if val<=0:
print(“Its -ve number”)
if val>=0:
print(“Its +ve number”)

”’
Write a program to take 2 inputs from the user and check if the first
number is greater, smaller or equal to the second one
”’
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
if num1 > num2:
print(num1,“is greater than”,num2)
elif num1 < num2:
print(num1,“is less than”,num2)
else:
print(num1, “and”, num2,“are equal”)

”’
WAP to take marks in 5 subjects as input, calculate total and average
and assign grade based on below condition:
a. avg 85 – Grade A
b. avg 70-85 – Grade B
c. avg 60-70 – Grade C
d. avg 50-60 – Grade D
e. avg 40 -50 – Grade E
f. avg <40 – Grade F
”’
marks1 = float(input(“Enter the marks in subject 1: “))
marks2 = float(input(“Enter the marks in subject 2: “))
marks3 = float(input(“Enter the marks in subject 3: “))
marks4 = float(input(“Enter the marks in subject 4: “))
marks5 = float(input(“Enter the marks in subject 5: “))
total = marks1 + marks5 + marks4 + marks3 + marks2
avg = total / 5
print(f”Total marks is {total:.2f} and average is {avg:.2f})
if avg>=85:
print(“Grade A”)
elif avg>=70:
print(“Grade B”)
elif avg>=60:
print(“Grade C”)
elif avg>=50:
print(“Grade D”)
elif avg>=40:
print(“Grade E”)
else:
print(“Grade F”)

”’
Let’s write a program to read length and breadth from the user
check if its square or rectangle and calculate area and perimeter
”’
length = int(input(‘Enter the length: ‘))
breadth = int(input(‘Enter the breadth: ‘))
#and & or are logical operator which connects you conditonal statements
# and: both the statements need to be true for True else its false
# or: both the statements need to be false for False else its True
if length>0 and breadth >0:
print(“Rectangle and Square both possible”)
if length==breadth:
print(“Square”)
print(f”Area is {length**2} and the perimeter is {4*length})
else:
print(“Rectangle”)
print(f”Area is {length * breadth} and the perimeter is {2 * (length+breadth)})
else:
print(“Neither Rectangle nor Square possible”)
”’
check if a number is positive, negative or zero
if the number is -ve, find the square root
if number is positive, check if its 2 digit or not
if 2 digits then interchange the values
otherwise, check if its divisible by 15,
”’

num1 = int(input(“Enter a number: “))
if num1<0:
print(“This is negative”)
print(f”Square root of {num1} is {num1**0.5})
elif num1==0:
print(“This is zero”)
else:
print(“This is positive”)
if num1>9 and num1<100:
#interchange the values: eg 35 = 53
# divide number by 10 =
d = num1 // 10
r = num1 % 10
new_num1 = r*10+d
print(f”{num1} is now made into {new_num1})

else:
if num1 % 15==0: # % mod – will give you remainder
print(“Number is divisible by 15”)
else:
print(“Number is not divisible by 15”)

#LOOPS – repeat the give block of code multiple times
# when you know exactly how many times to run – for
# repeatition is done based on a certain condition – while

# range(start,end,increment)- generates range of values from start upto end
# by increasing each element ny increment
# range(6,18,3): 6,9,12, 15
# range(start,end): increment is default 1
# range(15,19): 15,16,17,18
# range(end): start = 0, increment = 1
# range(6): 0, 1, 2, 3, 4, 5
#print(), input(), type(), int(),str(),complex(),bool(), float()

for var in range(6,18,3):
print(“Hello from the loop!”)
print(“Value of var is”,var)

for count in range(15,19):
print(“Hello from the loop2!”)
print(“Value of var is”,count)

for count in range(4):
print(“Hello from the loop3!”)
print(“Value of var is”,count)

###
for i in range(5):
print(“*”,end=” “)
print()
for i in range(1,101):
print(i,end=“, “)
print()
”’
Generate odd numbers between 1 and 30
”’
for i in range(1,30,2):
print(i,end=“, “)
print()
”’
Generate first 10 even numbers
”’
start = 0
for i in range(10):
print(start,end=“, “)
start=start+2

print()
# for loop examples
”’
Print all the numbers between 1 and 1000 which is perfectly divisible by 19 and 51
”’
start,end = 1, 10001
num1,num2 = 19,51
for n in range(start,end):
if n%num1==0 and n%num2==0:
print(n,end=“, “)
print()
”’
Generate prime numbers between 10000 and 50000
”’
start,end = 40000, 42000
for n in range(start,end):
isPrime = True
for num in range(2,n//2+1):
if n %num==0:
isPrime = False
break
if isPrime:
print(n,end=“, “)

”’
Print different * patterns
”’
for i in range(5):
print(“*”)

”’
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
”’
for j in range(5):
for i in range(5):
print(“*”,end=” “)
print()

”’
*
* *
* * *
* * * *
* * * * *
”’

for j in range(5):
for i in range(1+j):
print(“*”,end=” “)
print()

”’
* * * * *
* * * *
* * *
* *
*
”’

for j in range(5):
for i in range(5-j):
print(“*”,end=” “)
print()
”’
* * * * *
* * * *
* * *
* *
*
”’

for j in range(5):
for i in range(j):
print(” “,end=“”)
for i in range(5-j):
print(“*”,end=” “)
print()

”’
Assignment:
*
* *
* * *
* * * *
* * * * *

Solve assignments from the website
”’
## WHILE Loop
”’
WAP to print hello till user says no
”’
while True:
print(“HELLO 1”)
usr_inp=input(“Enter N to stop: “)
if usr_inp.lower()==“n”:
break
print(“====”)
usr_inp=input(“Enter N to stop: “)
while usr_inp.lower() !=‘n’:
print(“HELLO 2”)
usr_inp = input(“Enter N to stop: “)
”’
A company offers dearness allowance (DA) of 40% of basic pay and house
rent allowance (HRA) of 10% of basic pay. Input basic pay of an employee,
calculate his/her DA, HRA and Gross pay (Gross = Basic Pay + DA+ HRA).
a. Modify the above scenario, such that the DA and HRA
percentages are also given as inputs.
b. Update the program such that the program uses a user-defined
function for calculating the Gross pay. The function takes Basic pay,
DA percentage and HRA percentage as inputs and returns the gross pay.
”’
#Case 1
basic_pay = int(input(“Enter your basic pay:”))
da = basic_pay *0.4
hra = basic_pay*0.1
gross_pay = basic_pay + da + hra
print(“Your gross pay for this month is Rs”,gross_pay)

#Case 2
basic_pay = int(input(“Enter your basic pay:”))
da = int(input(“Enter the dearness allowance (%): “))
da = da/100
hra = int(input(“Enter the House rent allowance (%): “))
hra = hra/100
gross_pay = basic_pay + basic_pay*da + basic_pay*hra
print(“Your gross pay for this month is Rs”,gross_pay)
#case 3

# defining a user defined function (udf)
# input taken by the function – passing the value
# and anything returned from the function – function returns the output
def calc_gross_pay(bp,da,hra=10):
hra = hra / 100
da = da / 100
gross_pay = bp + bp * da + bp * hra
return gross_pay


basic_pay = int(input(“Enter your basic pay:”))
da = int(input(“Enter the dearness allowance (%): “))
hra = int(input(“Enter the House rent allowance (%): “))

result = calc_gross_pay(basic_pay,da,hra)
print(“Your gross pay for this month is Rs”,result)

result = calc_gross_pay(basic_pay,da)
print(“Your gross pay with default hra for this month is Rs”,result)

result = calc_gross_pay(da=da,bp=basic_pay,hra=hra)
print(“Your gross pay with non-positional for this month is Rs”,result)

# required positional arguments
# default (non-required)

”’
You have a monthly income of Rs 1100. Your monthly outgoings are as follows.
• Rent – Rs.500
• Food – Rs.300
• Electricity – Rs.40
• Phone – Rs 60
• Cable TV – Rs 30.
Calculate the Monthly Expenses and the remainder (what’s left over each month).
a. Modify the above program by inputting the income as well as values
for expenses and calculate Monthly expense.
b. Include a function to check whether you will have savings or you
have to borrow money based on the monthly income and total expenses.
The function should print an appropriate message for each case.
”’
#case 1
income = 1100
Rent=500
Food=300
Electricity=40
Phone=60
Cable=30
expenses = Rent+Food+Electricity+Phone+Cable
remainder = income-expenses
print(“Your expenses for this month is”,expenses)
print(“You remainder for this month is”,remainder)

#case 2
income = int(input(“Enter your Income:”))
Rent= int(input(“Enter your rent:”))
Food= int(input(“Enter your food expenses:”))
Electricity= int(input(“Enter your Electricity charges:”))
Phone= int(input(“Enter your Phone expenses:”))
Cable= int(input(“Enter your Cable TV expenses:”))
expenses = Rent+Food+Electricity+Phone+Cable
remainder = income-expenses
print(“Your expenses for this month is”,expenses)
print(“You remainder for this month is”,remainder)


# case 3
def check_remainder(income,expenses):
remainder = income-expenses
if remainder<0:
print(f”You need to borrow Rs {remainder} for this month”)
elif remainder>0:
print(f”You have a savings of Rs {remainder} for this month”)
else:
print(“This month you neither have savings nor need to borrow any money”)

income = int(input(“Enter your Income:”))
Rent= int(input(“Enter your rent:”))
Food= int(input(“Enter your food expenses:”))
Electricity= int(input(“Enter your Electricity charges:”))
Phone= int(input(“Enter your Phone expenses:”))
Cable= int(input(“Enter your Cable TV expenses:”))
expenses = Rent+Food+Electricity+Phone+Cable
check_remainder(income,expenses)


########## PRACTICE #################

# defining a user defined function (udf)
# input taken by the function – passing the value
# and anything returned from the function – function returns the output
def calc_gross_pay(n1,n2):
print(“Hi, I am in calc_gross_pay_function”)
total = n1 + n2
#print(total)
return total


val1 = 100
val2 = 150
ret_val = calc_gross_pay(val1,val2) #calling the function pass the value
print(“Value returned from the function is”,ret_val)
val1 = 10
val2 = 50
result = calc_gross_pay(val1,val2) #calling the function pass the value
print(“Value returned from the function is”,result)


# Guessing the number game: Computer v Human
# computer will think of the number and we will guess it
import random
num1 = random.randint(1,100)
attempts = 0
fouls = 0
while True:
guess = int(input(“Guess the number between 1 and 100: “))
if guess<1 or guess>100:
print(“Your guess is outside the valid number range! “,end=” “)
if fouls==0:
print(“This is your first foul, so you can continue but another foul will make you lose.”)
else:
print(“This is your second foul, sorry you lose.”)
break
fouls+=1
continue
attempts+=1
if num1 == guess:
print(f”You guessed it right in {attempts} attempts!”)
break
elif num1 > guess:
print(“Sorry! Its Incorrect! Guess a higher number”)
else:
print(“Sorry! Its Incorrect! Guess a lower number”)

#############
# Guessing the number game: Computer v Computer
# computer will think of the number and it will only guess it
import random
import time # date, datetime

start = time.time()
### finding average attempts of running this program
total_attempts = 0
for i in range(10000):
num1 = random.randint(1,100)
attempts = 0
fouls = 0
low,high=1,100
while True:
guess = random.randint(low,high)
if guess<1 or guess>100:
print(“Your guess is outside the valid number range! “,end=” “)
if fouls==0:
print(“This is your first foul, so you can continue but another foul will make you lose.”)
else:
print(“This is your second foul, sorry you lose.”)
break
fouls+=1
continue
attempts+=1
if num1 == guess:
print(f”You guessed it right in {attempts} attempts!”)
total_attempts+=attempts # a+=b => a = a+b ; a/=c => a =a/c
break
elif num1 > guess:
print(“Sorry! Its Incorrect! Guess a higher number”)
low=guess+1

else:
print(“Sorry! Its Incorrect! Guess a lower number”)
high=guess-1
end = time.time()
print(f”On average this program has taken {total_attempts/10000:.1f} attempts”)
print(f”Total time taken by the program to run 10000 times is {end-start} seconds”)

#############
# LIST
# collections: list, tuple, sets, dictionary, numpy, pandas
l1 = [10,20,“30”,False,“Hello”,[1,3,5]]
print(“Type of the variable = “,type(l1))
print(“Size/Length of the list = “,len(l1))
# read the values of a list:
print(l1[0])

# LIST: ordered mutable linear collection
list1 = [34,“Hello”,[2,3,4], True, False, 45]

#indexing – forward
print(“First value – “,list1[0])
print(“third value – “,list1[2])
list1[0] = 55.5
print(list1)
# backward indexing – right to left
print(“Last element – indexed as -1: “,list1[-1])
print(“First value – “,list1[-3])
print(“1,3,5 values – “,list1[0],list1[2],list1[4])
#
print(“First to third values – “,list1[0:3],list1[:3])
print(“First to third values – “,list1[0:5:2])
print(“First to last values – “,list1[:])
print(“last three values – “,list1[-3:])

list2 = [3,4,5]
list3 = list1 + list2
print(list3)
list4 = list2*3
print(“List4 = “,list4)

## using list in a for loop
for counter in list1:
print(“HELLO : “,counter,“has a data type of”,type(counter))


## Properties of a list
l1 = [2,3,4]
l1.pop() #pop without index will remove last element from the list
print(“1. l1 = “,l1)
l1.pop(0) #pop will remove the element at the given index
print(“2. l1 = “,l1)
l1.append(5) #append always adds the value at the end of the list
print(“3. l1 = “,l1)
l1.append(1)
print(“4. l1 = “,l1)
l1.append(8)
print(“5. l1 = “,l1)
l1.sort() #default it sorts in ascending
print(“6. l1 = “,l1)
l1.sort(reverse=True) #will sort in descending
print(“6. l1 = “,l1)
## creating duplicate list
l2 = l1 #deep copy – both variables point to the same data
l3 = l1.copy() # shallow copy – you create a different copy
print(“11 L1 = “,l1)
print(“11 L2 = “,l2)
print(“11 L3 = “,l3)
l1.append(33)
l2.append(43)
l3.append(53)
l1.append(3)
print(“12 L1 = “,l1)
print(“12 L2 = “,l2)
print(“12 L3 = “,l3)
# (value, start, stop) – whats the index of the value between start and stop
# start =0, stop default is -1
print(“Index of 3: “,l1.index(3,3,10))
# REMEMBER: Index will throw error when value not the in list
# count() will do the count and its used exactly like index
num= l1.count(3)
print(“Number of 3 in the list is”,num)
l1_dup = l1[3:11]
num = l1_dup.count(3)
# above 2 statements can be clubbed as one shown below:
num = l1[3:11].count(3)
print(“Number of 3 in the given range is”,num)
print(“List before reverse is: “,l1)
l1.reverse()
print(“List after reverse is: “,l1)

# + will perform: c = a+ b
#extend will be like a = a+b
list4 = [11,22,33]
l1.extend(list4)
print(“L1 after extend: “,l1)

#pop takes index – remove takes value to remove/delete from the list
l1.remove(3)
cnt = l1.count(18)
if cnt>0:
l1.remove(18)
print(“1. After remove: “,l1)
#append() will always add at the end, insert takes the position also along with the values
# first it takes index, then the value to add
l1.insert(2,32)
print(“1. INSERT 1=”,l1)
l1.insert(2,42)
print(“2. INSERT 2=”,l1)
l1.clear() # will clear the data from the list
print(“99 List1 = “,l1)
# I want to input marks of 5 students in 5 subjects

students_marks = []

for j in range(5):

all_marks=[]
for i in range(5):
marks = int(input(“Enter the marks in subject “+str(i+1)+“: “))
all_marks.append(marks)
print(f”Marks obtained by student {j+1}: {all_marks})
students_marks.append(all_marks)
print(“Marks obtained by students are:\n,students_marks)

students_marks=[[66, 55, 77, 88, 99], [45, 65, 76, 78, 98],
[90, 80, 45, 55, 55], [54, 64, 74, 84, 94],
[34, 53, 99, 66, 76]]
subjects = [“Maths”,“Stats”,“Physics”,“Programming”,“SQL”]
for k in range(len(students_marks)):
total = sum(students_marks[k])
print(f”Total marks obtained by student {k+1} is {total} and average “
f”is {total/len(students_marks)})
max_marks = max(students_marks[k])
print(f”Highest marks obtained by student {k + 1} is {max_marks}
f”in subject {subjects[students_marks[k].index(max_marks)]})


# TUPLE: linear ordered immutable collection

# tuple declared using ()
t1 = ()
print(“Type of t1 = “,type(t1))
t1 = (“hello”,) # (5+3)*2 =
print(t1)
print(“Type of t1 = “,type(t1))

t1 = (5,4,6,9,1)
print(t1)
print(“Type of t1 = “,type(t1))
# indexing is exactly same as list
#t1[0]=8 – ‘tuple’ object does not support item assignment

for i in t1:
print(“from tuple: “,i)

t1=list(t1) # converting tuple to list
t1=tuple(t1) #converting list to tuple

############
## STRING – str
###########
# there is no difference between declaring string using ‘ or ” quotes
# and there is no difference between ”’ and “”” strings
# ‘ or ” declares only 1 line of text but ”’ and “”” can be used
# to declare multi line of text
str1 = “hello”
#str1[0]=”H” – ‘str’ object does not support item assignment
# strings are immutable
# strings are same as list or tuple
# 0 to n-1 indexing and -1 to -n indexing

str2 = ‘hi there’

str3 = “””How are you?
Where are you?
What are you doing?”””

str4 = ”’I am fine
I am here
I am doing nnothing”’
print(type(str1), type(str2),type(str3), type(str4))
print(“Str1 \n————“)
print(str1)
print(“Str2 \n————“)
print(str2)
print(“Str3 \n————“)
print(str3)
print(“Str4 \n————“)
print(str4)

str11=str1.upper()
print(str1,str11)
str22 = “Hello ” + “There ” * 2
print(“Str22 = “,str22)
# str are used in for loop exactly same way as list or tuple
for i in str1:
print(“STR = “,i)
# Strings – in python
str1 = “HELLO”
str3 = ”’How Are YoU?”’
str2 = “123456”
# methods with is…() – is it … ?
print(“isupper: “,str1.isupper())
print(“islower: “,str3.islower())
print(“istitle: “,str3.istitle())
print(“isnumeric: “,str2.isnumeric())
print(“”,str2.isalnum())
print(“title: “,str3.title())
print(“lower: “,str3.lower())
print(“upper: “,str3.upper())

str3 = ”’How Are YoU?”’
print(“startswith: “,str3.startswith(“H”))
print(“endswith: “,str3.endswith(“?”))
usname = input(“Enter your username (only text and numbers allowed: “)
if usname.isalnum():
print(“Username accepted”)
else:
print(“Invalid username!”)
num1 = input(“Enter length: “)
if num1.isnumeric():
num1 = int(num1)
else:
print(“Invalid number”)

str4=“abcdefghijklmnopqrstuvwxyz”
# I want to check if the starting
# character is A and ending is Z
if str4.upper().startswith(“A”) and str4.upper().endswith(“Z”):
print(“Your condition is true”)
else:
print(“Incorrect condition”)

while True:
inp = input(“Enter Yes to stop and any key to continue: “)
if inp.title()==“Yes”:
break



str5 = “Enter Yes to stop and any key to continue: “
str_words = str5.split()
print(str_words)
# join() will take list as input
print(“JOIN: “,” “.join(str_words))
str_hyphen = “-:-“.join(str_words)
print(“New Statement: “,str_hyphen)
# need to split this special text
str_words = str_hyphen.split(“-:-“)
print(“STR HYPHEN: “,str_words)

str1 = “How are you going?”
str1 = str1.replace(“g”,“d”)
print(“1. Str1 = “,str1)

str1 = “How are you going you?”
str1 = str1.replace(“g”,“d”,1)
print(“2. Str1 = “,str1)

# you in str1 or not
# -1 indicates value not found
# positive number indicates first matching index
print(str1)
print(str1.upper().find(“YOU”,9,21))

str1 = ” How are you going you? “
print(str1.strip())
str1 = str1.split()
str1 = ” “.join(str1)
print(str1)

######### DICTIONARY ##########
## mutable unordered collection: pair of key and value (key:value)
dict1 = {1:“Hello”,“Name”:“Sachin”,“Runs”:35000}
print(dict1)
print(dict1[1])
print(dict1[“Runs”])
print(dict1.values())
print(dict1.keys())
print(dict1.items())

# Dictionary: immutable unordered collection
dict1 = {}
print(“Type of dictionary: “,type(dict1))

t_dict ={“Name”:“Sachin”}
dict1.update(t_dict)
print(dict1)

”’
Write a program to store marks of 5 subjects along with names
”’
master_data = {}
for i in range(3):
name=input(“Enter the student’s name: “)
marks = []
for j in range(5):
m1=int(input(“Enter the marks in Subject “+str(j+1)+“: “))
marks.append(m1)
t_dict={name:marks}
master_data.update(t_dict)

#
print(“The details are:\n,master_data)
”’
{‘Sachin’: [56, 76, 39, 76, 54], ‘Virat’: [89, 90, 33, 59, 90], ‘Mahi’: [88, 77, 99, 88, 99]}
”’
data = {‘Sachin’: [56, 76, 39, 76, 54],
‘Virat’: [89, 90, 33, 59, 90],
‘Mahi’: [88, 77, 99, 88, 99]}
print(list(data.keys())[1])

for k in data.keys():
print(k)

# deep & shallow
data2 = data # both will point to the same memory location
data3 = data.copy() # shallow – create photocopy- another dict object

data2.update({‘Rohit’:[66,67,78,77,82]})
print(“Data: “,data)
print(“Data 2: “,data2)
print(“Data 3: “,data3)

#SETS – linear mutable unordered collection

set1 = set({})
print(“Set1 = “,set1)
set1.add(“Apple”)
print(“Set1 = “,set1)

set1 = {1,3,5,7,9}
print(‘0. SET1: ‘,set1)
set2 = {3,4,5,6,7}


# properties of sets
print(“# Union”)
print(set1 | set2)
set3 = set1.union(set2)
print(set3)
print(“#Intersection”)
print(set1 & set2)
set3 = set1.intersection(set2)
print(set3)

print(“# Difference”)
print(set1 – set2)
set3 = set1.difference(set2)
print(set3)
print(set2 – set1)
set3 = set2.difference(set1)
print(set3)
print(“#Symmetric difference”)
print(set1 ^ set2)
set3 = set1.symmetric_difference(set2)
print(set3)

set1.remove(7)
print(“1. Set1:”, set1)
set1.pop()
print(“2. Set1:”, set1)
set1.clear()
print(“3. Set1:”, set1)

### List, Tuple, Set – they can be converted into each other format
l1=[1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
l1=list(set(l1))
print(l1)

###########
## Functions: user defined functions
def whatever():
print(“Hello”)
print(“Hello 2”)
print(“hello 3”)

whatever()

## 4 types:
# required positional parameters
# default keyword
# variable length paramets
# Functions
”’
Write a function to check if the number is prime or not
and use this to generate prime numbers
”’
def check_prime(val=53):
”’
This is a user defined function which takes
a value as input and checks if its a prime or not
@Written by Sachin Kohli
:param val:
:return:
”’
isPrime = True
for i in range(2,val//2+1):
if val%i==0:
isPrime = False
break
”’
if isPrime:
print(f”{val} is a prime number”)
else:
print(f”{val} is not a prime number”)
”’
return isPrime
# required positional argument
# default
# keyword

# check if val1 is greater than val2 then subtract
#otherwise add them
#SyntaxError: non-default argument follows default argument
def myfunction(val1, val2=50):
”’

:param val1:
:param val2:
:return:
”’
print(f”input values are: {val1} and {val2})
if val1 > val2:
print(“Subtraction = “,val1-val2)
else:
print(“Addition = “,val1+val2)

# write a function to add all the given numbers
#* against the argument makes it take values as a tuple
#** against the argument makes it take values as a dictionary
def add_all_num(*values, **data):
print(“add_all_num: values Values passed are: “,values)
print(“add_all_num: **data Values passed are: “, data)

if __name__==“__main__”: # current file is running
res = check_prime(41)
myfunction(43,33)
myfunction(val2=10,val1=20) #keywords, use exact same variable name
res = check_prime()
add_all_num(5,6,10,12,15, name=“Sachin”, game=“Cricket”,runs=50000)

”’ generate prime numbers between 10,000 to 15,000”’
for num in range(10000,15001):
res = check_prime(num)
if res:
print(num,end=“, “)
print()

print(“#################”)
print(help(input))
print(“——————–“)

print(input.__doc__)
print(“#################”)
print(check_prime.__doc__)

else:
print(“Thanks for using my program”)
# Class and Objects

class Books:
#functions which are part of a class are called methods
# members of class can be variables and methods
#object level members & class level members
total_books = 0

def __init__(self,title,author,price):
self.title = title
self.author = author
self.cost = price
Books.total_books +=1

def print_info(self):
print(“Title of the book is”,self.title)
print(“Author of the book is”, self.author)
print(“Cost of the book is”, self.cost)

@classmethod
def print_total(cls):
print(“Total books in the library are”,cls.total_books)


class Library:
total_lib = 0

def __init__(self,name,loc,pincode):
self.name = name
self.location = loc
self.pin = pincode

def print_info(self):
print(“Library: “,self.name)
print(f”Location: {self.location}{self.pin})

if __name__==“__main__”:
# CREATE OBJECT OF CLASS BOOKS
book1 = Books(“Python Programming”,“Sachin”,399)
book2 = Books(“SQL Programming”,“Virat”,299)
#creating objects call __init__() automatically
book3 = Books(“Machine Learning”,“Rohit”,499)
#book1.add_info(“Python Programming”,”Sachin”,399)
#book2.add_info(“SQL Programming”,”Virat”,299)
#book3.add_info(“Machine Learning”,”Rohit”,499)
book2.print_info()

Books.print_total()
book1.print_total()
book2.print_total()
book3.print_total()

###############################
###### Another file
###############################
import prog1

b1 = prog1.Books(“Data Analytics”, “Saurav”, 298)
b1.print_info()
l1 = prog1.Library(“ABC International Library”, “Hyderabad”, 500081)
l1.print_info()

”’
Create a class called MyMathOps and add functionalities for
Addition, Subtraction, Power, Multiplication and Division
You should have following methods:
1. init() – to get 2 values
2. calc_add() – perform addition
3. display_add() – to print total
4. calc_sub() – perform addition
5. display_sub() – to print total
6. calc_power() – perform addition
7. display_power() – to print total
8. calc_mul() – perform addition
9. display_mul() – to print total
10. calc_div() – perform addition
11. display_div() – to print total
”’
”’
Properties of class & objects:
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

#Accessibility: public (var), private (__var), protected (_var)
”’
#magazines
class LibraryContent:
def __init__(self,title,price):
self.title = title
self.cost = price

def __print_data(self):
print(“data from Library Content”)

def print_info(self):
print(“info from Library content”)

def display_something(self):
print(“Do Nothing”)
class Magazines(LibraryContent):
total_mags = 0
def __init__(self,title,issn,price):
LibraryContent.__init__(self, title, price)
self.issn = issn
Books.total_books +=1

def print_info(self):
print(“Title of the book is”,self.title)
print(“ISSN of the book is”, self.issn)
print(“Cost of the book is”, self.cost)

@classmethod
def print_total(cls):
print(“Total books in the library are”,cls.total_books)

class Books(LibraryContent):
#functions which are part of a class are called methods
# members of class can be variables and methods
#object level members & class level members
total_books = 0

def __init__(self,title,author,price):
LibraryContent.__init__(self,title,price)
self.author = author
Books.total_books +=1

def print_info(self):
print(“Title of the book is”,self.title)
print(“Author of the book is”, self.author)
print(“Cost of the book is”, self.cost)

@classmethod
def print_total(cls):
print(“Total books in the library are”,cls.total_books)


class Library:
total_lib = 0

def __init__(self,name,loc,pincode):
self.name = name
self.location = loc
self.pin = pincode

def print_info(self):
print(“Library: “,self.name)
print(f”Location: {self.location}{self.pin})

if __name__==“__main__”:
m1 = Magazines(“International Journal for Robotics”,“247-9988”,19800)
m1.print_info()
b1 = Books(“Python Book”,“Virat”,299)
b1.print_info()
m1.print_info()
#m1.__print_data()
#b1.print_data()
m1.display_something()

############ ANOTHER FILE #################
#Working with files:
# modes: r(read), w(write), a (append)
# r+, w+, a+

filename = “17DEC.txt”
fileobj = open(filename,“a+”) #by default read mode
fileobj.write(”’Twinkle Twinkle little star
How I wonder what you are”’)
fileobj.seek(0)
fileobj.write(”’Twinkle X Twinkle X little star
How I wonder what you are”’)
cont = fileobj.read()
print(cont)
fileobj.close()
stamp_5 = 2
stamp_2 = 2
stamp_1 = 2
total = 51
stamp_1+=3

rest_amount = total – (stamp_5*5 +stamp_2*2+stamp_1*1)
# we need to distribute rest_amount to 5,2,1
more_5 =rest_amount//5
stamp_5 +=more_5
rest_amount = rest_amount%5

more_2 =rest_amount//2
stamp_2 +=more_2
rest_amount = rest_amount%2
stamp_1+=rest_amount

print(f”Rs 5 ={stamp_5}, Rs 2 = {stamp_2}, Rs 1 = {stamp_1})
l1 = [10,40,20,50,30,60]
# l1 = [10,20,30,40,50,60]
”’
5
4
3
2
1
0
”’
#Print – Bubble Sort
l1 = [60,50,40,30,20,10]
for i in range(len(l1)-1):
for j in range(len(l1)-1-i):
if l1[j] > l1[j+1]:
l1[j],l1[j + 1] = l1[j + 1], l1[j]
print(“Sorted L1 = “,l1)

l1 = [10,40,20,50,30,60]
l1 = [60,50,40,30,20,10]
#Print – Selection Sort
for i in range(len(l1)-1):
for j in range(1+i, len(l1)):
if l1[i] > l1[j]:
l1[i],l1[j] = l1[j], l1[i]
print(“Sorted L1 = “,l1)

## if 55 is in the list or not
element = 50
l1 = [10,40,20,50,30,60]
found = False
for i in l1:
if element==i:
found = True
if found:
print(“Element is in the list!”)
else:
print(“Element is not in the list”)
# sequential sort – method
found = False
for i in range(len(l1)):
if element==l1[i]:
found = True
break
if found:
print(“Element is in the list!”)
else:
print(“Element is not in the list”)

# Binary search works on sorted list
L1 = [10, 20, 30, 40, 50, 60]
low,high=0,len(L1)-1

element = 51
found = False
while low<=high:
mid = (low + high) // 2
if L1[mid]==element:
found=True
break
else:
if element > L1[mid]:
low=mid+1
else:
high=mid-1

if found:
print(f”Binary Search: {element} is in the list!”)
else:
print(f”Binary Search: {element} is not in the list”)

############

# Files
filename=“17DEC.txt”
filobj = open(filename, “r+”)
content = filobj.read()
print(“1. =============\n,content)
filobj.seek(0)
content = filobj.read(20)
print(“2. =============\n,content)
content = filobj.read(20)
print(“3. =============\n,content)
filobj.seek(0)
content = filobj.readline()
print(“4. =============\n,content)
content = filobj.readline(5000) #read 5000 characters (in current)
print(“5. =============\n,content)

filobj.seek(0)
content = filobj.readlines()
print(“6. =============\n,content)
filobj.close()

# opening again in write mode
filobj = open(filename, “w”)
content=“””filename=”17DEC.txt”
filobj = open(filename, “r+”)
content = filobj.read()
print(“1. =============\n“,content)
filobj.seek(0)
content = filobj.read(20)
print(“2. =============\n“,content)
content = filobj.read(20)
print(“3. =============\n“,content)
filobj.seek(0)”””
filobj.write(content)

content= [‘filename=”17DEC.txt”\n, ‘filobj = open(filename, “r+”)\n,
‘content = filobj.read()\n, ‘print(“1. =============\n,
‘”,content)\n, ‘filobj.seek(0)\n, ‘content = filobj.read(20)\n,
‘print(“2. =============\n, ‘”,content)\n,
‘content = filobj.read(20)\n, ‘print(“3. =============\n,
‘”,content)\n, ‘filobj.seek(0)’]

filobj.writelines(content)
filobj.close()
”’
two types:
1. OLTP – Online Transaction Processing
2. OLAP – Online Analytical Processing

RDBMS – Relational Database Management System

SQL – Structured Query Language – language of Database
SELECT, INSERT, UPDATE, DELETE
CREATE, DROP

Table: EMPLOYEES
EMPID ENAME EPHONE EEMAIL DEPT DHEAD DCODE DLOC
1 AA 123 aa@aa.com Executive AA E01 NY
2 AB 223 ab@aa.com Executive AA E01 ML

Relationship:
1:1 – All the columns in same table
1:M / M:1 – Put them in 2 tables and connect them using Foreign Key
M:M – Pu them in 2 different tables and connect them using 3rd table

— MYSQL database
https://dev.mysql.com/downloads/mysql/
Download and install 8.0.35
1. Server
2. Client
3. Workbench
Connection requires: you know the server location, username, password, database_name

# Data types in MYSQL:
https://dev.mysql.com/doc/refman/8.0/en/data-types.html


use ouremployees;

create table departments (
DID integer primary key,
dname varchar(20),
dhod varchar(20),
dcode varchar(10));

insert into departments values(101,’PD’,’MR PD’,’234AWER439′);
select * from departments;

select * from employees;

”’
# connect to MYSQL
import pymysql
hostname,dbname,username,password = “localhost”,“ouremployees”,“root”,“learnSQL”
db_con = pymysql.connect(host=hostname,database=dbname, user=username,password=password)

db_cursor = db_con.cursor()


sql1=”’Create table employees(empid integer primary key,
name varchar(30),
phone varchar(10),
did integer,
Foreign key (DID) references Departments(DID))
”’
#db_cursor.execute(sql1)

sql1 = ”’Insert into Employees values(
101, ‘Sachin T’,’3456555′,101)”’
#db_cursor.execute(sql1)
db_con.commit()

sql1=”’Select * from Employees”’
db_cursor.execute(sql1)
results = db_cursor.fetchall()
for data in results:
print(data)
db_con.close()

”’
Two types of stats:
Descriptive stats: Central tendency: mean median mode
Measure of variance: range, variance & standard deviation


MF1 – 15% – 10-20%
MF2 – 15% – -10% – 50%

5 & 6 = 5.5
1 & 10 – 5.5

Inferential stats:
”’

# NUMPY – core scientific library
import numpy as np
vals = range(15)
mat1 = np.reshape(vals,(5,3))
print(mat1)
print(“1: “,mat1[3,1])
print(“2: “,mat1[:5,1])
print(“3: \n,mat1[1:4,1:])
print(“Shape: “,mat1.shape)
print(“Number of rows =”,mat1.shape[0])
print(“Number of columns =”,mat1.shape[1])
”’
2x + 5y = 15
3x + 4y = 20
scipy –
”’

mat2=np.zeros((4,4))
print(“Matrix 2 = \n,mat2)
mat2=np.ones((4,4))
print(“Matrix 2 = \n,mat2)

mat2=np.full((4,4),5.001)
print(“Matrix 2 = \n,mat2)

mat3 = np.random.random((3,3))
print(“Matrix 3 = \n,mat3)

np.random.seed(100)
mat3 = np.random.randint(10,50,(3,3))
print(“Matrix 3 = \n,mat3)
”’
[[18 34 13]
[49 33 25]
[20 40 44]]
”’


np.random.seed(100)
mat3 = np.random.randint(10,20,(3,3))
print(“Matrix 3 = \n,mat3)

mat4 = np.random.randint(15,25,(3,3))
print(“Matrix 4 = \n,mat4)

print(“Matrix addition”)
print(mat3 + mat4)
print(np.add(mat3,mat4))

print(“Matrix subtraction”)
print(mat3 – mat4)
print(np.subtract(mat3,mat4))

print(“Matrix multiplication”)
print(mat3 * mat4)
print(np.multiply(mat3,mat4))

print(“Matrix division”)
print(mat3 / mat4)
print(np.divide(mat3,mat4))

print(“Matmul – Matrix Multiplication”)
# MAT3 (m,n) @ MAT4 (x,y) = RESULT_MAT(m,y) and possible only if
#1. n = x
# (3,3) * (3,3) = (3,3)
# (2,8) * (2,8) => matmul is not possible
# (2,8) * (8,2) = (2,2)
# (8,2) * (2,8) = (8,8)
mat3 = np.random.randint(10,20,(8,2))
print(“Matrix 3 = \n,mat3)

mat4 = np.random.randint(15,25,(2,8))
print(“Matrix 4 = \n,mat4)
print(mat3 @ mat4)
print(np.matmul(mat3,mat4))

# NUMPY – core scientific library
import numpy as np

x = np.arange(0,3*np.pi,0.05)
print(x)
y=np.sin(x)
print(“Sin values of x:”,y)
import matplotlib.pyplot as plt
plt.plot(x,y)
plt.show()


import numpy as np

”’ x=3, y= 7
2x + 5y = 41
3x + 4y = 37
convert into 3 matrices:
1. Coefficient Matrix:
[2 5]
[3 4]

2. Variable Matrix:
[x]
[y]

3. Output Matrix:
[15]
[20]

Coeff Matrix * Variable Matrix = Output
=> Variable = inverse(Coeff) * Output
check if determinant is non-zero and then solve it

”’
coeff = np.array([[2,5],[3,4]])
print(coeff)
output=np.array([[41],[37]])
det_coeff = np.linalg.det(coeff)
print(“Determinant of Coeff Matrix = “,det_coeff)
if det_coeff==0:
print(“Cant find the solution for this problem”)
else:
result = np.linalg.inv(coeff) @ output
print(“Solution=\n,result)

”’
2x+3y = 10 # y=0,x=5; y=0.0001, 3.5, y=2,
4x+6y = 20
”’