L O A D I N G ## Python For Junior – July 2022

`a=5.0b=6c=8d=a+b+cprint(d)print()f="hello"print(type(f))print(type(d))#print(type(a))  #comment# comment# Data types#1. int - integer = numbers without decimal (.) - 5, 6, 99, -90val1 = 5  #intprint(val1)print(type(val1))val2 = 5.0  #floatprint(type(val2))#output:val3 = "asfsdfsdfdsfdf5" #str for stringprint(type(val3))val4 = True #bool - booleanprint(type(val4))#Operations that can be performed on all the values#Type of operation:  ARITHEMATIC Operations: +, -, *, /, //, %, **#input: it can take only numbers (int & float)#output: output will be either int or floatvar1 = 40var2 = 50print(var1+var2)print(var1-var2)print(var1*var2)print(var1/var2)# powerprint(3**4)  # ?print(10/3)  #integer divisionprint(10//3)print(10%3) #modulo - gives us remainder#Assignmentvalue1 = 50#comparison operation:  Is ... ? Output type is always a boolean: True or Falseval1 = 50val2 = 60print("val1 > val2: ", val1 > val2) # is val1 greater than val2?print("val2 > val1: ",val2 > val1)  #is val2 greater thab val1?print("val1 < val2: ", val1 < val2) # is val1 less than val2?print("val2 < val1: ",val2 < val1)  #is val2 less than val1?val1 = 50; val2 = 60val1,val2,val3,val4 = 50,50,60,60print("val1 >= val2: ", val1 >= val2) # is val1 greater than or equal to val2?print("val2 >= val1: ",val2 >= val1)  #is val2 greater than or equal to val1?print("val1 <= val2: ", val1 <= val2) # is val1 less than or equal to val2?print("val2 <= val1: ",val2 <= val1)  #is val2 less than or equal to val1?print(val1 == val2)# is it equal toprint(val1 != val2)# is it not equal to#############################logical operations -> input is boolean and output is also boolean#operators: and  or notprint(5+3-2*3+2)  # / * + -# 2 + 2print(True and False or False) #and or# FALSE OR FALSE = Falseval1, val2 = 30, 40print(val1> val2 or val1 == val2 and val1 <= val2 or val2 > val1 and val1 !=val2)# T#True# 2 softwares:  Python (python.org)# pycharm  (jetbrains.com)print(4+5)print("4+5")print("4+5 =",4+5)var1 = -15  #lets take a variable with name var1 and lets assume its value is -15print(type(var1))  # int = integer - any numeric value without the decimal part (.)var1 = 5.0print(type(var1))  #float - will have decimal partvar1 = "5"var1 = "Hello"var2 = var1print(type(var1)) #str - string - all textFALSE =Falsevar1 = "FALSE" #bool - boolean values   Trueprint(type(var1))# complex - square root (-1)# i = square root of -1# i * i = -1# square root (-25 = -1 * 25): 5i#int()val1 = 5jprint(type(val1))print(5j * 5j)a = 6-2jb =  6                   + 2jprint(a*b) #( (x-y)*(x+y) = x2 - y2  :36 +4 = 40 +0j)val1 = 6val2 = 12print(val1 + val2)print(val1 - val2)print(val1 * val2)print(val1 / val2)  #0.5print(val1 // val2)  #integer division - 0print(4 ** 3)  #power : exponent:  4 ** 3 = 4 cubeprint(13 % 5)### Arithematic operations#binval1 = 8print("Binary format = ",bin(8))print("Octal format = ",oct(8))print("Hexadecimal format = ",hex(8))print("Octal value = ",oct(0b1011))  # 8, 9, 10, 11 => 10,11,12,13 => 0o13print("Decimal value = ",int(0b1011))  # 11quantity = 25price = 21total = quantity * price# The total cost of 25 pens each costing 21 isprint("The total cost of",quantity,"pens each costing",price,"is",total)print("The total cost of {quantity} pens each costing {price} is {total}")print(f"The total cost of {quantity} pens each costing {price} is {total}")total = 1000  #implicitquantity = 30test_val = total+quantity  #implicit conversionprice = total /quantity  #implicit conversionprint(f"The total cost of {quantity} pens each costing {price:0.2f} is {total}")#input()user_value = input("Enter a number: ")print("User input value = ",user_value)print("Data type of user input is ",type(user_value))user_value = int(user_value)  #explicit conversionprint("User input value = ",user_value)print("Data type of user input is ",type(user_value))user_value2 = float(input("Enter another number: "))print(user_value2)#WAP to find area and perimeter of a rectangle by taking length and breadth as input### the area and perimeter of a rectangle of lenght XX and breadth YY is AA and PP respectively# a = l*b  / p = 2 (l+b)#WAP to find area and circumference of a circle by taking radius as input###  the area and circumference of a circle of radius XX  is AA and CC respectively#   pi = 3.04   / a= pi r square   / c = 2 * pi * ra= int(input("a = "))b= int(input("b = "))print(a+b)a= int(input("a = "))b= int(input("b = "))print(a+b)total = 1000  #implicitquantity = 30test_val = total+quantity  #implicit conversionprice = total /quantity  #implicit conversionprint(f"The total cost of {quantity} pens each costing {price:0.1f} is {total}")a=6b=5area = a * bperimeter = 2 * (a + b)print(f"area is {area:0.2f}")print("perimeter is"+ str(perimeter))## 22 JULY 2022# IF - elif elif -ELSEnum = 0if num <0:    print("Its a negative value")elif num >0:    print("Its a positive value")else:    print("Its zero!!!")#repeat set of code# for - when you know how many times to repeat# while - repeat untill a condition becomes falsefor i in range(0,10):  #start, end, increment (default value of increment when not mentioned is 1)    print("How are you?")    print("The value of i =",i)for i in range(4):  #start (default zero when no value given, end, increment (default value of increment when not mentioned is 1)    print("How are you?")    print("The value of i =",i)for i in range(3,31,3):    print("How are you?")    print("The value of i=", i)print("I am done")'''#wap to print:*****''''''* * * * ** * * ** * ** **'''n=5for j in range(n):    for i in range(n-j):        print("*",end= ' ')    print()## We will not have session on Monday# wap to print: * * * * *#generate values from 1 to 20 and check which numbers are divisible by 5#5 is divisible by 5#10 is divisible by 5#15 is divisible by 5#20 is divisible by 5for i in range(1,21):    if i%5 ==0:        print(i,"is divisible by 5")for i in range(1, 21):    print(i)    if i % 5==0:        print("not divisible")    else:        print("divisible")'''#1. WAP to generate multiple of a given number, eg 3:3 * 1 = 33 * 2 = 6...3 * 10 = 30''''''Generate multiplication table from 1 to 101 * 1 = 1   2 * 1 = 2   3 * 1 = 3  ...   10 * 1 = 101 * 2 = 2   2 * 2 = 4   3 * 2 = 6  ...   10 * 2 = 20...1 * 10 = 10   2 * 10 = 20  3 * 10 = 30 .... 10 * 10 = 100'''# 3. Enter 2 values (length & breadth) and check if they are rectangle or square and find area & perimeter# Sum of first n natural numbers:  1 + 2 + 3... +100 = n*(n+1)/2# 4. WAP to find sum of first n natural numbers (given n) using loop and then calculate using formula and confirm# if they give you same result.# 5. generate first n odd numbers and first n even numbers#Forfor i in range(1, 11):    for j in range(1, 11):        print(f"{j:2} * {i:2}={j*i:2}",end="  ")    print()#Whilei=1while True:    print(i)    i=i+1    ch = input("Press y to continue else stop!")    if ch!='y':        breaki=1while True:    if i%5==0:        print(i)    i=i+1    #ch = input("Press y to continue or else stop!")    if i==60:        break#Guessing game - between 1 and 100import randommain_num = random.randint(1,100)count_steps = 0start = 1end = 100while True:    guess = random.randint(start,end)    count_steps += 1  # a = a+ b => a+=b    if guess == main_num:        print(f"Congratulations! You got the correct value {guess} in {count_steps} chances.")        break    elif guess < main_num:        print(f"Sorry! Its higher than {guess}. Guess again")        start = guess+1    else:        print(f"Sorry! Its lower number than {guess}. Guess again")        end = guess - 1`

AUGUST 1  2022: DAY 7

`name = "What's Your Name?"name2 = 'Rahul Dravid'name3 = '''I am doing fineYou are fineWe are fine'''name4 = """Where are you going?Where are you coming from?Why are you doing \\thi\'s?Who you are?"""print(name4)print(type(name4))print(name)# He asked,"What's Your Name?"t1 = 'He asked,\"What\'s Your Name?\"'print(t1)t2 = '''He asked,"What's Your Name?"'''print(t2)t3 = name + name2print(t3)print(name2 * 4)t2 = '''He asked,"What's Your Name?"'''print("Total characters in t2 is ",len(t2))print(t2)  #indexing or slicingprint(t2[2:7])print(t2[-6:])print(t2[:])total_vowel = 0for i in t2:   #aeiou    if i =="a" or i=="A" or i=="e" or i=="E" or i=="I" or i=="i" or i=="o" or i=="O" or i=="u" or i=="U":        #print(i)        total_vowel+=1print("Total vowel in the text is ",total_vowel)total_vowel = 0for i in t2:   #aeiou    if i in "aeiouAEIOU":        #print(i)        total_vowel+=1print("2. Total vowel in the text is ",total_vowel)`

total_c = 0
for i in t2: #aeiou
if i not in ”’aeiouAEIOU ,’;:!@#\$%^&*””’:
#print(i)
total_c+=1
print(“2. Total consonants in the text is “,total_c)

t1 = “Good MOrning”
print(t1.count(‘o’) + t1.count(‘O’))
print(t1.upper().count(‘O’))
print(t1.split()) #when you dont pass any value in split-it splits on space

txt = “Enter,the,comma,separated,content”
words = txt.split(‘,’)
print(words)
new_txt = “”.join(words)
print(new_txt)

txt = “Enter the comma separated content: “
new_txt=“”
for i in txt:
if i.lower() not in “aeiou”:
new_txt+=i
print(new_txt)

txt3 = “HOWARE YOU”
print(txt3.isalpha() and txt3.isupper())

#Assignmets

Assignments

1. Write a Python program to move spaces to the front of a given string.

2. Write a Python program to compute sum of digits of a given string.

Input: ABC369abc810xyz

Output:27

3. Write a Python program to capitalize first and last letters of each word of a given string.

4. Write a Python program to print the index of the character in a string.

Input: Hello

Output:

Current character h position at 0

Current character e position at 1

Current character l position at 2

Current character l position at 3

Current character 0 position at 4

5. Write a Python program to swap comma and dot in a string.

Input: 75.99,25.11

Output: 75,99.25,11

More Programs to Practice

.     Swap commas and dots in a String

Program to convert String to a List

.     Count and display vowels in a string

Python program to check the validity of a Password (Atleast 1 caps, 1 digit and minimum 8 characters)

.     Python program to count number of vowels using sets in given string

6.     Check for URL in a String

7.     Check if a Substring is Present in a Given String

8.     Check if two strings are anagram or not (contains same set of characters)

9.     Map function and Dictionary in Python to sum ASCII values

10.  Map function and Lambda expression in Python to replace characters

11.  SequenceMatcher in Python for Longest Common Substring

12.  Print the initials of a name with last name in full

13.  Find the k most frequent words from data set in Python

14.  Find all close matches of input string from a list

15.  Check if there are K consecutive 1’s in a binary number

16.  Check if both halves of the string have same set of characters in Python

17.  Find the first repeated word in a string in Python

18.  Second most repeated word in a sequence in Python

19.  K’th Non-repeating Character in Python

20.  Reverse words in a given String in Python

21.  Print number with commas as 1000 separators in Python

22.  Remove all duplicates words from a given sentence

23.  Sort words of sentence in ascending order

24.  Reverse each word in a sentence

25.  Python code to print common characters of two Strings in alphabetical order

26.  Python program to count upper and lower case characters without using inbuilt functions

SOLUTIONS

(First Make attempt to solve on your own and only then look for the solutions

 ```inputStr = input("Enter the String: ") noSpacesChars = [ch for ch in inputStr if ch!=' '] print(noSpacesChars) spacesCount = len(inputStr) - len(noSpacesChars) result = ' '*spacesCount result = '"'+result + ''.join(noSpacesChars)+'"' print(result)``` ```inputStr = input("Enter the String: ") sumDigit = 0 for ch in inputStr:     if ch.isdigit() == True:         chr2int = int(ch)         sumDigit = sumDigit + chr2int print("Sum of Digits in the String are: ", sumDigit)``` ```inputStr = input("Enter the String: ") inputStr = inputStr.title()  #Set to Title Case result = "" for word in inputStr.split():     result += word[:-1] + word[-1].upper() + " " print(result[:-1])``` ```inputStr = input("Enter the String: ") for counter, ch in enumerate(inputStr):     print("Current character", ch, "position at", counter)``` ```amount = "75.99,25.11" amountTrans = amount.maketrans('.,', ',.') # maketrans() method returns a translation table # translate amount = amount.translate(amountTrans) print(amount)```

DAY 8: AUGUST  3, 2022

`#LIST## Basic datatypes - str, int, float, bool, complex#Collectionsmylist = [10,20.5,False,"Hello",50,[2,3,4]]print(type(mylist))  #data type of the variableprint(len(mylist))  #counting the members in the listmembers = len(mylist)print(mylist)   #dislaying all the membersprint(mylist)print(mylist[members-1])print(mylist[-1])print(type(mylist[-3]))#go through each member of the listfor i in mylist:    print(i)print([1,2,3]+[2,4,6])print([1,2,3]*3)#WAP to store marks of 5 subjectsmarks = []for i in range(5):    m = int(input("Enter the marks: "))    marks.append(m)print(marks)marks.insert(1,100)print("After Insert: ",marks)l1 = [20,10,30,25,45,40]l1.sort()print(l1)l1.reverse()print("After reverse: ",l1)#Lists are mutablel1 = [1,3,5,7]l1=50print("After edit: ",l1)#strings are immutable - you cant edit (you can overwrite)s1 = "Hello"#s1="h" - this is not possible in string#assignment & copyl1 = [1,3,5,7]l2 = l1  #they both point to same listsl3 = l1.copy() #l3 is a different list created with same values as l1print("==> l1",l1)print("==> l2",l2)print("==> l3",l3)l1.append(77)l2.append(99)l3.append(66)l1.append(88)print("After ==> l1",l1)print("After ==> l2",l2)print("After ==> l3",l3)mainlist = []while True:    print("Select your option: ")    print("1. Display the content\n2. Add member to end of list\n3. Add member to a specific position")    print("4. Remove a member\n5. Remove member from a specific position\n6. Display sorted list")    print("7. Display reverse list \n8. Exit")    ch = int(input("Enter you choice: "))    if ch==1:        print("Current list is:\n",mainlist)    elif ch==2:        value = int(input("Enter the element to be added: "))        mainlist.append(value)    elif ch==3:        value = int(input("Enter the element to be added: "))        pos = int(input("Enter the position where element to be added: "))        mainlist.insert(pos,value)    elif ch==4:        value = int(input("Enter the element to be removed: "))        if value in mainlist:            mainlist.remove(value)        else:            print(f"{value} is not in the list")    elif ch==5:        pos = int(input("Enter the position of element to be removed: "))        if pos > len(mainlist):            print(f"Sorry, {pos} position doesnt exist")        elif pos<=0:            print("Invalid option!")        else:            pos-=1            mainlist.pop(pos)    elif ch==6:        mainlist.sort()        #print("Sorted list is:\n", mainlist)    elif ch==7:        mainlist.reverse()        #print("Reverse list is:\n",mainlist)    elif ch==8:        break    else:        print("Invalid choice! Please select from below list")        continueprint("Thank you for using my program, see you soon!")`

DAY 9: Aug 5 2022

`l1 = [2,4,6,8]  #listt1 = (2,4,6,2,8,2,6)print(t1.count(2))print(t1.index(6))#Tuple is immutable version of Listl1 = tuple(l1)for i in l1:    print(i)t2 = (1,False,3,"hello",[2,4,6])t3 = (1,1)print("ASCII value: ",ord('a'))print("ASCII value: ",ord('0'))if t2 > t3:    print("larger: ",t2)else:    print("larger: ",t3)print(t2)val1,val2,val3,val4,val5 = t2print(val3)# you cant compare string with anyother values#float, int & bool (False 0 True 1)#complexif 'abc' > 'aaC':    print("Smaller")else:    print("Capital")t3 = list(t3)# Dictionaryval1 = {'Name':'Sachin',"Age": 32, "Runs": 20000,4:"Mumbai"}print(val1)d1 = {}name = "Rahul"age = 43runs = 15000d2 ={"Name": name,"Age": age,"Runs": runs}d1.update(d2)print(d1)#WAP to add 5 students marks (3 subjects) in a dictionary, where RollNo is the key and#marks should be saved as a listmarks_all = {}for i in range(3):    rollno = int(input("Enter the Roll No.: "))    list=[]    for i in range(3):        m = int(input("Enter marks: "))        list.append(m)    t_dict = {rollno:list}    marks_all.update(t_dict)print("Marks = ", marks_all)`

DAY 10: 8 AUGUST 2022

`dict1 = {}t_dict = {21:"Sachin"}dict1.update(t_dict)#Add books### bookid, title, author,price, copiesall_books={}t_dict = {102:["Python Programming","AB CD", 25.90, 5]}all_books.update(t_dict)t_dict = {103:["Python Programming by Someone","Someone", 15.90, 3]}all_books.update(t_dict)print(all_books)#add membersprint("Printing items:")for i in all_books.items():    print(i)print("Printing items:")bid = 103for i,j in all_books.items():    if i == 103:        print(i," : ",j,j[-1])print("Printing only keys:")for i in all_books.keys():    print(i)print("Printing only values:")for i in all_books.values():    print(i)### Edit the values for bid 103t_dict={}for i,j in all_books.items():    if i == 103:        j = j-1        t_dict={i:j}all_books.pop(103)all_books.update(t_dict)print(all_books)#SETs1 = {1,2,3,4,5,2,3,4,5}  #set will not print duplicate valuesprint(s1)  #set doesnt have any orders1.pop()  #it will remove any valueprint(s1)s1.clear() #remove all the membersprint(s1)#you can convert set to list, set to tuple,#list to set , tuple to set# tuple to list, list to tuplel1 = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]print(l1.count(5))l1 = list(set(l1))print(type(l1))print(l1)#specific set operations#UNIONs1={1,2,3,4}s2 = {3,4,5,6}print("UNION:",s1 | s2)print("UNION:",s1.union(s2))#INTERSECTIONprint("INTERSECTION:",s1 & s2)print("INTERSECTION:",s1.intersection(s2))#DIFFERENCEprint("DIFFERENCE:",s1 - s2)print("DIFFERENCE:",s1.difference(s2))#SYMMETRIC DIFFERENCEprint("SYMMETRIC DIFFERENCE:",s1 ^ s2)print("SYMMETRIC DIFFERENCE:",s1.symmetric_difference(s2))s1.update(s2)s1.intersection_update(s2)s1.difference_update(s2)s1.symmetric_difference_update(s2)##Functionsprint() #inbuilt functions#definition of a function:## should begin with def keyword, followed by the function##name that you want to give and then ():## in the body of definition, write the logicdef mysum():    a=50    b=60    print("Sum is: ",a+b)mysum()def mysum1():    a=50    b=60    #print("Sum is: ",a+b)    return a+b  #function is sending the value back to the called functionval = mysum1() #called function should catchprint("The answer is: ",val)#third type when we also pass the value to# function definitiondef mysum2(x,y): #a is passed to x and b is passed to y    sum = x+y    return suma=11b=24val = mysum2(a,b)print("Value is: ",val)#code reusability`

DAY 11: August 10 2022

`#How to use functionsdef fun_sum(a,b,c):    print(a)    print(b)    print(c)    sum = a+b+c    #print("Sum = ",sum)    return sumx = 51y = 52z = 59fun_sum(x,z,y) #mapping of variables in function definition is done left to right#number of values that you pass in same as the parameters defined in the function# simple interest = principle * timeline (in years) * rate of interest (%)#Priciple is the amount that you borrow#Timeline is for how many years you borrow# rate of interest is the ammount / hundred that you need to pay because you borrowed# How much simple interest I will pay if I borrow 45000 for 9 months @ of 5% interest# 45000 * 9/12 * 5/100 = ?# Write a function that takes 3 values- p,t,r and returns simple interest#In the main program take the input and pass on to the function and#after you get the simple interest from the function, add it to the amount#and display today amount due.#Function - which has required positional argumentsdef simple_interest(p,t,r):    si = p*t*r/100    return siprinciple = float(input("Enter borrowed money (\$): "))time = float(input("Enter time (in years):"))rate = float(input("Enter rate of interest (%):"))si = simple_interest(principle, time,rate)print("The interest is ",si,"and total payment due is \$",si+principle)print("Total interest paid is: ",si)# Function with default valuesdef simple_interest(p,t,r=5):    si = p*t*r/100    return siprinciple = float(input("Enter borrowed money (\$): "))time = float(input("Enter time (in years):"))rate = float(input("Enter rate of interest (%):"))si = simple_interest(principle, time,rate)print("The interest is ",si,"and total payment due is \$",si+principle)print("Total interest paid is: ",si)si = simple_interest(principle, time)print("The interest is ",si,"and total payment due is \$",si+principle)print("Total interest paid is: ",si)# Function with keyword argumentdef simple_interest(p,t,r=5):    si = p*t*r/100    return siprinciple = float(input("Enter borrowed money (\$): "))t = float(input("Enter time (in years):"))rate = float(input("Enter rate of interest (%):"))si = simple_interest(t=t,p=principle,r=rate)  #example of keywordprint("The interest is ",si,"and total payment due is \$",si+principle)print("Total interest paid is: ",si)si = simple_interest(principle, t)  #positionalprint("The interest is ",si,"and total payment due is \$",si+principle)print("Total interest paid is: ",si)# create a function which will take as parameter: num1, num2 and operator#my_calculator(n1,n2,op)  #op can be: + , - / *   **,  //  %#based on what you pass to the function, it should return the result#call the function from main# demonstrate using same program - positional and required functions,##  default functions and keyword arguments#variable length arguments functionsdef my_func(x,a,b,*y, **z):  #function definition has *parameter (tuple) and **parameter (read as dictionary)    print(x)    print(y)    print(z)    if 'name' in z.keys():        print("name is ",z['name'])    if 'city' in z.keys():        print("Belongs to ",z['city'])my_func(56,12,24,36,48,60,70,75,80,85,90,95,name="Sachin",team="India",type="Batting")print()#wap to calculate area of a square/rectangledef my_area(*data):    if len(data)==1:        return 3.15*data*data    if len(data)==2:        return data * dataarea = my_area()print(area)area = my_area(3)print(area)area = my_area(5,6)print(area)## Single function to calculate 2 areas:def my_area(data1, data2=-1):    if data2==-1:        return 3.15*data1*data1    if data2!=-1:        return data1 * data2`

Day 12  August 12, 2022

######################  MODULE FILE:  test1.py ##############

`#Required positional#Default#Keyword#variable lengthdef add_val(list1, val):    list1.append(val)    return list1def insert_val(list1, val,pos):    '''This function takes a list and appends a value to it'''    list1.insert(pos,val)    return list1if __name__=="__main__":    listn = [2,4,6,8,10]    listn = add_val(listn,12)    print(listn)    listn = insert_val(listn,pos=3,val=18)    print(listn)    help(insert_val)    help(input)`

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

####################  FILE 2 – from where we call #################

`import test1list2 = [1,2,3,4,5]result = test1.add_val(list2,99)print(result)def test_func():    print("HEllo")    #recursive function is to call itself    test_func()#test_func()#Factorial ?# 9! = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1# 9! = 9 * 8!# 8! = 8 * 7!def my_factorial(n):    #...    if n<=1:        return 1    return n * my_factorial(n-1)result = my_factorial(-1)print("Factorial is ",result)#import timeprint("Hello")time.sleep(1)print("hello")import datetimeprint("Time now is ",datetime.datetime.now())print("Time now is ",datetime.datetime.utcnow())print("Date: ", datetime.date.today())#Module: python file# functions or it have classes#Datetime is a module which has following classes:## 1. Datetime## 2. Date## 3. Time## 4. timedeltadate_1 = datetime.date(2022,8,12)print(type(date_1), " : ",date_1)`

Day 13  AUGUST  15, 2022

CLASS & OBJECTS – 1

`class Apple:    #Class level variables    color = "Red"    shape = "Round"    #Object level Function - METHODS    def apple_name(self,name):        self.name = name    def eat(self):        print(f"I am eating the apple {self.name}")apple1 = Apple()apple2 =Apple()  #Creating objectsapple2.apple_name("Fizi Apple")apple1.apple_name("Washington Apple")Apple.color = "Black"print("apple1.name: ",apple1.name)print("apple1.color: ",apple1.color)print("apple2.name: ",apple2.name)print("apple2.color: ",apple2.color)print(Apple.color)class Student:    school_name = "Indigo International School"    def create_new_student(self,name,phoneno):        self.name = name        self.phoneno = phoneno    def get_book(self,title,author):        self.title = title        self.author = author    def print_values(self):        print("Name: ",self.name)        print("School: ",Student.school_name)        print("Phone No: ",self.phoneno)        print("Title: ",self.title)        print("Author: ",self.author)s2 = Student()s1 = Student()s1.create_new_student("Sachin", 1234)s1.get_book("Python","John")s2.create_new_student("Rahul", 3234)s2.get_book("ML","George")s2.print_values()#constructor => initialization or init()# its the best place to assign valuesclass Student:   #something is being designed    school_name = "Indigo International School"    total_students = 0    def __init__(self,name,phoneno): #called automatically when object is created-        self.name = name        self.phoneno = phoneno        self.title = ""        self.author = ""        Student.total_students += 1    def get_book(self,title,author):        self.title = title        self.author = author    def print_values(self):        print("Name: ",self.name)        print("School: ",Student.school_name)        print("Phone No: ",self.phoneno)        print("Title: ",self.title)        print("Author: ",self.author)    @classmethod    def counter(cls):        print("Total students are: ",cls.total_students)s2 = Student("Sachin", 1234)  #object is borns1 = Student("Rahul", 3234)s1.get_book("Python","John")s2.get_book("ML","George")s2.print_values()s1.counter()#Assignment:#create more objects for Apple and Student classes and see the behavior#`

DAY 14 :  AUGUST 17, 2022

`#Class & Objectsclass School:    def __init__(self, name, age):        self.name = name        self.age = age        print(f"School class is initialized by {self.name}")    def display(self):        print(f"My name is {self.name} and I am {self.age} years old!")    def tell(self):        print("Sample method in parent class")class Teacher(School):    def __init__(self):        print("Teacher class is initialized")class Student(School):    def __init__(self,sname,sage):        School.__init__(self,sname,sage)        print("Student class is initialized")    def tell1(self):        print("Sample method in Student")school1 = School("ABC International School", 110)school2 = School("XYZ Private School", 10)student1 = Student("ABC Private School", 18)student1.tell()student1.display()school2.display()########################class Shape:    def area(self):        print("Sorry area is not possible for this shape")    def perimeter(self):        print("Sorry perimeter is not possible for this shape")    def length(self):        print("Sorry length is not possible for this shape")class Point(Shape):    def __init__(self, value):        self.value = value        print("Got the value as ",self.value)class Line(Shape):    def __init__(self, value1, value2):        self.value1 = value1        self.value2 = value2        print("Got the values as ",self.value1, self.value2)class Square(Shape):    def __init__(self, value):        self.value = value        print("Got the side as ",self.value)class Rectangle(Shape):    def __init__(self, l,b):        self.l = l        self.b = b        print("Got the length and breadth as ",self.l, self.b)    def area(self):        self.area = self.l * self.b        print("Area is ",self.area)print("###########################")r1 = Rectangle(5,6)s1 = Square(5)l1 = Line(10,5)p1 = Point(9)p1.area()r1.length()########################### A program to find if a number if Prime or notclass CheckPrime:    #initializaton    def __init__(self,number):        self.num = number        #self.valid = False        print(f"Got {self.num} to check")    def checkvalid(self):        if self.num >=1:            return True        else:            return False    def isPrime(self):        for i in range(2,self.num//2):                if self.num % i==0:                    return False        return True    def generatePrime(self,st=2,en=100):        for i in range(st,en+1):            self.num = i            if self.isPrime():                print(self.num, end=" ")# 11: 2,3,4,5,6,7,8,9if __name__ == "__main__":    num = 331    cp = CheckPrime(num)    if cp.checkvalid():        if cp.isPrime():            print("Number is a Prime")        else:            print("Number is not a Prime")    else:        print("Sorry, number is invalid")    start,end = 10,2000    print(f"Now generating Prime Numbers between {start} and {end}")    cp.generatePrime(start,end)`

DAY  15:  AUGUST  19, 2022

`#Work with filesfileobj = open("abc.txt","r")'''open() takes filename and mode:a - appendr - readw - write   w+'''val1 = """Hello My name is SachinI am a cricketerI live in Mumbai"""val2=["Hello everyone, how are you doing today?\n",      "I am fine and great\n","Hope you are doing good too\n"]#fileobj.writelines(val2)fileobj.close()fileobj = open("abc.txt","r+")#file_content = fileobj.read()print(fileobj.readline())print("========================")fileobj.seek(0)filecont = fileobj.read()n =filecont.lower().count("hello")print(n)#print(type(file_content))###most common database is RDBMS - Relational Database Management System# SQL (Structured Query Language) is the programming language of database#RDBMS - MySql, Oracle, SQL Server,DB2, SQLITE2## to work with SQLITE2 database, we need to import sqlite3import sqlite3con = sqlite3.connect("learnDB.db")connobj = con.cursor()#SQL command to create a tableq1 = '''create table students(ID Integer, Name text, Phone text, EMAIL text)'''#connobj.execute(q1)q2 = '''Insert into students(ID, NAME, PHONE,EMAIL) VALUES(101,'Sachin','123456','sachin@sachin.com')'''q22 = '''Insert into students(ID, NAME, PHONE,EMAIL) VALUES(102,'Rahul','223456','rahul@sachin.com')'''q23 = '''Insert into students(ID, NAME, PHONE,EMAIL) VALUES(103,'Laxman','323456','laxman@sachin.com')'''#connobj.execute(q2)#connobj.execute(q22)#connobj.execute(q23)#insert or update or delete - these commands need to be commitedcon.commit()q3 = '''Select * from students'''connobj.execute(q3)data = connobj.fetchall()for d in data:      print(d)  #list########## Working with operating system  ############disclaimer: different for windows and macimport osprint(os.name)print(os.getcwd())#os.rename('abc.txt','xyz.txt')print(os.listdir())os.system('cls')`

DAY 16 :  AUGUST 24, 2022

#inheritance in class
class City:
def dummy(self):
print(“Dummy method of City class”)
class School:
school_info = {}
def __init__(self,sname,city,website):
self.sname = sname
self.website = website
self.city = city
print(f“School object {self.sname} is created”)
t_dict = {sname:[city,website]}
School.school_info.update(t_dict)
def myschool_info(self):
print(“Displaying all the information of My School:”)
print(“School Name: “,self.sname)
print(”      City : “,self.city)
print(”    Website: “,self.website)
def dummy(self):
print(“This is a dummy method in School class”)
@classmethod
def display_allinfo(cls):
print(“Displaying all the information of Schools:”)
for i,j in cls.school_info.items():
print(i,” : “,j)

class Student(SchoolCity):
def __init__(self,name,rollno,emailid,sname,city,website):
School.__init__(self,sname,city,website)
self.name = name
self.rollno = rollno
self.emailid = emailid
print(f“Student with name {self.name} is created”)

def student_info(self):
print(”    NAME: “,self.name)
print(” ROLL NO: “,self.rollno)
print(“EMAIL ID: “,self.emailid)
def dummy(self):
print(“This is a dummy method in Student class”)
class Teacher(CitySchool):
def __init__(self,name,age,sname,city,website):
School.__init__(self,sname,city,website)
self.name = name
self.age = age
print(f“Teacher with name {self.name} is created”)
def teacher_info(self):
print(“NAME: “,self.name)
print(” AGE: “,self.age)
def dummy123(self):
print(“This is a dummy method in Teacher class”)

sc1 = School(“ABC School”“Vizag”,“www.abcschool.org”)
sc2 = School(“DEF International School”“Delhi”,“www.defschool.org”)
st1 = Student(“Sachin”121,“sachin@sachin.com”,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#sc1.display_allinfo()
#sc2.myschool_info()
#st1.student_info()
t1 = Teacher(“Kapil Dev”49,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#t1.teacher_info()
t1.myschool_info()
t1.dummy()

# Encapsulation: data hiding
## 3 levels of access:
## 1. Public access – methods can be called by subclass and also by the
###    main program- anybody can call anytime
## 2. Private access – nobody can call (neither subclass nor the main program)
####  private will have __before variable/methods name
## 3. Protected access – (only subclass can call but not main program) THIS IS NOT
###  STRICTLY IMPLEMENTED IN PYTHON
####  protected variables/methods will have _ before its name

#inheritance in class
class City:
print(“Dummy method of City class”)
class School:
school_info = {}
def __init__(self,sname,city,website):
self.sname = sname
self.website = website
self.city = city
print(f“School object {self.sname} is created”)
t_dict = {sname:[city,website]}
School.school_info.update(t_dict)
def myschool_info(self):
print(“Displaying all the information of My School:”)
print(“School Name: “,self.sname)
print(”      City : “,self.city)
print(”    Website: “,self.website)
def dummy(self):
print(“This is a dummy method in School class”)
@classmethod
def display_allinfo(cls):
print(“Displaying all the information of Schools:”)
for i,j in cls.school_info.items():
print(i,” : “,j)

class Student(SchoolCity):
def __init__(self,name,rollno,emailid,sname,city,website):
School.__init__(self,sname,city,website)
self.name = name
self.rollno = rollno
self.emailid = emailid
print(f“Student with name {self.name} is created”)

def student_info(self):
print(”    NAME: “,self.name)
print(” ROLL NO: “,self.rollno)
print(“EMAIL ID: “,self.emailid)
def dummy(self):
print(“This is a dummy method in Student class”)
class Teacher(CitySchool):
def __init__(self,name,age,sname,city,website):
School.__init__(self,sname,city,website)
self.name = name
self.age = age
print(f“Teacher with name {self.name} is created”)
def teacher_info(self):
print(“NAME: “,self.name)
print(” AGE: “,self.age)
def dummy123(self):
print(“This is a dummy method in Teacher class”)
#City.__dummy()# private is not callable

sc1 = School(“ABC School”“Vizag”,“www.abcschool.org”)
sc2 = School(“DEF International School”“Delhi”,“www.defschool.org”)
st1 = Student(“Sachin”121,“sachin@sachin.com”,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#sc1.display_allinfo()
#sc2.myschool_info()
#st1.student_info()
t1 = Teacher(“Kapil Dev”49,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#t1.teacher_info()
t1.myschool_info()
t1.dummy123()

## Demonstration of Protected members

#inheritance in class
class City:
print(“Dummy method of City class”)
class School:
school_info = {}
def __init__(self,sname,city,website):
self.sname = sname
self.website = website
self.city = city
print(f“School object {self.sname} is created”)
t_dict = {sname:[city,website]}
School.school_info.update(t_dict)
def myschool_info(self):
print(“Displaying all the information of My School:”)
print(“School Name: “,self.sname)
print(”      City : “,self.city)
print(”    Website: “,self.website)
def dummy(self):
print(“This is a dummy method in School class”)
@classmethod
def display_allinfo(cls):
print(“Displaying all the information of Schools:”)
for i,j in cls.school_info.items():
print(i,” : “,j)

class Student(SchoolCity):
def __init__(self,name,rollno,emailid,sname,city,website):
School.__init__(self,sname,city,website)
self.name = name
self.rollno = rollno
self.emailid = emailid
print(f“Student with name {self.name} is created”)

def student_info(self):
print(”    NAME: “,self.name)
print(” ROLL NO: “,self.rollno)
print(“EMAIL ID: “,self.emailid)
def dummy(self):
print(“This is a dummy method in Student class”)
class Teacher(CitySchool):
def __init__(self,name,age,sname,city,website):
School.__init__(self,sname,city,website)
self.name = name
self.age = age
print(f“Teacher with name {self.name} is created”)
def teacher_info(self):
print(“NAME: “,self.name)
print(” AGE: “,self.age)
def dummy123(self):
print(“This is a dummy method in Teacher class”)
#City.__dummy()# private is not callable

sc1 = School(“ABC School”“Vizag”,“www.abcschool.org”)
sc2 = School(“DEF International School”“Delhi”,“www.defschool.org”)
st1 = Student(“Sachin”121,“sachin@sachin.com”,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#sc1.display_allinfo()
#sc2.myschool_info()
#st1.student_info()
t1 = Teacher(“Kapil Dev”49,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#t1.teacher_info()
t1.myschool_info()
t1.dummy123()
t1._dummy()  ## this is protected meaning – doesnt appear when you call
# but doesnt throw error when you call it

class Shape:
def area(self):
print(“Area of this shape is not possible”)
def perimeter(self):
print(“Perimeter of this shape is not possible”)
def circumference(self):
print(“Circumference of this shape is not possible”)
import math
class Rectangle(Shape):
def __init__(self,l,b):
self.l = l
self.b = b
def area(self):
print(“Area is “,self.l * self.b)
def perimeter(self):
print(“Perimeter is “,2 * (self.l + self.b))
class Circle(Shape):
def __init__(self,r):
self.r = r
def area(self):
print(“Area is “,math.pi *self.r ** 2)
def circumference(self):
print(“Perimeter is “,2 * self.r *math.pi)

r1 = Rectangle(6,9)
r1.circumference()
r1.area()
c1 = Circle(5)
c1.perimeter()
c1.area()

DAY  17:  SEPTEMBER  5, 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  18:  SEPTEMBER 29, 2022

DAY  19:  SEPTEMBER  , 2022

DAY  20:  SEPTEMBER 2, 2022