Python For Juniors-2

DAY 1 : 16 AUG 2022

Download The Python Installer From Here (We Will Install Python 3.9.9):

https://www.python.org/downloads/release/python-399/

You can follow the instructions to install from here:
http://learn.swapnil.pw/python/pythoninstallation/


Watch Installation Video From Here:   https://www.youtube.com/watch?v=mhpu9AsZNiQ

Download & Install IDE for Python Programming

Follow The Steps From Here: https://learn.swapnil.pw/python/pythonides/

Day 2: AUGUST 18, 2022

 

print("Hello")
print()
print("How \nare you?"); # \n within quotes will give us newline
# \\n is used for newline in Python
print("\\\\n is used for newline in Python")
print()
print(5+3); # this is how we use comment in Python
print("5+3"); #text is represented in Python- " / '
print("Good",end=" ")
print("Evening")
x=10
x=15
#when you change the value, its called variable, in above examples
# x is a variable which takes first value of 10 and then 15
#variable name can contain : a...z, 0..9 and _
first_number =100
number1 = 50
# basic data type: integer (int), float (float), string (str), boolean (bool), complex (complex)
# int - no decimal point
second_number = -99
# type
print(type(second_number))
number3 = -5.0
print(type(number3))
val1 = "How are you?"
print(type(val1))
val2 = True # True or False
print(type(val2))

#Arithmetic operators:
num1 = 54
num2 = 5
print(num1 + num2)
print(num1 - num2)
print(num1 * num2) #multiplication
print(num1 / num2) #division
print(num1 // num2) #integer division -only integer
print(num1 % num2) #modulo - remainder
print(num1 ** num2) #power
import math
print(math.pi)

## int + int = int
# int - int = int
# int / int = float
# int //int = int

# float + float = float
#float - float = float

DAY 3: AUGUST 23, 2022

var1 = 5 #int
print(type(var1))
var2 = 5.0 #float
print(type(var2))
str1 = “Hello” #str – string, data is given within -pair of ‘ or “
print(type(str1))
var3 = True # or False : bool or boolean
print(type(var3))
var4 = 5j  #complex numbers
# square root of -1 – i in Maths
print(type(var4))
print(var4**2)

cost_price = 59
quantity = 27
total_cost = cost_price * quantity

print(“Cost Price is”,cost_price,“and the total quantity bought is”,quantity,“and so the total Cost calculated is”,total_cost)
# f string
print(f“Cost Price is {cost_price} and the total quantity bought is {quantity} and so the total Cost calculated is {total_cost})
a=50
b=23
c=a*b

sduotfhdsfhdsvncx = 50
weuru = 23
sdfjhsdkjfnh = sduotfhdsfhdsvncx * weuru

total_cost = 200
quanity = 77
cost_price = total_cost /quantity
print(f“TC is {total_cost}, quantity is {quantity} and cost is {cost_price:0.2f})
bats,country,pos = “Kohli”,“India”,“Captain”
print(f{bats:<17} plays for {country:>16} as {pos:^15} of the team”)
bats,country,pos = “Momgabera”,“Zimbabwe”,“Wicket-keeper”
print(f{bats:17} plays for {country:>16} as {pos:^15} of the team”)

print(“Good”, end=” “)
print(“Evening”)
# \n – newline: text goes to next line
print(“Hello \zHow are you doing today?”)
print(“Hello \nHow are you doing today?”)

#input
var1 = int(input(“Enter a number: “))  #var1 is str
#var1 = int(var1)   #explicit converting to int
print(f“You have entered {var1})
print(f“data type is {type(var1)})

#assignment 1: WAP to get length and breadth as input and calculate and display
#area and perimeter for a rectangle
#assignment 1: WAP to get radius as input and calculate and display
#area and circumference for a circle

DAY 4: AUGUST 25 2022

#Variables and data types
a = 5 #a is called variable
#variable names are not declared in quotes
print(a)
a=-10  #integer – int : number with no decimal point
print(“Value of a is “, a,“Type of a is “,type(a))
a=10.5   #float : decimal number
print(“Value of a is “, a,“Type of a is “,type(a))
a=“hello”   #string – str : text
print(“Value of a is “, a,“Type of a is “,type(a))
a=False   # or True: boolean – bool : just 2 values
print(“Value of a is “, a,“Type of a is “,type(a))
a=5j # square root of -1
print(“Value of a is “, a,“Type of a is “,type(a))
print(5j**2)

#Basic data types: int, float, str, bool, complex
#variable names: should not start with a number and 
### can have only _ along with alphabets and numbers
#valid examples: A_number, number_one, num1, n1u2m3
#Invalid examples:  8Five, first number, first$number
First = 10
first = 20

# 1 set of operations: ARITHEMATIC OPERATIONS
# performed on numbers- int, float, complex
print(first + First)
print(first – First)
print(first * First)
print(first / First)  #2.0
print(first // First) # 2
print(first % First) # 0
print(first **4)

#ASSIGNMENT 
val1 = First # = and then right side values goes to the left

#COMPARISON OPERATORS
# input values are numbers 
# output values are bool
num1 = 30
num2 = 30
print(num1 > num2) #is num1 greater than num2: F
print(num1 >= num2)  #True
print(num1 < num2)  #False
print(num1 <= num2 )  #True
print(num1 == num2 ) #comparing is == True
print(num1 != num2 ) #False

print(“Hello” > “hello”)
# ASCII A= 65, a=90s
print(“hello” > “hellO”)
print(“hELLO” > “Hello”)

#Boolean – LOGICAL OPERATORS
# input: bool
# output: bool
# and  or not:
#I am NOT going – YES/NO
print(not True)  #False
print(not False#True
num1 = 50
num2 = 48
print(not num1 >= num2) #False
#and: needs both input as True (or all) to be True
# otherwise it will give False (even 1 false will make false)
print(True and True)  #True
print(False and True#False
print(True and False#False
print(False and False#False
print(num1 == num2 and num2 <= num1) # False and True

## or: even if 1 value if True- result is True
### its false only  if all the values are false
print(True or True)  #True
print(False or True#True
print(True or False#True
print(False or False#False

#and has a highest precedence among and,or
# 2+3-2*3 = -1
# not a or b and c

#xor : will be True incase of odd number of True
## else False

#BITWISE:
# input is number
# output is also a number

num1 = 21   # 10101
num2 = 14   # 01110
            # 00100
print(num1 & num2)  #4
print(f{num1} equivalent in binary is {bin(num1)})
print(f{num2} equivalent in binary is {bin(num2)})
print(f“00100 is decimal is {int(0b100)})
#  &  |   ^
print(num1 | num2 )  #bitwise or  – 31
print(num1 ^ num2)  #bitwise xor  – 27

DAY 5:  30- AUG- 2022: IF and Nested IF

 

# IF - Conditions & For & While - LOOPS
num=6
if num%2 ==0:
print("the number is even")
print("I am in EVEN condition")
print()
else:
print("Number is Odd")
print("I am the MAIN program")
print("Thank you")
num=3
if num<0:
print("Sorry, we dont work with negative numbers")
elif num%2 ==0:
print("the number is even")
print("I am in EVEN condition")
else:
print("Number is Odd")

print("Continue...")

choice = "Y"
if choice =="Y":
print("Its a uppercase Y")
elif choice =="y":
print("Its a lowercase y")
else:
print("Its not Y")

if "asD" > "asd":
print("Its asd")
else:
print("ZSD") #lowercase have higher value than capital letters


avg = 95
#>80: Grade A, 70-80: B, 60-70: C, 50-60: D, less than 50: E

if avg>=80:
print("You have scored Grade A")
if avg >= 90:
print("Congratulation on Appreciation Letter")
if avg >=95:
print("You win President's Medal as well")
elif avg>=70:
print("You got Grade B")
elif avg>=60:
print("You got Grade C")
elif avg>=50:
print("You got Grade D")
else:
print("You got Grade E")

#Assignment: modify grade example to check for E grade to A

#WAP to check if a number is divisible by 5 and/or 3
num=30
#Approach 1:
#Calculate:
## Best performance: 8 times
## Worst performance: 8 times
## Average performance: (Best + Worst) / 2
if num%5 ==0 and num%3==0:
print("Number is divisible by 5 and 3")
print()
if num%5 ==0 and num%3!=0:
print("Number is divisible by 5 but not by 3")
if num%5 !=0 and num%3==0:
print("Number is divisible by 3 but not by 5")
if num%5 !=0 and num%3!=0:
print("Number is not divisible by 5 or 3")

#Approach:2
#Best performance: 2
#Worst performance: 3

num=30
if num%5==0:
if num%3==0:
print("Number is divisible by 5 and 3")
else:
print("Number is divisible by 5 but not by 3")
else:
if num%3==0:
print("Number is divisible by 3 but not by 5")
else:
print("Number is not divisible by 5 or 3")

#Nested condition: condition inside a condition

DAY 6: SEPTEMBER 1, 2022

import turtle

#setting up screen
screen = turtle.Screen()
screen.bgcolor("light green")
screen.title("Turtle Program: September 2, 2022")

#create my pen
pen =turtle.Turtle()

for i in range(5,21,3): # 0 - start (inclusive), 4 is the end (exclusive), increment
# range: 5, 8, 11,14
pen.forward(100) #moving -drawing
pen.right(60) #degree

#pen.left(90)
pen.hideturtle() #make turtle invisible
pen.penup()
pen.goto(100,100)
pen.pendown()
for i in range(5,20,3): # 0 - start (inclusive), 4 is the end (exclusive), increment
# range: 5, 8, 11,14

pen.forward(180) #moving -drawing
pen.right(144) # degree

pen.hideturtle() #make turtle invisible
pen.left(90)
pen.penup()
pen.goto(250,250)
pen.pendown()
#done
col = ["red","blue","orange","yellow","purple","green","indigo"]
for i in range(1,3,1):
pen.circle(5*i)
pen.circle(-5*i)
pen.pencolor(col[i%7])

pen.penup()
pen.goto(-300,0)
pen.pendown()

import random
for i in range(10):
val = random.randint(50,200)
pen.forward(val) # moving -drawing
angle = random.randint(20,180)
pen.right(angle)

ts = pen.getscreen()
ts.getcanvas().postscript(file="mydrawing.eps")
turtle.done()

DAY 7:  6 SEPTEMBER 2022

from platform import python_version

print(python_version())

http_code = "209"
match http_code:
case "200":
print("Success")
case "301":
print("Permanently moved to new location")
case "404":
print("Page not found")
case _:
print("Unknown Error Code")

# loops: for & while
print("Printing using For loop")
for i in range(5): #parameters: start =0, end <5, increment
print("Value of I is ",i)
print("Hello")
print("Good Evening")

print("Printing using While loop")
j=0
while j<5:
print("Value of J is ",j)
print("Hello")
print("Good Evening")
j+=1

#range(start =,end <,increment)
#range(3,9,3) = 3,6

#range(start, end) : if you see range() with just 2 values:
# these are START & END, which means default INCREMENT = 1
#range(3,8): 3,4,5,6,7

#range(end) : if you see range() with just 1 value:
# that is END, which means default, START =0, INCREMENT = 1
#range(5): 0,1,2,3,4

# first 5 odd numbers
for i in range(5):
print((i*2)+1)
print("########")
for i in range(1,10,2):
print(i)
print("########")
n=5
for j in range(n):
for i in range(n):
print("*",end=" ")
print()

print("########")
'''
*
* *
* * *
* * * *
* * * * *
'''
n=5
for j in range(n):
for i in range(j+1):
print("*",end=" ")
print()

n=5
for j in range(n):
for i in range(n-j):
print("*",end=" ")
print()
print("###########")

#printing multiplication table
n=1
mul = 13
for j in range(mul):
for i in range(mul):
print(f"{(i+1):<2} * {j+1:<2} = {(j+1) * (i+1):<3}", end=" ")
print()

DAY 8:  8 SEPTEMBER 2022

count=5
j=1
while j <=count:
i=1
while i<= count:
print("*",end=" ")
i+=1
print()
j+=1

while True:
num = int(input("Enter a number: "))
if num%2==0:
print("Its an even number")
else:
print("Its an odd number")
ch = input("Enter Y to continue: ")
if ch!="Y":
break

ch = int(input("How many students do you have? "))
count = 1
while count <= ch: # for i in range(ch)
sum = 0
for i in range(3): # subjects
m = int(input("Enter marks: "))
sum += m
avg = sum / 3
'''
Write the logic to find grade
'''
count += 1


#Guessing game version 1
import random
number = random.randint(1,100)
count=0
while True:
guess = int(input("Whats your guess? "))
count+=1
if guess ==number:
print(f"You have guessed it right in {count} attempts!")
break
elif guess > number:
print("Sorry, you have guessed a higher number. Please try again!")
else:
print("Sorry, you have guessed a lower number. Please try again!")

#Guessing game version 2
import random
import time
import datetime as dt
start = time.time()
number = random.randint(1,100)
print("======================")
print("We are guessing: ",number)
print("======================")
count=0
low,high = 1,100
while True:

guess = random.randint(low,high) #int(input("Whats your guess? "))
count+=1
if guess <1 or guess >100:
print("What have you done!!!! Try again")
continue #will go to the beginning of the loop
elif guess ==number:
print(f"You have guessed {guess} right in {count} attempts!")
break
elif guess > number:
print(f"Sorry, you have guessed {guess}, a higher number. Please try again!")
high = guess-1
else:
print(f"Sorry, you have guessed {guess}, a lower number. Please try again!")
low=guess+1
#input()
time.sleep(2)
end = time.time()
print(f"Program started executing at {dt.datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M:%S %p')}"
f" and it finished at {dt.datetime.fromtimestamp(end).strftime('%H:%M:%S')} "
f"so total execution time is {end-start} seconds")

#version 3 :
import random
import time
import datetime as dt
best_time = 0
start = time.time()
total_chances = 0
for i in range(1000):
print("i is ",i)
number = random.randint(1,100)
count=0
low,high = 1,100
while True:
guess = random.randint(low,high) #int(input("Whats your guess? "))
count+=1
if guess <1 or guess >100:
print("What have you done!!!! Try again")
continue #will go to the beginning of the loop
elif guess ==number:
#print(f"You have guessed {guess} right in {count} attempts!")
total_chances+=count
if count <7:
best_time+=1
break
elif guess > number:
#print(f"Sorry, you have guessed {guess}, a higher number. Please try again!")
high = guess-1
else:
#print(f"Sorry, you have guessed {guess}, a lower number. Please try again!")
low=guess+1
#input()
#time.sleep(2)

end = time.time()
print(f"Program started executing at {dt.datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M:%S %p')}"
f" and it finished at {dt.datetime.fromtimestamp(end).strftime('%H:%M:%S')} "
f"so total execution time is {end-start} seconds")
print("Average time per iteration is: ",(end-start)/1000)
print("Average chances per iteration is: ",total_chances/1000)
print("Total better than average attempts: ",best_time)

DAY 9: 13 SEPTEMBER 2022

#Strings
txt1 = 'Hello'
txt2 = "Hello how are youer wekjfdsjf sdjfsdjf jfopdskjpo spodjfopsdfo sodpkfsodpk"
txt3 = '''Hello
good evening
how was your day'''
txt4 = """Hello
have a good day"""
print(type(txt1),type(txt2),type(txt3),type(txt4))
print(txt3)
# What's Your name?
print("What's Your name?")
print('What\'s Your name?')

#slicing / indexing
print(txt2[0]) #first character
num_char = len(txt2) #5
print(txt2[num_char-1])
#3 to 7 characters
print(txt2[2:7]) #starting val is including, ending is upto
print(txt2[0:3]) #first 3 characters
print(txt2[:3]) #first 3 characters
print(txt2[num_char-3:num_char]) #last 3 characters
print(txt2[num_char-3:]) #last 3 characters
print(txt2)
print(txt2[:]) #
## backward indexing
print(txt2[-1]) #last char
print(txt2[-num_char]) #first char
print(txt2[-3:]) #last 3 characters

############
print(txt1 + txt2)
print(txt1*5)
print('E' in "HELLO")
search_txt = 'e'
main_txt = "HEllO"
print(search_txt.lower() in main_txt.lower())
print(search_txt.upper() in main_txt.upper())

#for loop using string
for t in txt1:
print(t)
for i in range(len(txt1)):
print(txt1[i])
txt1 = "hello"
print(txt1.islower())
txt1 = "hello 9"
print(txt1.isalnum())
name = input("Enter your first name: ")
if name.isalpha():
print("Name is saved")
else:
print("Invalid name")

num1 = input("Enter first number: ")
if num1.isdigit():
num1 = int(num1)
else:
print("Can not save this invalid number")


txt1 = "HeLLO HooW are YOU?"
print(txt1.lower())
print(txt1.upper())
print(txt1.title())
txt1 = "HeLLO. HooW are YOU? What are you DOING?"
txt1 = txt1.lower()
txt1=txt1[0].upper() + txt1[1:]
#Strings are immutable
print(txt1)
for c in txt1:
if not c.isalnum() and not c.isspace():
#print(c)
pos =txt1.index(c)
txt1 = txt1[:pos+2] + txt1[pos+2].upper() + txt1[pos+3:]

print(txt1)

DAY 10: 15 SEPTEMBER 2022

#Strings
txt1 = "Hello"
num = txt1.count("l",0,4)
print(num)
num = txt1.find("klo") #returns the position of match
print(num)

txt1 = "How are you doing today?"
content = txt1.split() #returns a list
print(content)
txt2 = "-------------".join(content) #accepts a list value
print(txt2)
old_text = "today"
if txt1.find(old_text) != -1:
txt3 = txt1.replace(old_text,"yesterday")
print(txt3)
else:
print("original text not in the string")

CONST_Name = "Sachin"

27 SEPTEMBER 2022

#Collections in Python
#1 List
list1 = [2,4,True,"Hello", [10,20,30]]
print(list1)
print(type(list1))
print(type(list1[1]))
print(list1[0])
print(list1[1:4])
print(list1[-1])
l2 = list1[-1]
print(type(l2))
print(l2[1])
print(list1[-1][1])

l1 = [1,3,5]
l2 = [2,4,6]
print(l1 + l2)
l3 = l1 * 3
print(l3)
for i in l3:
print(i)
print("###############")
for i in range(len(l3)):
print(l3[i])

# membership test: in
print(3 in l3)

#strings are immutable
str1 = "Hello"
#str1[1]="E"

#lists are mutable
l3[1] = 100
print(l3)

# inbuilt
list3 = [] #creating a blank list
print(type(list3))
print(len(list3))
list3.append(45)
list3.append(35)
list3.append(15)
list3.append(40)
list3.insert(2,80)
list3.insert(99,99)
print(list3)

sum=0
marks = []
for i in range(5):
m = int(input("Enter the marks: "))
marks.append(m)
sum+=m

print("List of marks are: ",marks)
print("Total sum = ",sum)


# [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

total_marks=[]
for j in range(3):
marks = []
print("#####################")
print("Entering marks for student ",j+1)
for i in range(5):
m = int(input("Enter the marks: "))
marks.append(m)
total_marks.append(marks)

print("Total marks: ",total_marks)

total_marks = [[55, 66, 77, 88, 77], [99, 88, 77, 88, 66], [77, 66, 77, 66, 88]]
#index of first subject marks: total_marks[0][0], [1][0], [2][0]

#finding marks in first subject for all the students
print(len(total_marks))
for i in range(len(total_marks)):
print(total_marks[i][0])

#find highest marks in all the subjects
###############################
#finding highest marks in subject 1
max= total_marks[0][0]
for i in range(1,len(total_marks)):
if max < total_marks[i][0]:
max=total_marks[i][0]
print("Highest marks: ",max)

max= -1
for i in range(len(total_marks)):
if max < total_marks[i][0]:
max=total_marks[i][0]
print("Highest marks: ",max)

### solving using first logic
max= []
for j in range(len(total_marks[0])):
for i in range(len(total_marks)):
if i==0:
max.append(total_marks[i][j])
print("max = ",max)
else:
print("i & j = ",i,j)
print("size of max = ",len(max))
if max[j] < total_marks[i][j]:
max[j] = total_marks[i][j]

print("Highest marks: ",max)

29 SEPTEMBER 2022

#list - mutable ordered collection
list1 = [10,3,10,4,10,8,10,2,10]
list1.append(6)
list1.insert(2,10)
print(list1)

#pop - removes element from given position
list1.pop(3)
print(list1)
#remove - removes the element that you give
list1.remove(10)
print(list1)
#want to remove all 10, so first count and then run the loop
tot_ele = list1.count(10)
for i in range(tot_ele):
list1.remove(10)
print(list1)

#reverse the order of the elements
list1.reverse()
print(list1)
list1.sort() #sort in ascending order
print(list1)
list1.sort(reverse=True) #sort in descending order
print(list1)

#index() - gives the position
print("Index of 4 is ",list1.index(4))
#index will give the position of first occurence

list1 = [3, 4, 8, 2, 6]
list2 = list1 #DEEP copy the elements
list3 = list1.copy() #Shallow copy: copies the elements
print("Printing 1")
print(list1)
print(list2)
print(list3)
list1.append(22)
list2.append(33)
list3.append(44)
print("Printing 2")
print(list1)
print(list2)
print(list3)
list4 = list1+list3
list1.extend(list3) #list1 = list1 + list3
print(list1)

###
#input:
#date: 29
#month: 9
#year: 2022
#output: 29th September 2022
date_end=['st','nd', 'rd']+ 17*['th'] + ['st','nd', 'rd']+7*['th']+['st']
month_convert=['January','February','March','April',
'May','June','July','August',
'September','October','November','December']
date = int(input("Enter the date: "))
month = int(input("Enter the month: "))
year = input("Enter the year: ")
output = str(date)+date_end[date-1] + " "+month_convert[month-1] + " "+ year
print(output)


# Tuple: immutable ordered collection
list1 = [4,5,6,7,89,10]
print(type(list1))
t1 = tuple(list1)
print(type(t1))
l1 = list(t1)
print(type(l1))

#immutable:
t1 = (2,2,4,6,7)
t1 = list(t1)
t1.append(8)
t1=tuple(t1)
print(type(t1))
print(len(t1))

t1 = (1,2,3,4) #packing

a,b,c,d = t1 #unpacking
print(a,b,c,d)

a,b,c,d = (1,2,3,4) #unpacking
print(a,b,c,d)

for i in t1:
print(i)
print(t1[2])

OCTOBER 4 2022 (Tuesday)

var1 = {True:50,5:"Sachin","City": "Mumbai"}
print(type(var1))
print(var1[True])
print(var1["City"])
print(var1)

var2 = {"Runs": 15900}
var1.update(var2)
print(var1)

for i in var1.keys(): #gets all the keys
print(i)
print(var1[i])
print(i," : ",var1[i])
for j in var1.values(): #gets all the values
print(j)

for k,v in var1.items():
print(k,":",v)

maindata={"Sachin": ["Sachin Tendkular","India", 15900],
"Ricky": ["Ricky Ponting","Australia",8990],
"Paine":["Tim Paine","Australia",7800],
"Kohli":["Virat Kohli","India",8900]}
filter="Australia"
for i in maindata.keys():
if maindata[i][1] == filter:
print(maindata[i][0])

maindata2 = maindata #deep copy
maindata3 = maindata.copy() #shallow copy
temp = {"Rohit":["Rohit Sharma","India",9281],
"Boucher":["Mark Boucher","South Africa",5600]}
maindata.update(temp)
print("Values after Update to maindata: ")
print(maindata)
print(maindata2)
print(maindata3)

maindata.popitem()
print(maindata2)
maindata.pop("Paine")
print(maindata2)

maindata.clear()
print(maindata2)

#SETS
#Sets
set1 = {3,6,7,3,6,7,3,6,7,3,6,7,3,6,7,3,6,7,3,6,7,3,6,7}
print(type(set1))
print(set1)

for num in set1:
print(num)
list1 = [3,6,73,6,73,6,73,6,73,6,73,6,73,6,73,6,7]
print(list1)
#remove duplicate elements from the list
list1 = list(set(list1))
print(list1)
set1.add(9)

print(set1)
#pop will remove a value
set1.pop()
#remove will remove the given value
set1.remove(3)
print(set1)

set1 = {1,10,2,6,8}
set2 = {2,6,8,21,22}
print(set1 | set2)
print(set1.union(set2))
#print(set1.update(set2))
print(set1)
#union(): set3 = set1.union(set2)
#update(): set1 = set1.union(set2)

print(set1 & set2)
print(set1.intersection(set2))
#intersection_update()

print(set1 - set2)
print(set2 - set1)
print(set1.difference(set2))
#difference_update()

print(set1 ^ set2)
print(set2 ^ set1)
print(set1.symmetric_difference(set2))
#symmetric_difference_update()

#isdisjoint
print(set1.isdisjoint(set2))
#issuperset
print(set1.issubset(set2))
#issubset
print(set1.issuperset(set2))

OCTOBER 6, 2022

list_items = [5,10,15,20,25,30,35,40,45]
element = 20
pos = -1
counter = 0
for i in list_items:
if element == i:
pos=counter
else:
counter+=1
if pos==-1:
print("Element is not in the list")
else:
print("Element is found at index ",pos)

#Sorting
## Bubble sort
## Linear sort
## Merge sort
## Insertion sort
## Shell sort
list_items = [5,10,15,20,25,30,35,40,45]
new_list=list_items.copy()

#bubble sort - descending order
for i in range(len(new_list)-1):
for j in range(len(new_list)-1-i):
if new_list[j] < new_list[j+1]:
new_list[j] , new_list[j+1] = new_list[j+1] , new_list[j]
print("Sorted list: \n",new_list)

seq_list = new_list.copy()
#sequential sort - ascending order
for i in range(len(seq_list)-1):
for j in range(i+1, len(seq_list)):
if seq_list[i] > seq_list[j]:
seq_list[i] , seq_list[j] = seq_list[j] , seq_list[i]
print("Sorted list: \n",seq_list)

#Binary search
list_val = seq_list
element = 45
le = len(list_val)
fe = 0
mid = (le+fe)//2
pos = -1

while fe <=le:
if element==list_val[mid]:
#print("Element is found at index ",mid)
pos = mid
break
elif element <list_val[mid]:
le = mid-1
mid = (le + fe) // 2
else:
fe=mid+1
mid = (le + fe) // 2
if pos==-1:
print("Element is not in the list")
else:
print("Element is found at index ",pos)

13 OCTOBER 2022

#Function
def mystatements():
print("Hello")
print("How are you doing?")
print("Good morning")
def mystatements2(name,greeting): #required & positional
print("Hello",name)
print("How are you doing?")
print(greeting)

def mystatements3(name, greeting="Good Morning"): #default & positional
#name is required and greeting is default
#required parameters are given before default
print("Hello",name)
print("How are you doing?")
print(greeting)
return 100

mystatements()
result = mystatements2("Sachin","Good Morning")
print(result) #None is returned
result = mystatements3("Sachin")
print(result)

#function to take 2 numbers as input and
# perform add, sub,multiplication & division
# create - 2 functions: 1)required positional
# 2)default wheren numbers are 99 & 99
#return 4 answers as tuple

20 OCTOBER 2022

#ax**2 + bx +c = 0 ; a,b,c are given then find x
# value of x is given as: (-b +/- sqroot(b**2 - 4ac))/2a
#Solve this:
# 2x**2 +3x -4 = 0
import math
math.sqrt(100)
def QuadEq(a,b,c=-4):
sol1 = (-b+(b**2 - 4*a[0]*c)**0.5)/(2*a[0])
sol2 = (-b-(b**2 - 4*a[0]*c)**0.5)/(2*a[0])
return sol1,sol2


solutions = QuadEq(b=3,a=[2,4,6])
print("Values of x are: ",solutions[0],"and",solutions[1])

#Values of x are: 0.8507810593582121 and -2.350781059358212

#variable length functions
def myfunc1(val1,val2, *values, **setofvalues):
print("Value 1: ",val1)
print("Values: ",values)
print("Set of Values: ", setofvalues)
myfunc1(10,11,12,13,14,15,"16",17,18,19,20,roll=34,name="Sachin",sports="Cricket")

def myfacto(x):
if x==1:
return 1
return x * myfacto(x-1)#recursion

result = myfacto(6)
print("Factorial = ",result)

25 OCTOBER 2022

# OBJECT ORIENTED PROGRAMMING
class Apple:
color="red"
shape="round"
count=0
def __init__(self,kind,price):
self.k = kind
self.cost = price
Apple.count+=1

def display(self):
print("So you have bought "+self.k+" apple at a cost of $",self.cost)

@classmethod
def classdisplay(cls):
print("This is an Apple class with color "+cls.color+" and shape is "+cls.shape)
print("Total Apple objects created are: ",cls.count)

app1 = Apple("Washington", 2)
app2 = Apple("Indian", 2)
app3 = Apple("Fizi", 2)
app4 = Apple("Washington", 3)
app5 = Apple("Fize", 2.5)
app3.display()
app1.classdisplay()
app4.classdisplay()

app6 = Apple("Indian", 5)
app6.display()
app4.classdisplay()

27 OCT 2022

INHERITANCE in PYTHON

class School:
def __init__(self):
print("School Object is created")

def printhi(self):
print("Hello from School")

class Student(School):
def __init__(self):
print("Student Object is created")
def studenthi(self):
print("Hello from Student")
def printhi(self):
print("This feature is not available")

class Teacher(School):
def __init__(self):
print("Teacher Object is created")
def teacherhi(self):
print("Hello from Teacher")
st1 = Student()
st1.studenthi()
st1.printhi()

NOV 1 , 2022

#SQL - Structured Programming Language
#CRUD - Create Read Update Delete

import sqlite3
connection = sqlite3.connect('mydb.db')
cur_obj = connection.cursor()

#cur_obj.execute('Drop Table MEMBERS')

create_table = '''
cREAte Table Members(
MemberID Integer Primary Key,
Name Text,
Address Varchar2(30),
Phone text,
Email text
)
'''
#cur_obj.execute(create_table)
#Create = INSERT command
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(1,"Sachin","Mumbai","123","sa@s.com")
'''
cur_obj.execute(insert_data)
connection.commit()
#SQL - Structured Programming Language
#CRUD - Create Read Update Delete

import sqlite3
connection = sqlite3.connect('mydb.db')
cur_obj = connection.cursor()

#cur_obj.execute('Drop Table MEMBERS')

create_table = '''
cREAte Table Members(
MemberID Integer Primary Key,
Name Text,
Address Varchar2(30),
Phone text,
Email text
)
'''
#cur_obj.execute(create_table)
#Create = INSERT command
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(1,"Sachin","Mumbai","123","sa@s.com")
'''
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(2,"Laxman","Hyderabad","123","la@s.com")
'''
#cur_obj.execute(insert_data)
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(3,"Sourav","Kolkata","123","sg@s.com")
'''
#cur_obj.execute(insert_data)
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(4,"Zaheer","Mumbai","223","za@s.com")
'''
#cur_obj.execute(insert_data)
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(5,"Gautam","Delhi","123","ga@s.com")
'''
#cur_obj.execute(insert_data)
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(6,"Rohit","Mumbai","113","ra@s.com")
'''
#cur_obj.execute(insert_data)

#update the phone number to 222 for MemberID = 2
update_query= '''Update Members Set Phone = "222" where memberid = 2'''
#cur_obj.execute(update_query)

#update the phone number to 222 for MemberID = 2
delete_query= '''Delete from Members where memberid = 3'''
cur_obj.execute(delete_query)

#Reading the content from the table
select_query = '''Select * from Members'''
cur_obj.execute(select_query)
output = cur_obj.fetchall()
for row in output:
print(row)

select_query = '''Select MemberID, Name, Address from Members where MemberID in (5,9,12,15)'''
cur_obj.execute(select_query)
output = cur_obj.fetchall() # []
for row in output:
print(row[0])

connection.commit()
# C - INSERT R- SELECT U-UPDATE D- DELETE
# Read to a file and write to a file
import os
print(os.getcwd())
#os.mkdir("C:\\Users\\Hp\\PycharmProjects\\pr1\\Nov_2")

#absolute path
#relative path

#1. Create File Object
file1 = open("Nov_2\\abc.txt","r") #mode: r-read w-write a-append, r+ w+ a+
poem1 = '''Twinkle Twinkle Little Star
How I WOnder What You Are
Up Above the World So High
Like a Diamond in the Sky
'''

#2 functions to write to a text file: Write & Writelines
#if file1.writable():
#file1.write(poem1)
file1.seek(30)
content1 = file1.readline()
file1.seek(0)
content2 = file1.read()
print("Readline: \n",content1)
print("Read: \n",content2)

#seek() - this is like a pointer/tracker which tracks where you are in the content reading
import sqlite3
conn = sqlite3.connect("mydb.db")
cursorobj = conn.cursor()

select_query1 = "Select Name from Sqlite_schema where type='table'"
select_query2 = "Select * from members"
cursorobj.execute(select_query2)
info = cursorobj.fetchall()
for i in info:
print(i[1])
# Create - Insert
#Read - Select
#Update
#Delete

############ Reading Files ##################
# operations you can perform on a file: Read, Write, Append
# creating, renaming, deleting - operating systems

import os
#os.makedirs("Nov_9") #make directory
#os.rmdir("Nov_9") #remove directory
file_name = "Nov_1/abcd.txt"
file_handle = open(file_name,"a")
#file mode - r, r+, w, w+, a, a+
str_val = """Twinkle Twinkle Little Star
How I wonder
What you are
Up above the world
so high
like a diamond
in the sky
"""
file_handle.write(str_val)

file_handle.close()

###################### NUMPY ################
#Numpy - matrices
import numpy as np
val = range(15)
mat1 = np.reshape(val,(5,3))
print(mat1)
print(mat1.shape)
print(mat1[2:,1])
#matrix 1
val = range(9)
mat1 = np.reshape(val,(3,3))
print("Matrix 1: \n",mat1)
#create matrix out of list of lists
list_val = [[1,2,1],[3,2,1],[2,2,2]]
mat2 = np.array(list_val)
print("Matrix 2: \n",mat2)

print(mat1 + mat2)
print(np.add(mat1,mat2))
#if mat 1 of shape m*n, mat2 should alse be m*n and output is also m*n
print(mat1 - mat2)
print(np.subtract(mat1,mat2))
print(mat1 / mat2)
print(np.divide(mat1,mat2))

## Multiplication - This is NOT MATRIX MULTIPLICATION
print(mat1 * mat2)
print(np.multiply(mat1,mat2))

####Matrix Multiplication
print(mat1 @ mat2)
print(np.matmul(mat1,mat2))

MATPLOTLIB

import matplotlib.pyplot as plt
import numpy as np

data = np.random.randn(1000)
plt.hist(data, bins=30,color="red")
plt.savefig("10NOVHIST.png")
plt.show()

data1 = np.random.normal(100,60, 500) #mean, sd, total
data2 = np.random.normal(100,20, 500) #mean, sd, total
data3 = np.random.normal(180,60, 500) #mean, sd, total
data4 = np.random.normal(180,20, 500) #mean, sd, total
fig = plt.figure()
ax=fig.add_axes([0,0,1,1])
plot_data = [data1,data2,data3,data4]
ax.boxplot(plot_data)
plt.show()

num_hrs = [3,5,9,4,2,8,6,7]
marks = [45,80,89,54,34,90,67,75]
plt.scatter(num_hrs,marks)
plt.show()

num_hrs = [3,5,9,4,2,8,6,7]
marks = [45,80,89,54,34,90,67,75]
marks.reverse()
plt.scatter(num_hrs,marks)
plt.title("Scatter Plot Hrs v Marks")
plt.xlabel("Hours / Week")
plt.ylabel("Marks (out of 100)")
plt.show()