Swapnil Saurav

## FREE PYTHON TRAINING BY BRC WARRIORS - AUG TO SEP 2022

DAY 0 – ORIENTATIONÂ  (AUGUSTÂ  12, 2022)

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

Â

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

## Watch Installation Video From Hereâ€‹

DAY 1:Â  PYTHONÂ  BASICSÂ  (AUGUST 15, 2022)

`print(3+4+5) #Python will evaluateprint('3+4+5')  #Python will print as it isprint('Hello how are you?')#this is a sample comment#comments are put in hashprint("Good evening")#there are two types of translators in programming#language - COMPILER & INTERPRETER#Constant v Variablex = 5x = 7x = 9.5# x is a variable which can change its value# x is the variable name# you can add number to variable namex1 = 10 #valid variable name#1x = 10 # it is wrong# you can give _ to variable name# _ is the only special character that can be# given to variable namefirst_num = 50print(first_num)print('first_num')print("First number value is ",first_num)#What are different data types in Python#in python, number is of 2 types:# int = integer: non decimal values: -inf to +inf## 5,10,-99999,-78, 0, 56# float = float: values with decimal## e.g.  -5.5, 0.0, 5.0 , 5.99999999val1 = 5val2 = 5.0#print the data type using type()print(type(val1))print(type(val2))#complex : square root of -1# square root of -25 ?# square root (25*-1) = 5i# iota (i) in python is written as jval3 = 5jprint(type(val3))val4 = "Hello" #text data in python is #called str (string)print(type(val4))# 5th data type is bool (boolean)#boolean takes 2 values: True & Falseval5 = Trueprint(type(val5))#Basic data types: int, float, complex, bool,str#WAP to calculate area and perimeter of a rectanglelength = 10breadth = 12area = length * breadthprint("Rectanle with sides",length,"and", breadth,      "has area of",area)perimeter = 2 * (length + breadth)print("Rectanle with sides",length,"and", breadth,      "has perimeter of",perimeter)# 1. calculate and display area and perimeter of a ##  square# 2. calculate and display area and circumference of a## circle`

## WATCH DAY 1 RECORDING HERE

DAY 2:Â  PYTHONÂ  OPERATORS(AUGUST 16, 2022)

Â

`#Program done on 16thpi = 3.14r = 5area = pi*r**2  # ** for powercircumference = 2 * pi * rprint("A circle with radius",r,"has a circumference"    " of",circumference," and area of",area)#Above I am moving only the content to different line#with just one print function#using format string -print(f"A circle with radius {r} has a circumference "    f"of {circumference:0.1f}  and area of {area}")print(5**2)print("Hi there \nHow are you?")  #\n stands for newlineprint("Hello",end=" ")  # end will make \n visibleprint("Good Evening")val1 = 59val2 = 25print(val1 + val2)  #additionprint(val1 - val2)  #subtractionprint(val1 * val2)  #multiplicationprint(val1 / val2)  #divisionprint(val1 ** val2)  # powerprint(val1 // val2)  # integer divisionprint(val1 % val2)  #modulo - remainder## These were arithematic operations#Comparison Operators## input are integer values and output is a boolean value (T/F)val1 = 12val2 = 12##comparison operators are:  >   <   >=   <= ==  !=print(val1 > val2)print(val1 >= val2)print(val1 < val2)print(val1 <= val2)print(val1 == val2)# a = 5 : assign value 5 to a // a will be 5# a==5 : asking question, is a equal to 5 ? answer would T/Fprint(val1 != val2)  # not equal to- is val1 not equal to val2 ?# Logical operators## checks the relationship between 2 boolean values## operators are:  and   or  not## and : if one value is False entire value will be false. Its true only when all the values### are Trueval1 = 15val2 = 19print(val1 !=val2  and  val1 > val2) #True and False = FALSE# OR - even if one nalue is True entire result will be Trueprint(val1 !=val2  or  val1 > val2) # TRUE or FALSE - Trueprint(not True)print(not False)val1 = 30print(val1 % 3)#INPUTa= input("Enter a value: ")   #interactive input - you dont have to give fixed valuea = int(a)  #int() str()  float() complex()  bool()print("Input value is ",a)print("Data type of input value is ", type(a))`

## WATCH DAY 2 RECORDING HERE

DAY 3:Â  PYTHONÂ  OPERATORS(AUGUST 17, 2022)

`#avg = 40#you have passedif avg >=40:  #if the condition is true only print command will be executed    print("You have passed")    print("I am in if")    print("I am also in if")else:    #pass #pass statement is used when you have nothing to write    print("Sorry you have not passed!")print("I am outside if")num = 25#wap to check if num is divisible by 5 or not#divisibility: if you divide the num by 5 and the remainder is zeroif num%5==0:    print(f"{num} is divisible by 5")else:    print(f"{num} is not divisible by 5")#wap to check if a number is positive or negativenum = -10if num >0:    print(f"{num} is positive number")elif num==0:    print("0 is neither a positive or negative number")else:    print(f"{num} is negative number")#WAP to print sum and average of 5 subjects and assign grade to the student based on:## avg >=80: A, avg>= 70: B, avg>=60: C, avg >=50: D, avg>=40: E, avg <40- Fmarks1 = input("Enter marks in subject 1: ")marks1 = int(marks1)marks2 = int(input("Enter marks in subject 2: "))marks3 = int(input("Enter marks in subject 3: "))marks4 = int(input("Enter marks in subject 4: "))marks5 = int(input("Enter marks in subject 5: "))total = marks1 + marks2 + marks3 + marks4 + marks5avg = total /5print(f"Student has scored a total of {total} marks and average of {avg}")#if you score more than 90% - you win school medal, if >=95%# we win President medalif avg >=80:    print("You have got Grade A")    if avg >=90:        if avg>=95:            print("You win President Medal")        else:            print("You win School Medal")elif avg >=70:    print("You have scored Grade B")elif avg >= 60:    print("You have scored Grade C")elif avg >= 50:    print("You have scored Grade D")elif avg >= 40:    print("You have scored Grade E")else:    print("Sorry, You have scored Grade F")print("Thank you for running my program")#wap to arrange given 3 numbers in increasing order#enter numbers as: 45, 75, 35 =>   35   45   75a,b,c = 85, 75,95l1,l2,l3 = a,a,aif a < b: #when a is less than b    if a<c: # a is less than b and a is less than cv [        l1 = a        if b<c:            l2,l3=b,c        else: #c is less than b            l2,l3 = c,b    else:  #a is less than b and greater than c [e.g. 3 5 2]        l1,l2,l3=c,a,belse:  #when b is less than a    if b <c:        l1 =b        if a <c:            l2,l3=a,c        else:            l2,l3 = c,a    else:  # c <b        l1,l2,l3 = c,b,aprint(f"{l1} <= {l2} <={l3}")`

## WATCH DAY 3 RECORDING HERE

DAY 4:Â  PYTHONÂ  TRAINING – IF Condition & FOR Loop(AUGUST 18, 2022)

`#yesterday we did arranging 3 words in increasing order#retry the same program but this time we will do in decreasing ordernum1,num2,num3 = 80,10,40b1,b2,b3 = num1,num1,num1#logic to find highest, second highest and lowest valuesif num1 >= num2:    if num1 >= num3:        b1 = num1        if num2 > num3:            b2,b3 = num2, num3        else:            b2,b3 = num3,num2    else: #num1 > num2 and num3 >num1        b1 = num3        b2,b3 = num1, num2else:  #num2 > num1    if num2 > num3:        b1 = num2        if num3 > num1:            b2,b3=num3,num1        else:            b2, b3 = num1, num3    else:        b1 = num3        b2, b3 = num2, num1#after the logic- b1 will have the higest value, b2: second highest and b3: lowest valueprint(f"{b1} >= {b2} >= {b3}")############ LOOPS   ######### FOR Loop - how many times you need to executeprint("Hello 5 times using FOR")for counter in range(0,5,1):# generate values from 0 (including) upto 5 (excluding) with increment of 1    print("Hello : ",counter)# range(3,8): when range has only 3 values then default increment is 1 (first val is starting and second is ending)for i in range(3,8):    print("Hello: ",i) #generated values: 3, 4, 5, 6,7print("3rd For loop: ")for i in range(3,8,2):    print("Hello: ",i) #generated values: 3, 5, 7print("For range with one value: ")for i in range(3): #if one value then its ending value, default start = 0 ; increment =1    print("Hello: ",i) #generated values: 0,1,2print("For loop is done)")############### * * * * *for i in range(5):    print("*",end=" ")print()'''* * * * ** * * * ** * * * ** * * * ** * * * *'''for j in range(5):    for i in range(5):        print("*",end=" ")    print()'''* * * * * * * * * * * * * * *'''for j in range(5):    for i in range(j+1):        print("*",end=" ")    print()'''* * * * ** * * ** * ** **'''for j in range(5):    for i in range(5-j):        print("*",end=" ")    print()## While Loop - checks for a condition, it will execute till the condition is true`

## Watch the Day 4 video here

Day 5:Â  19 AUGUST 2022

Â

`#for loop when we know how many times to run the loop# while is based on conditioni = 1while i <=5:    print(i)    i+=1user = "y"while user=="y":    print("How are you?")    user = input("Do you want to continue?")while True:    print("Select Your Option:")    print("1. Perform Addition")    print("2. Perform Subtract")    print("3. Perform Multiplication")    print("4. Perform Division")    print("5. Quit")    ch=int(input("Enter your choice? "))    if ch==1:        n1 = int(input("Enter a number: "))        n2 = int(input("Enter second number: "))        sum= n1 + n2        print("Addition is ",sum)    elif ch==2:        pass    elif ch==3:        pass    elif ch==4:        pass    elif ch==5:        print("We are exiting... thank you!")        break  #this command will throw us out of the loop    else:        print("Sorry, you have entered an invalid option! Try Again...")# for - same as for loop in Python# While - same as while in python# do.. while (exit controlled loop)#Generate Prime Numbers:start = 5000end = 10000while start <= end:    #check if a number is prime or not    num = start    #how to check? - if a number is divisible by 1 and itself only    isPrime = True    for i in range(2,num//2+1):        if num%i ==0:            isPrime = False            break    if isPrime:        print(num,end=", ")    start+=1  #now increment the start value to nextprint()"""**  **    **      **        ** * * * * *"""n = 8for i in range(n):    if i==0 or i==n-1:        for j in range(i+1):            print("*",end=" ")    else:        print("*",end= "")        for k in range(i):            print(" ",end=" ")        print("*",end="")    print()#Fibonacci series# 1,1,2,3,5,8,13.....n_terms = int(input("How many terms you want? "))if n_terms == 1:    print("1 ")elif n_terms > 1:    print(" 1", end=", ")    prev1,prev2 = 0,1    for i in range(1,n_terms):        current = prev1 + prev2        print(current, end=", ")        prev1, prev2 = prev2, currentelse:    print("Invalid input")`

Â

## Watch day 5 video Here

DAY 6 :  22 AUGUST 2022

# 22 aug 2022
#Practice on IF conditions as well as Loops
num = int(input(“Enter the number: “))
mul = int(input(“Enter the multiple: “))
print(f{num} X {mul} = {num*mul})
num = int(input(“Enter the number: “))
for i in range(10):
print(f{num} X {i+1} = {num*(i+1)})
”’
1 * 1 = 1    2 * 1 = 2   3 * 1 = 3 …   10 * 1
1 * 2 = 2
..
1 * 10 = 10
”’
for j in range(10):
for i in range(10):
print(f{i+1:<2} X {j+1:<2} = {(j+1)*(i+1): <3}, end=”  “)
print()
#wap to give options to perform sum, difference, multiplication or division
#continue till user wants
while True:
print(“Please select from below options: “)
print(“1. Addition \n2. Subtraction \n3. Multiplication \n4. Division \n5. Quit”)
ch=int(input(“Enter your option: “))
if ch==1:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
print(f“Addition of {num1} and {num2} is {num1+num2})
elif ch==2:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
print(f“Difference of {num1} and {num2} is {num1-num2})
elif ch==3:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
print(f“Multiplication of {num1} and {num2} is {num1*num2})
elif ch==4:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
print(f“Division of {num1} by {num2} is {num1/num2})
elif ch==5:
break
else:
continue
#wap to give options to perform sum, difference, multiplication or division
#continue till user wants
while True:
print(“Please select from below options: “)
print(“1. Addition \n2. Subtraction \n3. Multiplication \n4. Division \n5. Quit”)
ch=int(input(“Enter your option: “))
if ch==1:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
print(f“Addition of {num1} and {num2} is {num1+num2})
elif ch==2:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
print(f“Difference of {num1} and {num2} is {num1-num2})
elif ch==3:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
print(f“Multiplication of {num1} and {num2} is {num1*num2})
elif ch==4:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
print(f“Division of {num1} by {num2} is {num1/num2})
elif ch==5:
break
else:
continue

#Lets develop a guessing game
#Let computer think of a number and let computer guess that number
import random  # it has functions that deal with random numbers
comp_num = random.randint(1,100)
counter = 0
low,high = 1,100
while True:
guess_num = random.randint(low,high)
counter+=1
if guess_num ==comp_num:
print(f“Congratulations! You have guessed the number correctly in {counter} attempts!”)
break
else:
print(“Sorry! You did not get it correct”)
if guess_num > comp_num:
print(“HINT: Your number is higher than the actual number…”)
high=guess_num-1
else:
print(“HINT: Your number is lower than the actual number…”)
low = guess_num+1
# one line if condition
num = 10
if num>0:
print(“Positive”)
else:
print(“not Positive”)
#where you have condition which does one line of instruction, we can modify this as:
# we can re-write line no. 3 to 6 as:
output = “Positive” if num>0 else  “not Positive”
print(output)

#one line loop example:
output = [i for i in range(1,11)]
#[] is creating a list we will discuss later this week
print(output)

Â

Download Python book and many other technical books and videos for free from Story Mantra Android Mobile App. Login and then click on Technical category to access the material

DAY 7: AUGUST 23, 2022

`#String## its a text that Python usesgreet1 = 'hello'greet2 = "evening"print(type(greet2))print(greet1 + " "+ greet2)print(greet1 *5)print("Hello " + str(8))print(str(7) + str(8))'''comment'''greet3 = '''How are you today?I am fine'''print(greet3)greet4 = """I am fineI am going homeWhere are you going?"""print(greet4)greet1 ="Good Evening"for i in greet1:    print(i,end="")print()print(f"Number of characters in {greet1} are {len(greet1)} ")for i in range(len(greet1)):    print(i, end=" ")print()#slicing / indexing in String#concept is same for future discussions like List, Tuple, Dictionary,...greet1 = "Hello Bye"#counting starts from ZEROprint(greet1[0]) #position 1 = Index 0print(greet1[0]+greet1[4]+greet1[7])#counting or indexing starts from zero from left to right# len(greet1) = 9print(len(greet1))#first memeber of the string: greet1[0]size = len(greet1)#last member of the string: greet1[size-1]print(greet1[size-1])  #last character'''  H   E    L    L     O  0   1    2    3     4  => Left to Right is +ve indexing starting from zero  -5  -4  -3    -2   -1  => Right to Left is -ve indexing, starts from -1'''greet1 = "Hello Bye"#print last character, 3rd character and 5th last characterprint(greet1[-1] + greet1[-3]+greet1[-5])#indexing sequence of charactersgreet1 = "Hello Bye"print(greet1[0:3])  #first 3 charactersprint(greet1[2:5])  #lloprint(greet1[-7:-4])  #llo using -ve indexingsize = len(greet1)print(greet1[-size:-size+4])  #first 3 charactersprint(greet1[:-size+4])  #if left side is blanks, then its starting from 0print(greet1[6:9])  #last 3 characters using +ve indexingprint(greet1[-3:])  #last 3 characters using -ve indexingprint(greet1[:]) #print from first to last# Inbuilt Methods in String#functions part of a class is called methods#here class name is Stringgreet1 = "Hellobe Hello7Hello*y"print(greet1.isalpha()) #True/Falseprint(greet1.isalnum())print(greet1.isupper())  #check if its upper caseprint(greet1.islower())  #check if its lower caseprint(greet1.istitle()) #title case means - first character of every word# words can be separated by any non-alphabet# Str are called immutable (u cant edit)str1 = "hello"#str1[0] = "H"  #error because we cant edit the valuestr1 = "H"+str1[1:] #this is fine because we are creating new string variableprint(str1)`

DAY 8:Â  24 AUGUST 2022 –Â  String Methods – II and List – I

#Â String
#Â isupper,Â islower,istitle

num1Â =Â input(“EnterÂ lengthÂ ofÂ theÂ rectangle:Â “)
num2Â =Â input(“EnterÂ breadthÂ ofÂ theÂ rectangle:Â “)
ifÂ num1.isdigit()Â andÂ num2.isdigit():
Â Â Â Â num1Â =Â int(num1)Â
Â Â Â Â num2Â =Â int(num2)
Â Â Â Â areaÂ =Â num1Â *Â num2
Â Â Â Â perimeterÂ =Â 2Â *Â (num1Â +Â num2)
Â Â Â Â print(f“AreaÂ andÂ PerimeterÂ areÂ {area}Â andÂ {perimeter}Â respectively”)
else:
Â Â Â Â print(f“OneÂ orÂ moreÂ inputÂ valuesÂ areÂ invalid!”)

#Â StringÂ methods
#lower(),Â upper(),Â title()
greet1Â =Â “HelloÂ EveryONE”
print(“TitleÂ Case:Â “,greet1.title())
print(“UpperÂ Case:Â “,greet1.upper())
print(“LowerÂ Case:Â “,greet1.lower())

#WAPÂ toÂ inputÂ nationalityÂ andÂ ageÂ toÂ decideÂ whetherÂ thatÂ personÂ canÂ voteÂ orÂ not
ageÂ =Â int(input(“EnterÂ yourÂ age:Â “))Â
nationalityÂ =Â input(“EnterÂ YourÂ Nationality:Â “)
ifÂ ageÂ >=18Â andÂ nationality.lower()Â ==“india”:
Â Â Â Â print(“YouÂ areÂ eligibleÂ toÂ voteÂ inÂ India”)
else:
Â Â Â Â print(“Sorry,Â youÂ doÂ notÂ meetÂ theÂ criteriaÂ toÂ voteÂ inÂ India”)

statement1Â =Â “HelloÂ HowÂ AreÂ YouÂ DoingÂ Today?”
words1Â =Â statement1.split()Â Â #Â outputÂ isÂ aÂ List,Â whichÂ weÂ willÂ discussÂ later
print(words1)
text1Â =Â “Hello;How;are;you;doing;today;?”
words2Â =Â text1.split(“;”)Â #byÂ defaultÂ itÂ willÂ splitÂ onÂ blankÂ spaceÂ butÂ weÂ canÂ tellÂ howÂ toÂ split
print(words2)
txt2Â =Â ”Â “.join([‘Hello’,Â ‘How’,Â ‘are’,Â ‘you’,Â ‘doing’,Â ‘today’,Â ‘?’])
print(txt2)

#replace
txt3Â =Â “WhatÂ areÂ youÂ doingÂ today?”
txt3Â =Â txt3.lower().replace(“what”,“How”)
print(txt3)
#find
txt4Â =Â “HowÂ areÂ youÂ doingÂ todayÂ whatsÂ yourÂ name”
#WAPÂ toÂ findÂ isÂ theÂ textÂ hasÂ “doing”
resultÂ =Â txt4.find(“doing”)
ifÂ resultÂ ==-1:
Â Â Â Â print(“Sorry,Â theÂ textÂ doesntÂ containÂ doingÂ inÂ it”)
else:
Â Â Â Â print(“TextÂ hasÂ doingÂ atÂ positionÂ “,result)

text=Â “HELLOÂ EVERYONE”
reverse_txtÂ Â =Â “”
forÂ iÂ inÂ text:
Â Â Â Â reverse_txt=Â iÂ +Â reverse_txt
print(reverse_txt)

#Â WorkingÂ withÂ ListÂ datatype
#declareÂ aÂ list
list1Â =Â [5,Â True,“Hello”,Â [2,4,6]]
print(“SizeÂ ofÂ theÂ list:Â “,len(list1))
list2=Â [5.5,Â False]
print(list1Â +Â list2)
print(list2Â *Â 4)
print(“Hello”Â inÂ list1)

print(“ValuesÂ inÂ theÂ listÂ usingÂ ForÂ Loop:”)
forÂ iÂ inÂ list1:
Â Â Â Â print(i)

print(“#IndexingÂ /Â SlicingÂ sameÂ asÂ string”)
print(list1[-2:])
first_memÂ =Â list1[0]
print(type(first_mem))
last_memÂ =Â list1[-1]
print(type(last_mem))

#WAPÂ toÂ inputÂ marksÂ ofÂ 5Â subjectsÂ andÂ printÂ sumÂ andÂ averag
#Â FirstÂ typeÂ thatÂ weÂ haveÂ done:
sub1Â =Â int(input(“EnterÂ marksÂ inÂ sub1:Â “))
sub2Â =Â int(input(“EnterÂ marksÂ inÂ sub2:Â “))
sub3Â =Â int(input(“EnterÂ marksÂ inÂ sub3:Â “))
sub4Â =Â int(input(“EnterÂ marksÂ inÂ sub4:Â “))
sub5Â =Â int(input(“EnterÂ marksÂ inÂ sub5:Â “))
totalÂ =Â sub1Â +Â sub2Â +Â sub3Â +Â sub4Â +Â sub5Â
##problemÂ hereÂ isÂ thatÂ weÂ haveÂ toÂ writeÂ 5Â differentÂ input()
#toÂ avoidÂ repeatingÂ sameÂ thingÂ weÂ usedÂ loops
#TypeÂ 2:Â useÂ loop
totalÂ =Â 0
forÂ iÂ inÂ range(5):
Â Â Â Â mÂ =Â int(input(“EnterÂ theÂ marksÂ inÂ subjectÂ “+str(i+1)+“:Â “))
Â Â Â Â total+=m
print(“TotalÂ afterÂ stepÂ 2:Â “,total)

#methodÂ 2Â avoidÂ usÂ fromÂ writingÂ samethingÂ againÂ andÂ againÂ –Â usedÂ loopÂ instead
#problemÂ hereÂ is:Â weÂ lostÂ theÂ individualÂ marks

totalÂ =Â 0
marksÂ =Â []
forÂ iÂ inÂ range(10):
Â Â Â Â mÂ =Â int(input(“EnterÂ theÂ marksÂ inÂ subjectÂ “+str(i+1)+“:Â “))
Â Â Â Â marks.append(m)
Â Â Â Â total+=m
print(f“MarksÂ obtainedÂ inÂ eachÂ subjectÂ isÂ {marks}Â andÂ theÂ totalÂ marksÂ isÂ {total})

st1Â =Â [65,Â 78,Â 90,Â 54,Â 69,Â 90,Â 87,Â 69,Â 75,Â 76]
st2Â =Â [65,Â 78,Â 90,Â 94,Â 69,Â 90,Â 87,Â 69,Â 75,Â 76]
st3Â =Â [65,Â 78,Â 90,Â 54,Â 69,Â 50,Â 87,Â 69,Â 75,Â 76]
st4Â =Â [65,Â 78,Â 90,Â 54,Â 69,Â 92,Â 87,Â 69,Â 75,Â 76]
highest_marksÂ =Â []

forÂ iÂ inÂ range(10):
Â Â Â Â ifÂ st1[i]Â >Â st2[i]Â andÂ st1[i]Â >Â st3[i]Â andÂ st1[i]Â >Â st4[i]:
Â Â Â Â Â Â Â Â highest_marks.append(st1[i])
Â Â Â Â elifÂ st2[i]Â >Â st1[i]Â andÂ st2[i]Â >Â st3[i]Â andÂ st2[i]Â >Â st4[i]:
Â Â Â Â Â Â Â Â highest_marks.append(st2[i])
Â Â Â Â elifÂ st3[i]Â >Â st2[i]Â andÂ st3[i]Â >Â st1[i]Â andÂ st3[i]Â >Â st4[i]:
Â Â Â Â Â Â Â Â highest_marks.append(st3[i])
Â Â Â Â #ifÂ st4[i]Â >Â st2[i]Â andÂ st4[i]Â >Â st3[i]Â andÂ st4[i]Â >Â st1[i]:
Â Â Â Â else:
Â Â Â Â Â Â Â Â highest_marks.append(st4[i])
print(“highestÂ marksÂ inÂ eachÂ subjectÂ is:Â “,highest_marks)

#insert()
st1.insert(0,100)
print(st1)
#appendÂ willÂ addÂ atÂ theÂ back
#insertÂ takesÂ theÂ positionÂ numberÂ –Â youÂ canÂ addÂ atÂ anyÂ position

Â

DAY 9 – 25 AUGUST 2022:  LIST – 2 and TUPLE INTRO

list1 = [3,5.4,False,“Hello”,[2,3,4]]
#append – by default adds at the end
#insert – takes position also to add

list1[1] = 100
print(list1)

#List is Mutable ; String is Immutable
list2 = list1  #list2 will have same values as list1
list3 = list1.copy()   #list3 will be duplicate copy of list1
#when we say equal to : list2 is not created different set of values
## they all point to same data in the memory
## one data and two names are created
# when we do copy – it is like photocopy, duplicate copy is
## created and they are separate- list1 and list3 have no connection after this
print(“Printing after 1 Iteration”)
print(list1,“\n”,list2,“\n”,list3)
#as expected all 3 have same list of values
list1.append(999)
list2.append(“mango”)
list3.append(“india”)
print(“Printing after 2 Iteration”)
print(list1,“\n”,list2,“\n”,list3)
# there are 2 methods to remove as well:  remove() – value and pop() – position
list1.pop(0)
list3.remove(False)
if False in list3:
list3.remove(False)
else:
print(“False is no longer in the list”)
print(“List 2: “,list2)
print(“List 3: “,list3)
pos = 100
if len(list1)>pos:
list1.pop(pos)
else:
print(f{pos} index is not in the list”)

list1 = [5,10,100,70,90,90,90,40]
list1.reverse()  #reverse() method doesnt return anything (none)
print(list1)
list1.sort()  #sort is done in the increasing order
print(“List after sorted: “,list1)

# how to sort in decreasing order?
list1.sort(reverse = True)
#list1.reverse()
print(” “,list1)
count_of_90 = list1.count(90)
print(f“There are {count_of_90} values with 90″)
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
list3 = list1 + list2
print(list3)
#extend()
list1.extend(list2)
print(list1)

#WAP where we input date, month and year in numbers
# and display as – date(st/nd/rd/th) Month_in_text Year
# eg. date = 25  month = 8 year = 2022
# output would be 25th August 2022
month_txt = [‘January’‘February’,‘March’,‘April’,‘May’,
‘June’‘July’,‘August’,‘Setember’,‘October’,
‘November’‘December’]
date_th = [‘st’,‘nd’,‘rd’] + 17*[‘th’] + [‘st’,‘nd’,‘rd’] +7*[‘th’] +[‘st’]
date = int(input(“Enter the Date: “))
month = int(input(“Enter the Month: “))
year = input(“Enter the Year: “)
result = str(date)+date_th[date-1]+” “ + month_txt[month-1]+” “ + year
print(result)

#Assignment: input marks of 5 subjects for 5 students and display
#the highest marks in each subject and also for overall and name the student

#Tuple
#Tuple is immutable version of List
#It is also linear collection, can store multiple values
#but we cant edit (just like String)
#Lists are mutable & Tuple and String are Immutable
t1 = ()
print(len(t1))
print(type(t1))
t1 = list(t1)
print(type(t1))
t1.append(5)
t1 = tuple(t1)
print(t1)

# t1 = (5) – this is invalid
t1 = (5,) #- this is valid- this is true only if tuple has ONLY 1 member
t1 = (5,10,15)

#In reading operations Tuple is preferred over List as it is much faster
# So lists are converted into Tuple for reading op like FOR/WHILE
#Lists are preferred for Writing Operations because Tuple is Immutable

DAY 10: AUGUST 26, 2022

#26Â AUGÂ 2022
#Tuple
t1Â =Â (“Sachin”,“Kohli”,“Rohit”)
name1,Â name2,Â name3Â =Â t1Â Â #unpacking
#sinceÂ theÂ sizeÂ ofÂ t1Â isÂ 3,Â weÂ shouldÂ useÂ exactlyÂ 3Â variablesÂ toÂ unpack
print(t1)
print(name1,Â name2,name3)
forÂ iÂ inÂ t1:
Â Â Â Â print(i)

t1Â =Â list(t1)
print(type(t1))
t1.append(“Rishabh”)
t1Â =Â tuple(t1)
print(t1.index(“Kohli”))

#Dictionary
student_marksÂ =Â {‘2018CSE046’:Â [86,39,98,76,69],Â True:“Evening”,3:3}
print(student_marks[‘2018CSE046’])
print(student_marks[True])Â
#ListÂ andÂ DictionaryÂ areÂ mutableÂ /Â StrÂ andÂ TupleÂ –Â theyÂ immutable
student_marks[True]Â =Â “GoodÂ Evening”
print(student_marks[True])

#WAPÂ toÂ inputÂ rollnumberÂ andÂ theÂ marksÂ inÂ 3Â subjectsÂ forÂ 3Â students
all_studentsÂ =Â {}
studentÂ =Â {102:Â [67,87,73]}
all_students.update(student)Â #thisÂ isÂ howÂ youÂ addÂ aÂ dictÂ toÂ another
print(all_students)
#solutionÂ toÂ theÂ aboveÂ question
all_studentsÂ =Â {}
forÂ iÂ inÂ range(3):Â Â #students
Â Â Â Â print(“InputÂ detailsÂ forÂ Student”+str(i+1)+“:Â “)
Â Â Â Â rollÂ =Â int(input(“EnterÂ RollÂ No:Â “))
Â Â Â Â marks_listÂ =Â []Â Â #Â toÂ readÂ nextÂ setÂ ofÂ marks
Â Â Â Â forÂ jÂ inÂ range(3):
Â Â Â Â Â Â Â Â mark=input(“EnterÂ theÂ marksÂ inÂ subject”+str(j+1)+“:Â “)
Â Â Â Â Â Â Â Â marks_list.append(mark)
Â Â Â Â temp_dictÂ =Â {roll:Â marks_list}
Â Â Â Â all_students.update(temp_dict)

print(“AllÂ theÂ studentÂ recordsÂ are:Â “)
print(all_students)

all_students={101:Â [’76’,Â ’78’,Â ’83’],Â 90:Â [’54’,Â ’67’,Â ’90’],Â 95:Â [’95’,Â ’55’,Â ’55’]}
print(all_students.keys())
print(all_students.values())

forÂ i,jÂ inÂ all_students.items():
Â Â Â Â print(f“KeyÂ isÂ {i}Â andÂ valueÂ isÂ {j})Â

#removeÂ particularÂ keyÂ –Â pop()
#studentÂ withÂ rollÂ noÂ 95Â toÂ beÂ removed
all_students.pop(95)
print(all_students)

#differenceÂ betweenÂ =Â andÂ extend
#Â extendÂ isÂ usedÂ toÂ addÂ 2Â dictionaries
#Â =Â isÂ toÂ assignÂ (l3Â =Â l1Â +Â l2Â =>Â thisÂ doesntÂ existÂ inÂ Dictionary)

#differenceÂ betweenÂ =Â andÂ copy
dict2Â =Â all_students
dict3Â =Â all_students.copy()

#newÂ memberÂ toÂ dict1:
all_students.update({100:Â [56,68,75]})
print(“dict2:Â “,dict2)
#whenÂ youÂ tryÂ addÂ duplicateÂ key,Â oldÂ valueÂ isÂ replacedÂ withÂ newÂ value
#SoÂ yourÂ dictionaryÂ cantÂ haveÂ duplicateÂ values
print(“dict3:Â “,dict3)
#Â =Â isÂ doingÂ deepÂ copyÂ (sameÂ asÂ List)Â –Â itÂ willÂ pointÂ toÂ sameÂ memoryÂ location
#Â copyÂ isÂ calledÂ shallowÂ copyÂ (sameÂ asÂ List)Â –Â itÂ willÂ createÂ aÂ duplicateÂ copy

womens_team=Â {“Mithali”:Â 232,Â “Anjum”:Â 130,Â “Jhulan”:Â 202}
mens_teamÂ =Â {“Kohli”:Â 190,Â “Rohit”:Â 185,Â “Rishabh”:Â 50}
indianÂ =[]
forÂ iÂ inÂ womens_team.values():
Â Â Â Â indian.append(i)
forÂ iÂ inÂ mens_team.values():
Â Â Â Â indian.append(i)
print(indian)

womens_team=Â {“Mithali”:Â “India”,Â “Lisa”:“Aus”,Â “Anjum”:Â “India”,“Karen”:“Aus”,Â “Jhulan”:Â “India”}
mens_teamÂ =Â {“Kohli”:Â “India”,Â “JoeÂ Root”:“Eng”,Â “Rohit”:Â “India”,“Babar”:“Pak”,Â “Rishabh”:Â “India”}
indianÂ =[]
forÂ i,jÂ inÂ womens_team.items():
Â Â Â Â ifÂ j.lower()Â ==Â “india”:
Â Â Â Â Â Â Â Â indian.append(i)
forÂ i,jÂ inÂ mens_team.items():
Â Â Â Â ifÂ j.lower()Â ==Â “india”:
Â Â Â Â Â Â Â Â indian.append(i)
print(“IndianÂ playersÂ thatÂ appearsÂ inÂ theÂ listsÂ are:Â \n”,indian)

#SETÂ –Â whichÂ isÂ sameÂ asÂ SetÂ theoryÂ inÂ Mathematics
#setsÂ areÂ alsoÂ declaredÂ usingÂ {}Â justÂ likeÂ aÂ dictionary
#howÂ toÂ identifyÂ setÂ fromÂ dictÂ ?Â dictÂ hasÂ keyÂ andÂ valueÂ both
#butÂ setÂ hasÂ onlyÂ values
#setÂ Â doesntÂ haveÂ indexÂ andÂ alsoÂ cantÂ acceptÂ duplicateÂ values
set1Â =Â {1,2,2,3,3,3,4,4,4,5}
print(f“Set1Â isÂ ofÂ typeÂ {type(set1)}Â andÂ valuesÂ {set1})
#Â Tuples,Â ListÂ andÂ SetsÂ areÂ convertibleÂ intoÂ eachÂ otherÂ forms
set1Â =Â list(set1)
set1.append(7)
set1=set(set1)
print(set1)

list_evenÂ =Â []
forÂ iÂ inÂ tuple(set1):
Â Â Â Â ifÂ i%2==0:
Â Â Â Â Â Â Â Â list_even.append(i)
print(f“TotalÂ evenÂ numbersÂ are:Â {len(list_even)},Â andÂ theÂ valuesÂ areÂ {list_even})

list1Â =Â [44,55,66,44,55,77,88,88,99]
#WapÂ toÂ removeÂ duplicateÂ values:
list1Â =Â list(set(list1))
print(list1)

set1Â =Â set([66,Â 99,Â 44,Â 77,Â 55,Â 88])
set2Â =Â {77,55,88,33,22}
print(set1,Â “\n”,set2)

#Â union,Â intersection,Â subset,Â difference,Â superset

Â

Day 11: August 27, 2022

#Day 11: 27 AUGUST 2022
set1 = {1,3,5,7,9,11}
set2 = {7,9,11,13,15}
print(set1 & set2) #intersection
#common elemets between the sets
print(set1.intersection(set2))

## union: find all the values
print(set1 | set2)
print(set1.union(set2))

#difference
print(set1 -set2)
print(set2.difference(set1))
#symetric difference
print(set1 ^ set2)
print(set2.symmetric_difference(set1))
print(“Working with Update methods”)
#same as union of (set1 – set2 and set2 – set1)
#All the above operations are returning us 3rd set
## update: set1 = set1 | set2
## intersection_update: set1 = set1 & set2
## difference_update: set1 = set1 – set2
##summetric_difference_update: set1 = set1 ^ set2
set1.update(set2)
set1.intersection_update(set2)
set1.difference_update(set2)
set1.symmetric_difference_update(set2)
print(set1)
set1 = {79111315}
print(set1.pop()) #any value is removed
#above method returns the value removed
print(set1)
print(set1.remove(15)) #doesnt return
print(set1) #this will not have 15
set2= {7,11,100,200,300}
print(set1.isdisjoint(set2))
set1 = {1,3,5,7,9#superset of set2- it has all the elemets of set2
set2 = {3,5,7}  #subset of set1- all the
#elements of set2 belongs in set1
print(set1.issuperset(set2))
print(set2.issubset(set1))

#functions
#we are defining a function here
def myfunc1():
print(“Hello”)
print(“How are you?”)
print(“Where are you?”)

#we are not putting returnin in above function
def myfunc2():
print(“Hello 2”)
print(“How are you? 2”)
print(“Where are you? 2”)
return 100
#above function is returning 100

#now I am calling user defined function:
myfunc1()
print(“Ok, now lets go for second time:”)
myfunc1()
print(myfunc1()) #since myfunc1 doesnt return, it prints None
print(myfunc2()) #since myfunc2 has 100 as return

return_val_myfunc2 = myfunc2()
return_val_myfunc1 = myfunc1()
print(“return_val_myfunc2: “, return_val_myfunc2)
print(“return_val_myfunc1: “, return_val_myfunc1)

#wap to input 3 numbers and print its sum
n1 = int(input(“Enter a number: “))
n2 = int(input(“Enter a number: “))
n3 = int(input(“Enter a number: “))
sum = n1 + n2 + n3
print(“Sum is “,sum)

n1 = int(input(“Enter a number: “))
n2 = int(input(“Enter a number: “))
n3 = int(input(“Enter a number: “))
sum = n1 + n2 + n3
return sum

print(“Addition of 3 numbers is “,result)
print(“We have added 3 numbers and the result is “,result)

## Watch Day 11 Video Here

Day 12: August 29, 2022

`#AUG 29 2022#Functions#You can put your questions in the website as well if you want to reach out to me###########################def greetings():  #function definition    print("Hello")    print("How are you?")    print("Where are you now?")print("Calling the function now")greetings()  # calling the function#execution of above function is not complete till greetings() is doneprint("Calling the function again")greetings()def addition_type1():    n1 = int(input("Enter first number: "))    n2 = int(input("Enter second number: "))    sum = n1 + n2    print("Sum of given two numbers is ",sum)addition_type1()# TYPE 1: this is an example of function that doesnt take any input parameter# and doesnt return any valuedef addition_type2():    n1 = int(input("Enter first number: "))    n2 = int(input("Enter second number: "))    sum = n1 + n2    #print("Sum of given two numbers is ",sum)    return sumprint(addition_type2())  #print directlyresult = addition_type2()print("Type 2 function that returns value as ",result)#This is example of Type 2 function where we dont provide any#input but the function returns of outputdef addition_type3(n1, n2):  #we are providing input parameters    print("Values of n1 and n2 are: ",n1,n2)    sum = n1 + n2    #print("Sum of given two numbers is ",sum)    return sum  # return valuesprint(addition_type3(56,21))  #print directlya = int(input("Enter first number: "))b = int(input("Enter second number: "))result = addition_type3(a,b)print("Type 3 function that takes input and also returns value ",result)def addition_type4(n1, n2):  #we are providing input parameters    print("Values of n1 and n2 are: ",n1,n2)    sum = n1 + n2    print("Sum of given two numbers is ",sum)print(addition_type4(56,21))  #print directlya = int(input("Enter first number: "))b = int(input("Enter second number: "))result = addition_type4(a,b)print("Type 3 function that takes input and also returns value ",result)#function that we declare are called User Defined Functions#functions that come preinstalled - print() input() int() - inbuilt functionsdef input_val():    n1, n2 = 40, 30    return n1,n2def calculation(n1,n2):    add = n1 + n2    sub = n1 - n2    mul = n1 * n2    div = n1 / n2    return add, sub,mul,divdef display(r1,r2,r3,r4):    print("Sum of two numbers is ", r1)    print("Difference of two numbers is ", r2)    print("Multiplication of two numbers is ", r3)    print("Ratio of two numbers is ", r4)a,b = input_val()result1, result2, result3, result4 = calculation(a,b)display(result1, result2, result3, result4)# global v local variablex = 50    #global variabledef display_info1():    x = 20  #local to display_info1    print("X is ",x)def display_info2():    print("X is ",x)def display_info3():    global x    print("X is ",x)    x = 30    print("X is ",x)display_info1()  #local will always take precedence over globaldisplay_info2()  #when there is no local, global is calleddisplay_info3()#WAP to input value and check if the number is odd or evendef check_odd(n):    """This function takes a number and checks if the number is odd    It returns True if the number is odd otherwise False    """    if n%2 !=0:        return True    else:        return Falseprint("Enter the series of numbers to check if odd or even, enter non number to end!")while True:    inp = input("Enter a number: ")    if inp.isdigit():        inp = int(inp)        check = check_odd(inp)        if check:            print("Its an Odd number")        else:            print("Its an Even number")    else:        break# Write a function to generate next fibonacci numberdef generate_fibonacci(n1, n2):    return n1 + n2n1 = 0n2 = 1print("Fibonacci numbers are: \n 1")while True:    result = generate_fibonacci(n1, n2)    print(result, end=" ===> ")    ch = input("Hit Enter to continue anyother key to stop!")    n1, n2 = n2, result    if len(ch) != 0:        break#Doc String: Doc string is always the first """ line (after function declaration)#this adds to the documentation of the functionhelp(help)help(input)help(print)`

## Watch Day 12 Video Here

Day 13: August 30, 2022

`#Example of Function that takes REQUIRED POSITIONAL argumentsdef add_numbers(n1,n2):    print("Values of n1 and n2 are: ",n1,n2)#Example of function with default values# in below example n1 and n2 are required# whereas n3, n4,n5 will take default values if not provideddef add_numbers2(n1,n2,n3=3,n4=4,n5=5):    print("Values of n1, n2,n3,n4 and n5 are: ", n1, n2,n3,n4,n5)def add_numbers3(n1,n2):    print("Values of n1 and n2 are: ",n1,n2)add_numbers(5,49)add_numbers2(5,49)add_numbers2(10,20,30)add_numbers2(5,15,25,35,45)add_numbers3(n2=25,n1=36)  #example of non-positional#Required because function definition has 2 parameters so we must#provide exactly 2 values#Positional because the order in which we must give will be#matched from left to rightdef create_report(n1=-1,n2=-1,title=""):    if len(title) !=0:        print("         PERFORMING REPORT         ")        print("-----------------------------------")        print(" TITLE: ",title)    if n1>0:        print("-----------------------------------")        print("  SCORE : ",n1)    if n2>0:        print("-----------------------------------")        print(" MAX SCORE : ",n2)create_report(title="Quality Score for Today",n2=5,n1=3.8)#Variable length arguments#values are not provided, then it shouldnt be createddef players_info(*names, **information):    # * will make this variable a TUPLE    # ** will make this a dictionary    print("Value and Type of names: ",names, type(names))    print("Value and Type of information: ", information, type(information))    if "home" in information.keys():        print("Home of the players is ",information["home"])    if "sports" in information.keys():        print("Sports they play is ",information["sports"])players_info("Sachin","Kohli","Kapil","Laxman",sports = "Cricket", country="India",type="BAT")def isPrime(num):    #flag = True    for i in range(2,num):        if num %i ==0:            return False    return True#WAF to check if a number is a prime or not#continue the function to generate series of prime numbersstart_num = int(input("From which number you want to generate Prime: "))end_num = int(input("Upto which number you want to generate Prime: "))for j in range(start_num, end_num+1):    if isPrime(j):        print(j, end=", ")#Recursive Functions# function that calls itselfdef my_factorial(n):    if n==1:        return 1    return n *my_factorial(n-1)result = my_factorial(9)print("Result : ",result)# 5! = 5 *4!#4! = 4 * 3!# 3! = 3 * 2!# 2! = 2 * 1!# 1! = 1 * 0!# 0! = 1  #ending line for function`

## Watch Day 13 Video Here

August 31, 2022:Â  HOLIDAY

Day 14: September 1, 2022

`#1 Sep 2022#Decorators and some inbuilt functionsdef display_details(name,about):    print("Name: ",name)    print("About: ",about)#example 2def myfunction1():    def my_inside_function():        print("First line from inner function!")        print("I am also getting printed in inside function")    print("Name is getting printed in myfunction1: ",name)    print("Nextline I will call inside function")    my_inside_function()    print("Last line thank you")#example 3:def outer_function1():    print("First line from inneouter_function1 function!")    print("I am also getting printed in outer_function1 function")def outer_function2(param1):    print("First line from inneouter_function1 function!")    print("I am also getting printed in outer_function1 function")    param1()#example 4:def my_function1(x):    def my_fun2(y):        return x+y    return my_fun2if __name__ == "__main__":    # calling the function    name = "Sachin Laxman"    about = "I am an international cricketer and love to play football"    display_details(name, about)    print_details = display_details  # creating another name for the function    print_details(name, about)    myfunction1()    outer_function2(outer_function1)    result = my_function1(10)    print(result(5))############################# Below code in different file#######################import datetimeprint("Current time: ", datetime.datetime.now())  #current system timeprint("Current year: ", datetime.datetime.now().year)print("Current ", datetime.datetime.now().month)print("Current ", datetime.datetime.now().day)print("Current ", datetime.datetime.now().hour)print("Current ", datetime.datetime.now().minute)#print(datetime.datetime.now().strftime('%Y-%m%-%d'))import randomprint(random.randint(10,20))print(random.random())var = "hello"`

## Watch Day 14 Video Here

DAY 15: September 2, 2022

`# CLASS & OBJECTSclass Student:    def print_info(self,name): #self indicates this method is object level        print("I am being called from an object")        self.name = name    def display_name(self):        print("Name is: ",self.name)s1 = Student()s1.print_info("Laxman")s2 = Student()s2.print_info("Rahul Dravid")s3 = Student()s3.print_info("Zaheer Khan")s4 = Student()s4.print_info("Ashish Nehra")s2.display_name()class Calculations:    def get_value(self,a,b):        self.num1 = a        self.num2 = b    def __init__(self,a,b):        self.num1 = a        self.num2 = b    def add_values(self):        print("Sum of two numbers are: ",self.num1 + self.num2)    def multiple_values(self):        print("Multiplication of two numbers is: ",self.num1 * self.num2)c1 = Calculations(21,34)#c1.get_value(21,34)c1.multiple_values()c2 = Calculations(6,8)c2.add_values()class Students:    def __init__(self,name,rollno,ph,email):        self.name = name        self.rollno = rollno        self.phone = ph        self.email = email        self.avg = 0  #default values for now not available        self.grade = "Z" #default values    def calc_avg(self):        sum=0        for i in range(3):            m = int(input("Enter marks: "))            sum+=m  #sum += m        self.avg = sum/3    def calc_grade(self):        if self.avg >80:            self.grade = "A"        elif self.avg >70:            self.grade = "B"        elif self.avg >60:            self.grade = "C"        elif self.avg >50:            self.grade = "D"        else:            self.grade = "E"s1 = Students("Sachin Tendulkar",103,989898989898989898,"sachin@tendulkar.com")s2 = Students("Suresh Raina",109,11118989898,"sraina@tendulkar.com")s1.calc_avg()s1.calc_grade()print("Grade of ",s1.name," is ",s1.grade)`

Â

## Watch Day 15 Video Here

DAY 16:Â  3 SEPTEMBER 2022

`class School: #Base class    def __init__(self):        print("Sample Init function")    def display_school_info(self):        print("Parent class")class Students(School): #Derived class    number_of_students = 0    def __init__(self,name,rollno,ph,email):        self.name = name        self.rollno = rollno        self.phone = ph        self.email = email        self.avg = 0  #default values for now not available        self.grade = "Z" #default values        Students.number_of_students += 1    def calc_avg(self):        sum=0        for i in range(3):            m = int(input("Enter marks: "))            sum+=m  #sum += m        self.avg = sum/3    def calc_grade(self):        if self.avg >80:            self.grade = "A"        elif self.avg >70:            self.grade = "B"        elif self.avg >60:            self.grade = "C"        elif self.avg >50:            self.grade = "D"        else:            self.grade = "E"    @classmethod    def display_info(cls):        print("Current number of students are: ",Students.number_of_students)s1 = Students("Sachin Tendulkar",103,989898989898989898,"sachin@tendulkar.com")s2 = Students("Suresh Raina",109,13118989898,"sraina@tendulkar.com")s3 = Students("Dhoni",119,14118989898,"sraina@tendulkar.com")s4 = Students("Kapil",120,14618989898,"sraina@tendulkar.com")s1.calc_avg()s1.calc_grade()print("Grade of ",s1.name," is ",s1.grade)print("#########################")print("Name: ",s1.name)print("Email: ",s1.email)print("Number of students: ",s1.number_of_students)print("#########################")print("Name: ",s2.name)print("Email: ",s2.email)print("Number of students: ",s2.number_of_students)print("#########################")print("Name: ",s3.name)print("Email: ",s3.email)print("Number of students: ",s3.number_of_students)print("#########################")print("Name: ",s4.name)print("Email: ",s4.email)print("Number of students: ",s4.number_of_students)print("#########################")Students.display_info()# Inheritance : The derived class (child class) gets access to all the members of Base (parent) class# except those which are already present in derived (child) classclass School:    def __init__(self):        print("This is Init in School")    def display_info(self):        print("Printing from Display School")class Student (School):    def __init__(self):        print("This is Init in Student")    def display(self):        print("Printing from Display Student")class Teacher(School):    def __init__(self):        print("This is Init in Teacher")    def display(self):        print("Printing from Display Teacher")sc = School()st = Student()t1 = Teacher()`

## Watch Day 16 Video Here

DAY 17:Â  5 SEPTEMBER 2022

`class City:    def __print_data(self):        #putting double underscore in front of the        # name(method or variable) will make it private        print("Sample method")class School(City):    def __init__(self, name, age):        print("This is Init in School")        self.name = name        self.age = age    def display_info(self):        print("Printing from Display School")        print("Name  : ", self.name)        print("Age   : ",self.age)class Student (School):    def __init__(self, name, age, marks):        School.__init__(self,name, age)        self.marks = marks        print("This is Init in Student")    def display(self):        print("Printing from Display Student")        School.display_info(self)        print("Marks    :",self.marks)class Teacher(School):    def __init__(self,name,age,salary):        School.__init__(self,name,age)        print("This is Init in Teacher")        self.salary = salary    def display(self):        print("Printing from Display Teacher")        School.display_info(self)        print("Salary    :", self.salary)st = Student("Sachin", 16, 88)t1 = Teacher("Kapil", 49, 85000)st.display()t1.display()t1.__print_data()#Attributes of Students: Name, Age, marks#Attributes of Teachers: Name, Age, salary#Encapsulation: information hiding# eg Parent class doesnt want to share its method with derived class#write a program to check is a number is prime or notclass CheckPrime:    def __init__(self, number):        self.num = number        self.isPrimeVar = False        self.isValid = False    def checkvalid(self):        if self.num <2:            print("Not a valid number to check")            self.isValid = False        else:            self.isValid = True    def calculatePrime(self):        self.checkvalid()        if self.isValid:            self.isPrimeVar = True            for i in range(2,self.num//2): #10: 2,3,4 => 15: 2,3,4,5,6                if self.num%i ==0:                    self.isPrimeVar = False                    break        else:            self.isPrimeVar = False    def isPrime(self):        self.calculatePrime()        return self.isPrimeVarif __name__ == '__main__':    st,en = 500,1500    st2,en2 = 1,300    st3,en3 = 50,900    st4,en4 = 5000, 10000    for i in range(st,en+1):        chkPrime = CheckPrime(i)        result = chkPrime.isPrime()        if result:            print(i, end=", ")    print("\n\n Next Output: \n")    for i in range(st2,en2+1):        chkPrime = CheckPrime(i)        result = chkPrime.isPrime()        if result:            print(i, end=", ")    print("\n\n Next Output: \n")    for i in range(st3,en3+1):        chkPrime = CheckPrime(i)        result = chkPrime.isPrime()        if result:            print(i, end=", ")    print("\n\n Next Output: \n")    for i in range(st4,en4+1):        chkPrime = CheckPrime(i)        result = chkPrime.isPrime()        if result:            print(i, end=", ")`

## WATCH DAY 17 VIDEO

DAY 18: September 6, 2022

`#SQLITE 3:import sqlite3 as sqcon = sq.connect('studentsrecord.db')cursorobj = con.cursor()#cursorobj.execute("Drop Table Students")create_table_student= "CREATE TABLE STUDENTS( ROLLNO INT, NAME VARCHAR(18), " \                      "FEES REAL, ADM_DATE DATE, AGE INT, PRIMARY KEY (ROLLNO))"#cursorobj.execute(create_table_student)# C of CRUD: Create data (Insert)insert1 = "INSERT INTO STUDENTS VALUES(103,'Virat Kohli', 3500.50, '12-APR-2021',12)"#cursorobj.execute(insert1)insert1 = "INSERT INTO STUDENTS(ROLLNO,NAME, AGE) VALUES(104,'Rohit Sharma',8)"#cursorobj.execute(insert1)# R of CRUD: Read => SELECTselect1 = "Select * from Students"cursorobj.execute(select1)values = cursorobj.fetchall()print(values)for i in values:    print(i[1])# U for Update (CRUD)update_query = "Update Students set Fees = 1508.20 Where RollNo=104"cursorobj.execute(update_query)# D for Delete (CRUD)delete_str = "Delete from Students where Rollno = 102"#cursorobj.execute(delete_str)con.commit()`

#### Access Database Study Material

DAY 19: September 7, 2022

`# OLTP - Online Transaction Processing - live applications# OLAP - Online Analytical Processing: Data Analytics, Machine Learning, Data Science, Data Warehouse,## Business Intelligence#SQLITE 3:import sqlite3 as sqfrom datetime import date  #datatime has datetime, date and timecon = sq.connect('studentsrecord.db')cursorobj = con.cursor()select1 = "Select max(RollNo) from Students"cursorobj.execute(select1)values = cursorobj.fetchone()max_roll = values[0]#print(max_roll)fees_list = [2000,2500,2300,2400,1500,1600,1700,1800,1900,2000,2100,2200,2300,2400,2500,2600,2700]# Part 1: Steps to demonstrate Insert using dynamic querywhile False:    #RollNo: Look at the max value in the database, add one to it    RollNo = max_roll+1    max_roll+=1    #Name    name = input("Enter the Name of the Student: ")    #Age    age = int(input("Enter the age of the Student: "))    #Adm Date - default today's date    adm_date = date.today()    #Fees - read from a list based on age    fees = fees_list[age]    #We have to assign values dynamically to the sql query    insert1 = "INSERT INTO STUDENTS(ROLLNO,NAME, AGE,ADM_DATE,FEES) VALUES(?,?,?,?,?)"    cursorobj.execute(insert1,(RollNo,name,age,adm_date,fees))    con.commit()    ch=input("Enter Zero to stop it: ")    if ch=='0':        breakselect1 = "Select * from Students where rollno=104"cursorobj.execute(select1)values = cursorobj.fetchall()print(values)select1 = "Select * from Students where age>8"cursorobj.execute(select1)values = cursorobj.fetchall()print(values)select1 = "Select * from Students where age>8 and name like 'S%' "cursorobj.execute(select1)values = cursorobj.fetchall()print(values)select1 = "Select * from Students where age between 9 and 12"cursorobj.execute(select1)values = cursorobj.fetchall()print(values)`

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

PRACTICE SQL (Select command only) at:Â  livesql.oracle.com

Create an account and you have the complete access:

Â

select Employee_ID, First_name, last_name, Phone_number from HR.Employees;

select First_name, last_name, first_name ||’ ‘|| last_nameÂ  as FullName from HR.Employees;

select * from HR.Employees;

select count(Employee_ID) from HR.Employees;

select sum(Salary) from HR.Employees where department_ID = 90;

select department_ID, avg(Salary) as AVG_SALARY from HR.Employees group by department_ID order by AVG_SALARY DESC;

## Watch Day 19 Video Here

DAY 20: September 8, 2022

`import osprint(os.name)#current working directoryprint(os.getcwd())print(os.listdir())filefound = Falsefor i in os.listdir():    if i=='mydrawing.png':        print("File found")        filefound = True        os.rename('mydrawing.png', 'myowndrawing.png')if filefound==False:    print("Current Folder doesnt have this file")if os.name=='nt':    os.system('cls')else:    os.system('clear')print("Screen is cleared!")from pathlib import Path#os.makedirs("D:/Sep8data")#os.remove("D:/Sep8data/sample.txt") # will remove files only#use rmdir to remove folders#os.rmdir("D:/Sep8data")import datetimecontent = Path("C:/Users/Hp/PycharmProjects")#iterate through given directoryfor c in content.iterdir():    print(c.name)dir_content = os.scandir("C:/Users/Hp/PycharmProjects/pr1")for dir_c in dir_content:    dir_time = dir_c.stat().st_mtime    dir_timestamp = datetime.datetime.fromtimestamp(dir_time).strftime("%Y-%m-%d %H:%M")    print(dir_time, " : ",dir_timestamp)file_obj = open("file1.txt","r")#open takes 2 parameters: filename with directory & mode## mode: r - read; w-write a-add to the existing content#reading option 1: read() -can read any \$ of numberprint(file_obj.read())file_obj.seek(0)print("======================")print(file_obj.read(500))file_obj.seek(0)#reading option 2: readline() - maximum you can read is one lineprint(file_obj.readline(7000))#reading option 3:readlines() - you can read any number of linesprint(file_obj.readlines())file_obj.seek(0)entire_lines = file_obj.readlines()print(type(entire_lines))print(entire_lines)print("Total lines of text: ",len(entire_lines))print("10th line = ",entire_lines[9])#close the filefile_obj.close()#### Write content to the file## this will delete the previous content completely##file_obj = open("file1.txt","a+")txt = "This is the sample text to be added"file_obj.write(txt)file_content_list = ["First line\n","second line to be added\n","Third line"]file_obj.writelines(file_content_list)file_obj.close()`

## Watch Day 20 Video Here

DAY 21: September 9, 2022

`################################# WORKING WITH JSON  ##############################JSON files - how to work with them#JavaScript Object Notationdata = '''{    "Name": "Sachin",    "Game": "Cricket",    "Interests": [        "Playing Music",        "Driving Cars",        "Sleeping"],    "Address": {        "Street": "121, ABC Road",        "Locality":"Bandra",        "City": "Mumbai"    },    "Phone": [        {            "Type":"Personal Mobile",            "Number":"123456"        },        {            "Type":"Landline",            "Number":"323456"        }    ]}'''#load / loads /dump  / dumpsimport jsondata_dict = json.loads(data)print(data_dict)print(data_dict["Interests"])#reading the data from a file - load()file_handle = open("json_demo.json","r")data_dict2 = json.load(file_handle)print(data_dict2)print(data_dict2['Address'])file_handle.close()########## Writing JSON object to Screen (dumps) & File (dump)data_output = json.dumps(data_dict2, indent=4)print(data_output)file_handle2 = open("json9Sep.json","w")json.dump(data_dict2,file_handle2, indent=4, sort_keys=True)file_handle2.close()################################## WORKING WITH CSV    #############################import csvfile_handle = open("D:/dataset/csvdata.csv")csv_obj = csv.reader(file_handle,delimiter = '|')row_count = 0header = []for row in csv_obj:    if row_count==0:        header = row        row_count = 1    else:        print(header[0]," : ",row[0])file_handle.close()h_list = ["Employee","Department","EmailID"]list1 = ["Sachin","Marketing","s@c.com"]list2 = ["Rahul","Sales","r@c.com"]file_handle2 = open("D:/dataset/Sep9csv.csv","w")csv_obj2 = csv.writer(file_handle2,delimiter=';')csv_obj2.writerow(h_list)csv_obj2.writerow(list1)csv_obj2.writerow(list2)file_handle2.close()`

## Watch Day 21 Video Here

DAY 22: September 10, 2022

`import threadingimport timedef thread_func():    for i in range(5):        print("Child Thread Has Now Started")        time.sleep(1)def thread_func2():    for i in range(5):        print("Second Child Thread Has Now Started")        time.sleep(1)t1 = threading.Thread(target=thread_func)t2 = threading.Thread(target=thread_func2)t3 = threading.Thread(target=thread_func2)t1.start()t2.start()t3.start()t3.join()t1.join()t2.join()######  Accessing Critical Section#### by acquiring and releasing the lockimport threadingimport time#global variablex=0def increment():    global x    x+=1def perform_task(lock):    for i in range(5):        lock.acquire()        increment()        time.sleep(1)        lock.release()def main_task():    global x    x = 0    lock = threading.Lock()    t1 = threading.Thread(target=perform_task,args=(lock,))    t2 = threading.Thread(target=perform_task,args=(lock,))    t3 = threading.Thread(target=perform_task,args=(lock,))    t4 = threading.Thread(target=perform_task,args=(lock,))    #start the thread    t1.start()    t2.start()    t3.start()    t4.start()    #join - wait until threads are done executing    t1.join()    t2.join()    t3.join()    t4.join()for i in range(15):    main_task()    print(f"Iteration {i+1}: x = {x}")`

Â

DAY 23: SeptemberÂ  12Â  Â 2022

`# Topic: ERROR HANDLING# 3types of errors:## 1. Syntax error: not following the given rule## print("Hello## Syntax errors have to be corrected only then program can run## 2. Logical error## If I have 5 apples and I get 3 more from my brother, how many apples do I have?print(5 - 3) # logical error## 3. Runtime error - when you get error at the runtime mostly based on the valuesa=10b=2c=a/b   #ZeroDivisionError#num1 = int(input("Enter a number: "))   #ValueErrorfile_handle = open("file1.txt")  #FileNotFoundError#How to handle runtime errors:#1. to identify the block of code that can give you runtime error#2. We put that block in try#3. using except keyword, catch that error#4. (optional) else: code that will run if no error#5. (optional) finally: the code in this will run irrespective of error### Method 1: we have nested trytry:    num1 = int(input("Enter the numerator: "))    num2 = int(input("Enter the denominator: "))except ValueError:    print("Sorry, please enter a valid number and try again!")else:    try:        div = num1/num2    except ZeroDivisionError:        print("Since numerator is zero, we can not proceed!")    else:        print("The division is ",div)## Method 2: use single trytry:    num1 = int(input("Enter the numerator: "))    num2 = int(input("Enter the denominator: "))    div = num1 / num2except ValueError:    print("You have not entered valid number.")except ZeroDivisionError:    print("Can not proceed further as you have entered zero in denominator")except Exception:    print("Some error has occured but recheck and try again!")else:    print("The answer is ",div)finally:    print("Thank you for using the program")`

## Watch Day 23 Video Here

DAY 24: SeptemberÂ  13Â  Â 2022

Â

`### NUMPY## Matrix like structureimport numpy as npdata = range(16)#range() takes 3 parameters: start val =0, end = 16(upto/excluding), increment =1mat1 = np.reshape(data,(4,4))print(mat1)mat1 = np.reshape(data,(2,8)) #(rows,cols)print(mat1)mat2 = np.zeros((3,4))print(mat2)mat3 = np.ones((3,3))print(mat3)mat4 = np.full((4,4),4)print(mat4)data = [[2,5,4],[1,0,1],[3,5,2]]print(type(data))mat5 = np.array(data)print(mat5)print(type(mat5))#second row second columnprint(mat5[1,1]) #left of , is for rows and right is for columns#first rowprint(mat5[0,:]) #: start from 0 and go upto endprint(mat5[0])#second and third row for first and second columnprint(mat5[1:,:2])data = [[3,4,2],[1,2,1],[3,2,5]]mat6 = np.array(data)print("Matrix 5: \n",mat5)print("Matrix 6: \n",mat6)print("#perform addition:")print(mat5 + mat6) #additionprint(np.add(mat5,mat6))print("#perform subtraction:")print(mat5 - mat6) #additionprint(np.subtract(mat5,mat6))print("#perform multiplication:")print(mat5 * mat6) #additionprint(np.multiply(mat5,mat6))print("#perform matrix multiplication:")#What you see above is simple multiplication, not#Matrix Multiplication# For matrix multiplication to happen: compare #rows and #columns# A(a*b) : a number of rows and b number of columns# B(m*n) : m number of rows and n number of columns# for A MATMUL B , b should be equal to m, output matrix is (a * n)# for B MATMUL A, n should be equal to a, output matrix is (m * b)#please refer your Matrix chapter for calculation stepsprint(mat5 @ mat6)print(np.matmul(mat5,mat6))print("#perform division:")print(mat5 / mat6)print(np.divide(mat5,mat6))print("#perform dot multiplication:")print(mat5.dot(mat6))print("Number of rows and columns in Matrix 6: ",np.shape(mat6))#iterate through values using flatfor e in mat6.flat:    print(e)import matplotlib.pyplot as pltx = np.arange(0, 3*np.pi,0.3)y = np.sin(x)plt.plot(x,y)plt.show()`

## Watch Day 24 Video Here

DAY 25: SeptemberÂ  14Â  2022

Hi all.. due to some urgent work, I will not be able to take session today. We will take  30 min extra on September 15 and 16 and wrap up our training. Thanks for your understanding and sorry for  change in schedule.

DAY 26: SeptemberÂ  15Â  2022

Â

`# 3 variables linear algebra problem# 2x +5y +2z = -38  # 6 -40 - 4 = -38# 3x - 2y +4z = 17  # 9 +16 - 8 = 17# -6x + y -7z = -12import numpy as np# A = Coefficient matrixA = [[2,5,2],[3,-2,4],[-6,1,-7]]A = np.array(A)# v = variable# v = [[x],[y],[z]] - we need to find the values# O = OuputO = [[-38],[17],[-12]]O = np.array(O)# A * v = O#We know the value of A and O and find the value of v# v = A inv * O#if determinand of A is non-zero only then inverse of the matrix can be calculateddet_A = np.linalg.det(A)if det_A ==0:    print("Solution is not possible")else:    Inv_A = np.linalg.inv(A)    v = np.matmul(Inv_A,O)    print("Solution is: ",v)    print("Values of X, Y, Z are: ",v[0,0],v[1,0],v[2,0])########## PANDAS  ############import pandas  as pdplayer_stats = {"Name":["Sachin","Laxman","Rahul","Zaheer","Ashish"],                "Type": ["Batting","Batting","Batting","Bowling","Bowling"],                "Runs": [12111, 9898,11213,4500,1200]}print(type(player_stats))print(player_stats)player_stats = pd.DataFrame(player_stats)print(type(player_stats))print(player_stats)fruit_prod = [["Apples", 400,390],["Oranges", 389,411],["Bananas",295,656],["Mangoes",568,451]]fruit_prod = pd.DataFrame(fruit_prod,columns=["Fruit",2021, 2022], index=["January","February","March","April"])print(fruit_prod)#Reading the data from github location#My github location:  github.com/swapnilsauravdata_set = pd.read_csv("https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/Mall_Customers.csv")print(data_set)print(data_set.head()) #first 5 rowsprint("Specific value:")print(data_set['Annual Income (k\$)'][0])#There are 2 ways to read the value from a dataframe:# 1) using the index name or column name: df.loc[]# 2) read column and row using number: df.iloc[]#first 3 rows and first 3 columns - ilocprint("1. First three rows and first three columns: \n",data_set.iloc[0:3,2:5])print("2. ",data_set.loc[[0,12,21,31],:])print("3. ",data_set.loc[[0,12,21,31],["Gender","Age","Spending Score (1-100)"]])`

## Watch Day 26 Video

DAY 27: SeptemberÂ  16Â  2022

`#Plotting a Histogram Graphimport matplotlib.pyplot as pltimport numpy as npdata1 = np.random.normal(100,10,200)data2 = np.random.normal(60,10,200)data3 = np.random.normal(100,20,200)data4 = np.random.normal(120,5,200)fig = plt.figure()ax = fig.add_axes([0,0,1,1])data_all = [data1,data2,data3,data4]boxplt = ax.boxplot(data_all)plt.show()`
`#Histogram using Matplotlibimport matplotlib.pyplot as pltimport numpy as npdata = np.random.normal(50,10,100000)plt.hist(data)plt.savefig("hist1.png")plt.show()#Boxplot using Matplotlibimport matplotlib.pyplot as pltimport numpy as npdata = np.random.normal(50,10,200)plt.boxplot(data)plt.title("Compare Delivery Times")plt.suptitle("For Product A")plt.xlabel("Products")plt.ylabel("Delivery Days")plt.savefig("boxplot1.png")plt.show()#Multiple Boxplot using Matplotlibimport matplotlib.pyplot as pltimport numpy as npdata = np.random.normal(0,10,200)data2 = np.random.normal(70,20,20000)data3 = np.random.normal(130,5,200)data4 = np.random.normal(0,3,200)fig,ax = plt.subplots()ax.boxplot([data,data2,data3,data4])#plt.boxplot(data)plt.title("Compare Delivery Times")plt.suptitle("For Product A")plt.xlabel("Products")plt.ylabel("Delivery Days")plt.savefig("boxplot1.png")plt.show()#Plotting stacked bar chartimport matplotlib.pyplot as pltimport numpy as npfruits = ['Apple','Banana','Cherry','Mango']jan = [112,98,67,45]feb = [82,88,47,65]mar = [102,108,37,145]apr = [55,55,55,55]jan_feb = np.add(jan,feb).tolist()jan_feb_mar = np.add(jan_feb,mar).tolist()#bars = np.add(jan,feb).tolist()positions = [0,1,2]plt.bar(fruits,jan)plt.bar(fruits,feb,bottom=jan)plt.bar(fruits,mar,bottom=jan_feb)plt.bar(fruits,apr,bottom=jan_feb_mar)plt.show()#Scatter plot using matplotlibimport matplotlib.pyplot as pltimport numpy as npjan = [112,98,67,45]feb = [82,88,47,65]plt.scatter(x=jan,y=feb)plt.show()#Heatmap using matplotlibimport matplotlib.pyplot as pltimport numpy as npdata = np.random.random((30,30))#print(data)plt.imshow(data, cmap='hot')plt.show()`

DAY 28: September  17  2022

## Basic Python Exercises

Problem 1: Area of a Circle

 from math import pir = float(input (“Input the radius of the circle : “))print (“The area of the circle with radius ” + str(r) + ” is: ” + str(pi * r**2))

Program 2: Accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers

 values = input(“Input some comma seprated numbers : “)list = valuestuple = tuple(list)print(‘List : ‘,list)print(‘Tuple : ‘,tuple)

Program 3: Accepts an integer (n) and computes the value of n+nn+nnn.

 a = int(input(“Input an integer : “))n1 = int( “%s” % a )n2 = int( “%s%s” % (a,a) )n3 = int( “%s%s%s” % (a,a,a) )print (n1)print(n2)print(n3)print (n1+n2+n3)

Program 4: Program to print the documents (syntax, description etc.) of Python built-in function(s).

 print(abs.__doc__)

Program: Check whether a specified value is contained in a group of values

 def is_group_member(group_data, n):    for value in group_data:        if n == value:            return True    return Falseprint(is_group_member([1, 5, 8, 3], 3))print(is_group_member([5, 8, 3], 1))

Program: Create a histogram from a given list of integers

 def histogram( items ):    for n in items:        output = ”        times = n        while( times > 0 ):          output += ‘*’          times = times – 1        print(output) histogram([2, 3, 6, 5])

Program: Concatenate all elements in a list into a string

 def concatenate_list_data(list):    result= ”    for element in list:        result += str(element)    return result print(concatenate_list_data([1, 5, 12, 2]))

Program: Program to compute the greatest common divisor (GCD) of two positive integers.

 def gcd(x, y):    gcd = 1     if x % y == 0:        return y     for k in range(int(y / 2), 0, –1):        if x % k == 0 and y % k == 0:            gcd = k            break    return gcd print(gcd(12, 17))print(gcd(12, 66))

Program: Future value of a specified principal amount, rate of interest, and a number of years

 amt = 10000int = 3.5years = 7 future_value  = amt*((1+(0.01*int)) ** years)print(round(future_value,2))

Program: Program to locate Python site-packages.

 import site;print(site.getsitepackages())

Program: Find out the number of CPUs using

 import multiprocessingprint(multiprocessing.cpu_count())

Program: Parse a string to Float or Integer

 n = “246.2458”print(float(n))print(int(float(n)))

Program: List all files in a directory in Python

 import globfile_list = glob.glob(‘*.*’)print(file_list)

## Data Types Programs

Program: Program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string

 def string_both_ends(str):    if len(str) < 2:        return ”     return str[0:2] + str[-2:] print(string_both_ends(‘Thunder’))print(string_both_ends(‘Bird’))print(string_both_ends(‘A’))

 def add_string(str1):    length = len(str1)     if length > 2:        if str1[-3:] == ‘ing’:            str1 += ‘ly’        else:            str1 += ‘ing’     return str1 print(add_string(‘ab’))print(add_string(‘abc’))print(add_string(‘string’))

Program: Strip a set of characters from a string

 def strip_chars(str, chars):    return “”.join(c for c in str if c not in chars) print(“\nOriginal String: “)print(“The quick brown fox jumps over the lazy dog.”)print(“After stripping a,e,i,o,u”)print(strip_chars(“The quick brown fox jumps over the lazy dog.”, “aeiou”))print()

Program: Format a number with a percentage

 x = 0.25y = –0.25print(“\nOriginal Number: “, x)print(“Formatted Number with percentage: “+“{:.2%}”.format(x));print(“Original Number: “, y)print(“Formatted Number with percentage: “+“{:.2%}”.format(y));print()

Program: Prints the unique words in sorted form from a comma separated sequence of words

 items = input(“Input comma separated sequence of words: “) words = [word for word in items.split(“,”)]print(“,”.join(sorted(list(set(words)))))

Program: Function to create the HTML string with tags around the word(s)

Program: Sort a string lexicographically

 def lexicographi_sort(s):    return sorted(sorted(s), key=str.upper) print(lexicographi_sort(‘This is a long sentence’))print(lexicographi_sort(‘ThisIsASingleWord’))

Program: Reverse words in a string

 def reverse_string_words(text):    for line in text.split(‘\n‘):        return(‘ ‘.join(line.split()[::-1]))print(reverse_string_words(“The quick brown fox jumps over the lazy dog.”))print(reverse_string_words(“Python Exercises.”))

Program: Program to get the largest number from a list

 def max_num_in_list( list ):    max = list[ 0 ]    for a in list:        if a > max:            max = a    return maxprint(max_num_in_list([1, 2, –8, 0]))

Program: Program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples

 def last(n): return n[-1] def sort_list_last(tuples):    return sorted(tuples, key=last) print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))

Program: Print a list after removing specified elements

 color = [‘Red’, ‘Green’, ‘White’, ‘Black’, ‘Pink’, ‘Yellow’]color = [x for (i,x) in enumerate(color) if i not in (0,4,5)] print(color)

Program: Difference between the two lists

 list1 = [1, 2, 3, 4]list2 = [1, 2]print(list(set(list1) – set(list2)))

Program: Sieve of Eratosthenes method, for computing prime number

 def prime_eratosthenes(n):    prime_list = []    for i in range(2, n+1):        if i not in prime_list:            print (i)            for j in range(i*i, n+1, i):                prime_list.append(j) print(prime_eratosthenes(100))

Program: Program to check if a given key already exists in a dictionary

 d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}def is_key_present(x):  if x in d:      print(‘Key is present in the dictionary’)  else:      print(‘Key is not present in the dictionary’)is_key_present(5)is_key_present(9)

Program: Merge two Python dictionaries

 d1 = {‘a’: 100, ‘b’: 200}d2 = {‘x’: 300, ‘y’: 200}d = d1.copy()d.update(d2)print(d)

Program: Sum all the items in a dictionary

 my_dict = {‘data1’:100,‘data2’:-54,‘data3’:247}print(sum(my_dict.values()))

Program: Get the maximum and minimum value in a dictionary

 my_dict = {‘x’: 500, ‘y’: 5874, ‘z’: 560} key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) print(‘Maximum Value: ‘, my_dict[key_max])print(‘Minimum Value: ‘, my_dict[key_min])

Program: Reverse a tuple

 #create a tuplex = (“samplestring”)# Reversed the tupley = reversed(x)print(tuple(y))#create another tuplex = (5, 10, 15, 20)# Reversed the tupley = reversed(x)print(tuple(y))

Program: Find maximum and the minimum value in a set

 #Create a setseta = set([5, 10, 3, 15, 2, 20])#Find maximum valueprint(max(seta))#Find minimum valueprint(min(seta))

## Conditional statements and loops Programs

Program: Construct a specified pattern, using a nested for loop

 n = 5;for i in range(n):    for j in range(n, i, –1):        print(” “),    for k in range(i):        print (‘* ‘),    print(‘ ‘) for i in range(n, 0, –1):    for j in range(n, i, –1):        print(” “),    for k in range(i):        print(‘* ‘),    print(‘ ‘) *         *  *       *  *  *     *  *  *  *   *  *  *  *  *     *  *  *  *       *  *  *         *  *           *

Program: Prints each item and its corresponding type from a list

 datalist = [1452, 11.23, 1+2j, True, ‘w3resource’, (0, –1), [5, 12],{“class”:‘V’, “section”:‘A’}]for item in datalist:   print (“Type of “,item, ” is “, type(item))

Program: Fibonacci series between 0 to 50

 x, y = 0, 1 while y < 50:    print(y)    x, y = y, x + y

Program: Calculate the number of digits and letters in a string

 s = raw_input(“Input a string: “)d=l=0for c in s:    if c.isdigit():        d=d+1    elif c.isalpha():        l=l+1    else:        passprint(“Letters”, l)print(“Digits”, d)

Program: Check the validity of a password

Validation:

Â·        At least 1 letter between [a-z] and 1 letter between [A-Z].

Â·        At least 1 number between [0-9].

Â·        At least 1 character from [\$#@].

Â·        Minimum length 6 characters.

Â·        Maximum length 16 characters.

 import re p = raw_input(“Input your password: “)x = Truewhile x:    if (len(p) < 6 or len(p) > 12):        break    elif not re.search(“[a-z]”, p):        break    elif not re.search(“[0-9]”, p):        break    elif not re.search(“[A-Z]”, p):        break    elif not re.search(“[\$#@]”, p):        break    elif re.search(“\s”, p):        break    else:        print(“Valid Password”)        x = False        break if x:    print(“Not a Valid Password”)

Program: Program to print alphabet pattern ‘A’.

 result_str=“”;      for row in range(0,7):          for column in range(0,7):               if (((column == 1 or column == 5) and row != 0) or ((row == 0 or row == 3) and (column > 1 and column < 5))):                  result_str=result_str+“*”              else:                    result_str=result_str+” ”          result_str=result_str+“\n”      print(result_str); ***   *   *  *   *  *****  *   *  *   *  *   *

Program: A Math Quiz Program

 import randomimport mathprint “Welcome to Math Quiz World”num1= random.randint(1, 10)num2= random.randint(1, 10)num3= random.randint(1, 10)list=[num1, num2, num3]maxNum= max(list)minNum= min(list)sqrtOne= math.sqrt(num1) correct= Falsewhile(correct == False):    guess1= input(“Which number is the highest? “+ str(list) + “: “)    if maxNum == guess1:        print(“Correct!”)        correct = True    else:        print(“Incorrect, try again”) correct= Falsewhile(correct == False):    guess2= input(“Which number is the lowest? ” + str(list) +“: “)    if minNum == guess2:        print(“Correct!”)        correct = True    else:        print(“Incorrect, try again”) correct= Falsewhile(correct == False):    guess3= raw_input(“Is the square root of ” + str(num1) + ” greater than or equal to 2? (y/n): “)    if sqrtOne >= 2.0 and str(guess3) == “y”:        print(“Correct!”)        correct = True    elif sqrtOne < 2.0 and str(guess3) == “n”:        print(“Correct!”)        correct = True    else:        print(“Incorrect, try again”) print(“Thanks for playing!”)

## Functions Programs

Program: Multiply all the numbers in a list

 def multiply(numbers):    total = 1    for x in numbers:        total *= x    return totalprint(multiply((8, 2, 3, –1, 7)))

Program: Calculate the factorial of a number

 def factorial(n):    if n == 0:        return 1    else:        return n * factorial(n-1)n=int(input(“Input a number to compute the factiorial : “))print(factorial(n))

Program: Write a Python function that that prints out the first n rows of the Pascal’s triangle

Note: Pascal’s triangle is an arithmetic and geometric figure first imagined by Blaise Pascal.

 def pascal_triangle(n):   trow = [1]   y = [0]   for x in range(max(n,0)):      print(trow)      trow=[l+r for l,r in zip(trow+y, y+trow)]   return n>=1pascal_triangle(6)

## Search and Sorting Programs

Program: Program for binary search

 def binary_search(item_list, item):    first = 0    last = len(item_list) – 1    found = False    while (first <= last and not found):        mid = (first + last) // 2        if item_list[mid] == item:            found = True        else:            if item < item_list[mid]:                last = mid – 1            else:                first = mid + 1    return found print(binary_search([1, 2, 3, 5, 8], 6))print(binary_search([1, 2, 3, 5, 8], 5))

Program: Bubble sort

 def bubbleSort(nlist):    for passnum in range(len(nlist) – 1, 0, –1):        for i in range(passnum):            if nlist[i] > nlist[i + 1]:                temp = nlist[i]                nlist[i] = nlist[i + 1]                nlist[i + 1] = temp nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]bubbleSort(nlist)print(nlist)

Program: Selection sort

 def selectionSort(nlist):    for fillslot in range(len(nlist) – 1, 0, –1):        maxpos = 0        for location in range(1, fillslot + 1):            if nlist[location] > nlist[maxpos]:                maxpos = location         temp = nlist[fillslot]        nlist[fillslot] = nlist[maxpos]        nlist[maxpos] = temp nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]selectionSort(nlist)print(nlist)

Program: Shell sort

 def shellSort(alist):    sublistcount = len(alist) // 2    while sublistcount > 0:        for start_position in range(sublistcount):            gap_InsertionSort(alist, start_position, sublistcount)         print(“After increments of size”, sublistcount, “The list is”, nlist)         sublistcount = sublistcount // 2 def gap_InsertionSort(nlist, start, gap):    for i in range(start + gap, len(nlist), gap):         current_value = nlist[i]        position = i         while position >= gap and nlist[position – gap] > current_value:            nlist[position] = nlist[position – gap]            position = position – gap         nlist[position] = current_value nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]shellSort(nlist)print(nlist)

Program: Quick sort

 def quickSort(data_list):    quickSortHlp(data_list, 0, len(data_list) – 1) def quickSortHlp(data_list, first, last):    if first < last:        splitpoint = partition(data_list, first, last)         quickSortHlp(data_list, first, splitpoint – 1)        quickSortHlp(data_list, splitpoint + 1, last) def partition(data_list, first, last):    pivotvalue = data_list[first]     leftmark = first + 1    rightmark = last     done = False    while not done:         while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:            leftmark = leftmark + 1         while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:            rightmark = rightmark – 1         if rightmark < leftmark:            done = True        else:            temp = data_list[leftmark]            data_list[leftmark] = data_list[rightmark]            data_list[rightmark] = temp     temp = data_list[first]    data_list[first] = data_list[rightmark]    data_list[rightmark] = temp     return rightmark data_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]quickSort(data_list)print(data_list)

Program: Counting sort algorithm

 def counting_sort(array1, max_val):    m = max_val + 1    count = [0] * m     for a in array1:        # count occurences        count[a] += 1    i = 0    for a in range(m):        for c in range(count[a]):            array1[i] = a            i += 1    return array1 print(counting_sort([1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7))

## Recursion Programs

Program: Program to calculate the sum of a list of numbers using Recursion.

 def list_sum(num_List):    if len(num_List) == 1:        return num_List[0]    else:        return num_List[0] + list_sum(num_List[1:]) print(list_sum([2, 4, 5, 6, 7]))

Program: Think of a recursive version of the function f(n) = 3 * n, i.e. the multiples of 3

 def mult3(n):    if n == 1:        return 3    else:        return mult3(n-1) + 3for i in range(1,10):    print(mult3(i))

Program:  Write a function which implements the Pascal’s triangle:

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

 def pascal(n):    if n == 1:        return [1]    else:        p_line = pascal(n-1)        line = [ p_line[i]+p_line[i+1] for i in range(len(p_line)-1)]        line.insert(0,1)        line.append(1)    return line

Program:  The sum of the squares of two consecutive Fibonacci numbers is also a Fibonacci number, e.g. 2 and 3 are elements of the Fibonacci sequence and 2*2 + 3*3 = 13 corresponds to Fib(7).

 memo = {0:0, 1:1}def fib(n):    if not n in memo:        memo[n] = fib(n-1) + fib(n-2)    return memo[n] def find_index(*x):   “”” finds the natural number i with fib(i) = n “””   if len(x) == 1:      # started by user      # find index starting from 0      return find_index(x[0],0)   else:      n = fib(x[1])      m = x[0]      if  n > m:         return –1      elif n == m:         return x[1]      else:         return find_index(m,x[1]+1) print(” index of a |    a |     b | sum of squares | index “)print(“=====================================================”)for i in range(15):   square = fib(i)**2 + fib(i+1)**2   print( ” %10d |  %3d |   %3d | %14d | %5d ” % (i, fib(i), fib(i+1), square, find_index(square)))

Program: Program to calculate the sum of the positive integers of n+(n-2)+(n-4)… (until n-x =< 0)

 def sum_series(n):    if n < 1:        return 0    else:        return n + sum_series(n – 2) print(sum_series(6))print(sum_series(10))

Program: Write a Python program to calculate the harmonic sum of n-1

The harmonic sum is the sum of reciprocals of the positive integers

 def harmonic_sum(n):    if n < 1:        return 0    else:        return (harmonic_sum(n – 1))+ 1/n print(harmonic_sum(7.0))print(harmonic_sum(4.0))

Program: Program to find  the greatest common divisor (gcd) of two integers.

 def Recurgcd(a, b):    low = min(a, b)    high = max(a, b)     if low == 0:        return high    elif low == 1:        return 1    else:        return Recurgcd(low, high % low) print(Recurgcd(28, 14)

## Date Time Programs

Program: Python script to display the various Date Time formats

 import timeimport datetimeprint(“Current year: “, datetime.date.today().strftime(“%Y”))print(“Month of year: “, datetime.date.today().strftime(“%B”))print(“Week number of the year: “, datetime.date.today().strftime(“%W”))print(“Weekday of the week: “, datetime.date.today().strftime(“%w”))print(“Day of year: “, datetime.date.today().strftime(“%j”))print(“Day of the month : “, datetime.date.today().strftime(“%d”))print(“Day of week: “, datetime.date.today().strftime(“%A”))

Program: Find the date of the first Monday of a given week

 import timeprint(time.asctime(time.strptime(‘2015 50 1’, ‘%Y %W %w’)))

## Class Programs

Program: Program to get all possible unique subsets from a set of distinct integers

Input : [4, 5, 6]

Output : [[], [6], [5], [5, 6], [4], [4, 6], [4, 5], [4, 5, 6]]

 class py_solution:    def sub_sets(self, sset):        return self.subsetsRecur([], sorted(sset))     def subsetsRecur(self, current, sset):        if sset:            return self.subsetsRecur(current, sset[1:]) + self.subsetsRecur(current + [sset[0]], sset[1:])        return [current] print(py_solution().sub_sets([4, 5, 6]))

Program: A class has two methods. First method accept a string from the user, Second method print the string in upper case

 class IOString():    def __init__(self):        self.str1 = “”     def get_String(self):        self.str1 = raw_input(“Please enter a string: “)     def print_String(self):        print(self.str1.upper()) str1 = IOString()str1.get_String()str1.print_String()

Program: Get the class name of an instance

 import itertoolsx = itertools.cycle(‘ABCD’)print(type(x).__name__)

Program: A class constructed by a radius and two methods which will compute the area and the perimeter of a circle

 class Circle():    def __init__(self, r):        self.radius = r     def area(self):        return self.radius ** 2 * 3.14     def perimeter(self):        return 2 * self.radius * 3.14 NewCircle = Circle(8)print(NewCircle.area())print(NewCircle.perimeter())

## File Input Output Programs

Program: Count the frequency of words in a file

 from collections import Counterdef word_count(fname):    with open(fname) as f:        return Counter(f.read().split()) print(“Number of words in the file :”, word_count(“readme.txt”))

Program: Read a file line by line store it into an array

 def file_read(fname):    content_array = []    with open(fname) as f:        # Content_list is the list that contains the read lines.        for line in f:            content_array.append(line)        print(content_array) file_read(‘test.txt’)

Program: Get the file size of a plain file

 def file_size(fname):    import os    statinfo = os.stat(fname)    return statinfo.st_size print(“File size in bytes of a plain file: “, file_size(“test.txt”))

## Regular Expression Programs

Program: Match a string that contains only upper and lowercase letters, numbers, and underscores

 import re def text_match(text):    patterns = ‘^[a-zA-Z0-9_]*\$’    if re.search(patterns, text):        return ‘Found a match!’    else:        return (‘Not matched!’) print(text_match(“The quick brown fox jumps over the lazy dog.”))print(text_match(“Python_Exercises_1”))

Program: Search the numbers (0-9) of length between 1 to 3 in a given string

 import re results = re.finditer(r”([0-9]{1,3})”, “Exercises number 1, 12, 13, and 345 are important”)print(“Number of length 1 to 3”)for n in results:     print(n.group(0))

Program: Abbreviate ‘Road’ as ‘Rd.’ in a given string

Program: Convert camel case string to snake case string

 def camel_to_snake(text):    import re    str1 = re.sub(‘(.)([A-Z][a-z]+)’, r’\1_\2′, text)    return re.sub(‘([a-z0-9])([A-Z])’, r’\1_\2′, str1).lower() print(camel_to_snake(‘PythonExercises’))

Program: Split a string with multiple delimiters

 import retext = ‘The quick brown\nfox jumps*over the lazy dog.’print(re.split(‘; |, |\*|\n‘,text))

Some More Programs to Test Your Skills

 1.      Design a simple Battleship game. It is a strategy type guessing game between you and the computer. The program should create a 5*5 board and computer will conceil its battleship in a perticular row and column (generated using random number). You will be calling “shots” by guessing where the computer has conceiled its battleship. If you guess the position right then computer’s fleet is destroyed and you win. 2.      Generate random password for your gmail ID Password should be a combination of LOWERCASE_CHARS, UPPERCASE_CHARS, DIGITS and SPECIALS CHARS (‘!’, ‘@’, ‘#’, ‘\$’, ‘%’, ‘^’, ‘&’, ‘*’) 3.      Print All Integers That Arenâ€™t Divisible by Either 2 or 3 and Lie between 1 and 50 4.       Number Reverser: This Python number reverser script will reverse any given number. So, 1234 becomes 4321. 5.      URL String Parser: Read a URL string and parse it to get information. Example: www.cardetails.com?model=x&color=black&package=signature&interior=brown&wheels=alloy one can parse the domain name, model, color, package, interior and wheels information from the above URL. Output should look something like this: {‘model’: ‘x’, ‘color’: ‘black’, ‘package’: ‘signature’, ‘interior’: ‘brown’, ‘wheels’: ‘alloy’} Model: x Color: black Package: signature Interior: brown Wheels: alloy 6.      Hangman Program: Write a program to guess the secret word. Enter a word as input and start guessing the game. Initially  _ will be printed to show the number of characters in the word and then as the user guess it correctly the characters appear on the screen. Max wrong guess is 10 and if the guess is correct then chance is not lost. 7.      Write a program that prints the numbers from 1 to 100.   But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. 8.      Dice Roller program for your game of ludo: write a program to generate random number generated between 1-6 (or any range youâ€™d like if you tweak the code), and also you can change the number of dice you want to roll. 9.      Search a Computer For Specific Files In this example, we will see how to use the os.walk() module function to walk a directory tree, and the fnmatch module for matching file names.   What is OS.walk? It generates the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).         dirpath                # is a string, the path to the directory.         dirnames             # is a list of the names of the subdirectories in dirpath (excluding ‘.’ and ‘..’).         filenames            # is a list of the names of the non-directory files in dirpath.         To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).   The fnmatch module is purely a string matching operation. Simple Matching: fnmatch() compares a single file name against a pattern and returns a boolean indicating whether or not they match. The comparison is case-sensitive when the operating system uses a case-sensitive file system.   Filtering: To test a sequence of filenames, you can use filter(). It returns a list of the names that match the pattern argument.

## NO VIDEO - PRACTICE DAY- Practice Above Programs Please

Day 29 : Setember 19, 2022

`#Plotting a Histogram Graphimport matplotlib.pyplot as pltimport numpy as npdata1 = np.random.normal(100,10,200)data2 = np.random.normal(60,10,200)data3 = np.random.normal(100,20,200)data4 = np.random.normal(120,5,200)fig = plt.figure()ax = fig.add_axes([0,0,1,1])data_all = [data1,data2,data3,data4]boxplt = ax.boxplot(data_all)plt.show()import matplotlib.pyplot as pltimport pandas as pddataset = pd.read_csv("https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/student.csv")plt.boxplot(dataset['age'])plt.show()#395 -1 is outlier : 394#394/4 =98.5`

Introduction to Machine Learning

DAY 30: SeptemberÂ  20Â  Â 2022 : Linear Regression

Â

Â

`import pandas as pdimport matplotlib.pyplot as pltdata_df = pd.read_csv("https://raw.githubusercontent.com/swapnilsaurav/MachineLearning/master/2_Marks_Data.csv")#print(data_df)plt.scatter(data_df['Hours'],data_df['Marks'])plt.show()#features:X = data_df.iloc[:,0:1].valuesprint(X)#Target:y = data_df.iloc[:,1].values#pip install scikit-learn packagefrom sklearn.linear_model import LinearRegressionregressor = LinearRegression()#training the modelregressor.fit(X,y)print("Linear Regression Output: ")print("Coefficient/Slope = ",regressor.coef_)print("Intercept /Constant = ",regressor.intercept_)# Y = 7.57 * X + 20.7 = 58.5#37.8 +20.7#predicting using the model:output = regressor.predict(X)output_df = pd.DataFrame({    'Actual': y,    'Predicted': output})print(output_df)`
`Â `

## Watch Day 30 Video here

##### Python For Juniors-2

DAY 1 : 16 AUG 2022

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

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 Pythonprint("\\\\n is used for newline in Python")print()print(5+3);  # this is how we use comment in Pythonprint("5+3"); #text is represented in Python- " / 'print("Good",end=" ")print("Evening")x=10x=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 =100number1 = 50# basic data type: integer (int), float (float), string (str), boolean (bool), complex (complex)# int - no decimal pointsecond_number = -99# typeprint(type(second_number))number3 = -5.0print(type(number3))val1 = "How are you?"print(type(val1))val2 = True  # True or Falseprint(type(val2))#Arithmetic operators:num1 = 54num2 = 5print(num1 + num2)print(num1 - num2)print(num1 * num2) #multiplicationprint(num1 / num2)  #divisionprint(num1 // num2)  #integer division -only integerprint(num1 % num2)  #modulo - remainderprint(num1 ** num2)  #powerimport mathprint(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 - LOOPSnum=6if 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=3if 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 lettersavg = 95#>80: Grade A, 70-80: B, 60-70: C, 50-60: D, less than 50: Eif 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 3num=30#Approach 1:#Calculate:## Best performance: 8 times## Worst performance: 8 times## Average performance: (Best + Worst) / 2if 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: 3num=30if 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 screenscreen = turtle.Screen()screen.bgcolor("light green")screen.title("Turtle Program: September 2, 2022")#create my penpen =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 invisiblepen.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)  # degreepen.hideturtle() #make turtle invisiblepen.left(90)pen.penup()pen.goto(250,250)pen.pendown()#donecol = ["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 randomfor 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_versionprint(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 & whileprint("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=0while 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 numbersfor i in range(5):    print((i*2)+1)print("########")for i in range(1,10,2):    print(i)print("########")n=5for j in range(n):    for i in range(n):        print("*",end=" ")    print()print("########")'''** ** * ** * * ** * * * *'''n=5for j in range(n):    for i in range(j+1):        print("*",end=" ")    print()n=5for j in range(n):    for i in range(n-j):        print("*",end=" ")    print()print("###########")#printing multiplication tablen=1mul = 13for 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=5j=1while j <=count:    i=1    while i<= count:        print("*",end=" ")        i+=1    print()    j+=1while 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":        breakch = int(input("How many students do you have? "))count = 1while 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 1import randomnumber = random.randint(1,100)count=0while 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 2import randomimport timeimport datetime as dtstart = time.time()number = random.randint(1,100)print("======================")print("We are guessing: ",number)print("======================")count=0low,high = 1,100while 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 randomimport timeimport datetime as dtbest_time = 0start = time.time()total_chances = 0for 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

`#Stringstxt1 = 'Hello'txt2 = "Hello how are youer  wekjfdsjf sdjfsdjf jfopdskjpo spodjfopsdfo sodpkfsodpk"txt3 = '''Hellogood eveninghow was your day'''txt4 = """Hellohave 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 / indexingprint(txt2[0]) #first characternum_char = len(txt2) #5print(txt2[num_char-1])#3 to 7 charactersprint(txt2[2:7]) #starting val is including, ending is uptoprint(txt2[0:3]) #first 3 charactersprint(txt2[:3]) #first 3 charactersprint(txt2[num_char-3:num_char]) #last 3 charactersprint(txt2[num_char-3:]) #last 3 charactersprint(txt2)print(txt2[:]) ### backward indexingprint(txt2[-1]) #last charprint(txt2[-num_char]) #first charprint(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 stringfor 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 immutableprint(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

`#Stringstxt1 = "Hello"num = txt1.count("l",0,4)print(num)num = txt1.find("klo") #returns the position of matchprint(num)txt1 = "How are you doing today?"content = txt1.split()  #returns a listprint(content)txt2 = "-------------".join(content) #accepts a list valueprint(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 Listlist1 = [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 * 3print(l3)for i in l3:    print(i)print("###############")for i in range(len(l3)):    print(l3[i])# membership test: inprint(3 in l3)#strings are immutablestr1 = "Hello"#str1[1]="E"#lists are mutablel3[1] = 100print(l3)# inbuiltlist3 = [] #creating a blank listprint(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=0marks = []for i in range(5):    m = int(input("Enter the marks: "))    marks.append(m)    sum+=mprint("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 studentsprint(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 1max= 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= -1for i in range(len(total_marks)):    if max < total_marks[i][0]:        max=total_marks[i][0]print("Highest marks: ",max)### solving using first logicmax= []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 collectionlist1 = [10,3,10,4,10,8,10,2,10]list1.append(6)list1.insert(2,10)print(list1)#pop - removes element from given positionlist1.pop(3)print(list1)#remove - removes the element that you givelist1.remove(10)print(list1)#want to remove all 10, so first count and then run the looptot_ele = list1.count(10)for i in range(tot_ele):    list1.remove(10)print(list1)#reverse the order of the elementslist1.reverse()print(list1)list1.sort() #sort in ascending orderprint(list1)list1.sort(reverse=True) #sort in descending orderprint(list1)#index() - gives the positionprint("Index of 4 is ",list1.index(4))#index will give the position of first occurencelist1 = [3, 4, 8, 2, 6]list2 = list1  #DEEP copy the elementslist3 = list1.copy() #Shallow copy: copies the elementsprint("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+list3list1.extend(list3) #list1 = list1 + list3print(list1)####input:#date: 29#month: 9#year: 2022#output: 29th September 2022date_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] + " "+ yearprint(output)# Tuple: immutable ordered collectionlist1 = [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)  #packinga,b,c,d = t1  #unpackingprint(a,b,c,d)a,b,c,d  = (1,2,3,4)  #unpackingprint(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 copymaindata3 = maindata.copy()  #shallow copytemp = {"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`
`#Setsset1 = {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 listlist1 = list(set(list1))print(list1)set1.add(9)print(set1)#pop will remove a valueset1.pop()#remove will remove the given valueset1.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()#isdisjointprint(set1.isdisjoint(set2))#issupersetprint(set1.issubset(set2))#issubsetprint(set1.issuperset(set2))`

OCTOBER 6, 2022

`list_items = [5,10,15,20,25,30,35,40,45]element = 20pos = -1counter = 0for i in list_items:    if element == i:        pos=counter    else:        counter+=1if 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 sortlist_items = [5,10,15,20,25,30,35,40,45]new_list=list_items.copy()#bubble sort - descending orderfor 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 orderfor 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 searchlist_val = seq_listelement = 45le = len(list_val)fe = 0mid = (le+fe)//2pos = -1while 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) // 2if pos==-1:    print("Element is not in the list")else:    print("Element is found at index ",pos)`

13 OCTOBER 2022

`#Functiondef 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 100mystatements()result = mystatements2("Sachin","Good Morning")print(result)  #None is returnedresult = 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 = 0import mathmath.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,sol2solutions = 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 functionsdef 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)#recursionresult = myfacto(6)print("Factorial = ",result)`

25 OCTOBER 2022

`# OBJECT ORIENTED PROGRAMMINGclass 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 PYTHONclass 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 Deleteimport sqlite3connection = 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 commandinsert_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 Deleteimport sqlite3connection = 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 commandinsert_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 = 2update_query= '''Update Members Set Phone = "222" where memberid = 2'''#cur_obj.execute(update_query)#update the phone number to 222 for MemberID = 2delete_query= '''Delete from Members where memberid = 3'''cur_obj.execute(delete_query)#Reading the content from the tableselect_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 fileimport osprint(os.getcwd())#os.mkdir("C:\\Users\\Hp\\PycharmProjects\\pr1\\Nov_2")#absolute path#relative path#1. Create File Objectfile1 = open("Nov_2\\abc.txt","r") #mode: r-read w-write a-append, r+  w+  a+poem1 = '''Twinkle Twinkle Little StarHow I WOnder What You AreUp Above the World So HighLike 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 sqlite3conn = 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 systemsimport os#os.makedirs("Nov_9") #make directory#os.rmdir("Nov_9")  #remove directoryfile_name = "Nov_1/abcd.txt"file_handle = open(file_name,"a")#file mode - r, r+, w, w+, a, a+str_val = """Twinkle Twinkle Little StarHow I wonderWhat you areUp above the worldso highlike a diamondin the sky"""file_handle.write(str_val)file_handle.close()######################  NUMPY  #################Numpy - matricesimport numpy as npval = range(15)mat1 = np.reshape(val,(5,3))print(mat1)print(mat1.shape)print(mat1[2:,1])#matrix 1val = range(9)mat1 = np.reshape(val,(3,3))print("Matrix 1: \n",mat1)#create matrix out of list of listslist_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*nprint(mat1 - mat2)print(np.subtract(mat1,mat2))print(mat1 / mat2)print(np.divide(mat1,mat2))## Multiplication - This is NOT MATRIX MULTIPLICATIONprint(mat1 * mat2)print(np.multiply(mat1,mat2))####Matrix Multiplicationprint(mat1 @ mat2)print(np.matmul(mat1,mat2))`

#### MATPLOTLIB

`import matplotlib.pyplot as pltimport numpy as npdata = np.random.randn(1000)plt.hist(data, `