a=5.0
b=6
c=8
d=a+b+c
print(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, -90
val1 = 5 #int
print(val1)
print(type(val1))
val2 = 5.0 #float
print(type(val2))
#output:
val3 = "asfsdfsdfdsfdf5" #str for string
print(type(val3))
val4 = True #bool - boolean
print(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 float
var1 = 40
var2 = 50
print(var1+var2)
print(var1-var2)
print(var1*var2)
print(var1/var2)
# power
print(3**4) # ?
print(10/3) #integer division
print(10//3)
print(10%3) #modulo - gives us remainder
#Assignment
value1 = 50
#comparison operation: Is ... ? Output type is always a boolean: True or False
val1 = 50
val2 = 60
print("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 = 60
val1,val2,val3,val4 = 50,50,60,60
print("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 to
print(val1 != val2)# is it not equal to
############################
#logical operations -> input is boolean and output is also boolean
#operators: and or not
print(5+3-2*3+2) # / * + -
# 2 + 2
print(True and False or False) #and or
# FALSE OR FALSE = False
val1, val2 = 30, 40
print(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 -15
print(type(var1)) # int = integer - any numeric value without the decimal part (.)
var1 = 5.0
print(type(var1)) #float - will have decimal part
var1 = "5"
var1 = "Hello"
var2 = var1
print(type(var1)) #str - string - all text
FALSE =False
var1 = "FALSE" #bool - boolean values True
print(type(var1))
# complex - square root (-1)
# i = square root of -1
# i * i = -1
# square root (-25 = -1 * 25): 5i
#int()
val1 = 5j
print(type(val1))
print(5j * 5j)
a = 6-2j
b = 6 + 2j
print(a*b) #( (x-y)*(x+y) = x2 - y2 :36 +4 = 40 +0j)
val1 = 6
val2 = 12
print(val1 + val2)
print(val1 - val2)
print(val1 * val2)
print(val1 / val2) #0.5
print(val1 // val2) #integer division - 0
print(4 ** 3) #power : exponent: 4 ** 3 = 4 cube
print(13 % 5)
### Arithematic operations
#bin
val1 = 8
print("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 => 0o13
print("Decimal value = ",int(0b1011)) # 11
quantity = 25
price = 21
total = quantity * price
# The total cost of 25 pens each costing 21 is
print("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 #implicit
quantity = 30
test_val = total+quantity #implicit conversion
price = total /quantity #implicit conversion
print(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 conversion
print("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 * r
a= int(input("a = "))
b= int(input("b = "))
print(a+b)
a= int(input("a = "))
b= int(input("b = "))
print(a+b)
total = 1000 #implicit
quantity = 30
test_val = total+quantity #implicit conversion
price = total /quantity #implicit conversion
print(f"The total cost of {quantity} pens each costing {price:0.1f} is {total}")
a=6
b=5
area = a * b
perimeter = 2 * (a + b)
print(f"area is {area:0.2f}")
print("perimeter is"+ str(perimeter))
## 22 JULY 2022
# IF - elif elif -ELSE
num = 0
if 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 false
for 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=5
for 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 5
for 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 = 3
3 * 2 = 6
...
3 * 10 = 30
'''
'''
Generate multiplication table from 1 to 10
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3 ... 10 * 1 = 10
1 * 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
#For
for i in range(1, 11):
for j in range(1, 11):
print(f"{j:2} * {i:2}={j*i:2}",end=" ")
print()
#While
i=1
while True:
print(i)
i=i+1
ch = input("Press y to continue else stop!")
if ch!='y':
break
i=1
while 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 100
import random
main_num = random.randint(1,100)
count_steps = 0
start = 1
end = 100
while 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 fine
You are fine
We 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 + name2
print(t3)
print(name2 * 4)
t2 = '''He asked,"What's Your Name?"'''
print("Total characters in t2 is ",len(t2))
print(t2[4]) #indexing or slicing
print(t2[2:7])
print(t2[-6:])
print(t2[:])
total_vowel = 0
for 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+=1
print("Total vowel in the text is ",total_vowel)
total_vowel = 0
for i in t2: #aeiou
if i in "aeiouAEIOU":
#print(i)
total_vowel+=1
print("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.
Input: Hello from Hyderabad
Output: HellofromHyderabad
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.
Input: hello from hyderabad
Output: HellO FroM HyderabaD
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: ")
|
inputStr = input("Enter the String: ")
|
inputStr = input("Enter the String: ")
|
inputStr = input("Enter the String: ")
|
amount = "75.99,25.11"
|
DAY 8: AUGUST 3, 2022
#LIST
## Basic datatypes - str, int, float, bool, complex
#Collections
mylist = [10,20.5,False,"Hello",50,[2,3,4]]
print(type(mylist)) #data type of the variable
print(len(mylist)) #counting the members in the list
members = len(mylist)
print(mylist) #dislaying all the members
print(mylist[0])
print(mylist[members-1])
print(mylist[-1])
print(type(mylist[-3]))
#go through each member of the list
for i in mylist:
print(i)
print([1,2,3]+[2,4,6])
print([1,2,3]*3)
#WAP to store marks of 5 subjects
marks = []
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 mutable
l1 = [1,3,5,7]
l1[2]=50
print("After edit: ",l1)
#strings are immutable - you cant edit (you can overwrite)
s1 = "Hello"
#s1[0]="h" - this is not possible in string
#assignment & copy
l1 = [1,3,5,7]
l2 = l1 #they both point to same lists
l3 = l1.copy() #l3 is a different list created with same values as l1
print("==> 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")
continue
print("Thank you for using my program, see you soon!")
DAY 9: Aug 5 2022
l1 = [2,4,6,8] #list
t1 = (2,4,6,2,8,2,6)
print(t1.count(2))
print(t1.index(6))
#Tuple is immutable version of List
l1 = 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 = t2
print(val3)
# you cant compare string with anyother values
#float, int & bool (False 0 True 1)
#complex
if 'abc' > 'aaC':
print("Smaller")
else:
print("Capital")
t3 = list(t3)
# Dictionary
val1 = {'Name':'Sachin',"Age": 32, "Runs": 20000,4:"Mumbai"}
print(val1[4])
d1 = {}
name = "Rahul"
age = 43
runs = 15000
d2 ={"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 list
marks_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, copies
all_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 members
print("Printing items:")
for i in all_books.items():
print(i)
print("Printing items:")
bid = 103
for i,j in all_books.items():
if i == 103:
print(i," : ",j[0],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 103
t_dict={}
for i,j in all_books.items():
if i == 103:
j[3] = j[3]-1
t_dict={i:j}
all_books.pop(103)
all_books.update(t_dict)
print(all_books)
#SET
s1 = {1,2,3,4,5,2,3,4,5} #set will not print duplicate values
print(s1) #set doesnt have any order
s1.pop() #it will remove any value
print(s1)
s1.clear() #remove all the members
print(s1)
#you can convert set to list, set to tuple,
#list to set , tuple to set
# tuple to list, list to tuple
l1 = [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
#UNION
s1={1,2,3,4}
s2 = {3,4,5,6}
print("UNION:",s1 | s2)
print("UNION:",s1.union(s2))
#INTERSECTION
print("INTERSECTION:",s1 & s2)
print("INTERSECTION:",s1.intersection(s2))
#DIFFERENCE
print("DIFFERENCE:",s1 - s2)
print("DIFFERENCE:",s1.difference(s2))
#SYMMETRIC DIFFERENCE
print("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)
##Functions
print() #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 logic
def 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 function
val = mysum1() #called function should catch
print("The answer is: ",val)
#third type when we also pass the value to
# function definition
def mysum2(x,y): #a is passed to x and b is passed to y
sum = x+y
return sum
a=11
b=24
val = mysum2(a,b)
print("Value is: ",val)
#code reusability
DAY 11: August 10 2022
#How to use functions
def fun_sum(a,b,c):
print(a)
print(b)
print(c)
sum = a+b+c
#print("Sum = ",sum)
return sum
x = 51
y = 52
z = 59
fun_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 arguments
def simple_interest(p,t,r):
si = p*t*r/100
return si
principle = 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 values
def simple_interest(p,t,r=5):
si = p*t*r/100
return si
principle = 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 argument
def simple_interest(p,t,r=5):
si = p*t*r/100
return si
principle = 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 keyword
print("The interest is ",si,"and total payment due is $",si+principle)
print("Total interest paid is: ",si)
si = simple_interest(principle, t) #positional
print("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 functions
def 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/rectangle
def my_area(*data):
if len(data)==1:
return 3.15*data[0]*data[0]
if len(data)==2:
return data[0] * data[1]
area = 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 length
def add_val(list1, val):
list1.append(val)
return list1
def insert_val(list1, val,pos):
'''This function takes a list and appends a value to it'''
list1.insert(pos,val)
return list1
if __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 test1
list2 = [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 time
print("Hello")
time.sleep(1)
print("hello")
import datetime
print("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. timedelta
date_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 objects
apple2.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 values
class 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 born
s1 = 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 & Objects
class 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 not
class 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,9
if __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 files
fileobj = open("abc.txt","r")
'''
open() takes filename and mode:
a - append
r - read
w - write w+
'''
val1 = """Hello My name is Sachin
I am a cricketer
I 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 sqlite3
import sqlite3
con = sqlite3.connect("learnDB.db")
connobj = con.cursor()
#SQL command to create a table
q1 = '''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 commited
con.commit()
q3 = '''Select * from students'''
connobj.execute(q3)
data = connobj.fetchall()
for d in data:
print(d[1]) #list
########## Working with operating system ###########
#disclaimer: different for windows and mac
import os
print(os.name)
print(os.getcwd())
#os.rename('abc.txt','xyz.txt')
print(os.listdir())
os.system('cls')
DAY 16 : AUGUST 24, 2022
DAY 17: SEPTEMBER 5, 2022
import turtle
#setting up screen
screen = turtle.Screen()
screen.bgcolor("light green")
screen.title("Turtle Program: September 2, 2022")
#create my pen
pen =turtle.Turtle()
for i in range(5,21,3): # 0 - start (inclusive), 4 is the end (exclusive), increment
# range: 5, 8, 11,14
pen.forward(100) #moving -drawing
pen.right(60) #degree
#pen.left(90)
pen.hideturtle() #make turtle invisible
pen.penup()
pen.goto(100,100)
pen.pendown()
for i in range(5,20,3): # 0 - start (inclusive), 4 is the end (exclusive), increment
# range: 5, 8, 11,14
pen.forward(180) #moving -drawing
pen.right(144) # degree
pen.hideturtle() #make turtle invisible
pen.left(90)
pen.penup()
pen.goto(250,250)
pen.pendown()
#done
col = ["red","blue","orange","yellow","purple","green","indigo"]
for i in range(1,3,1):
pen.circle(5*i)
pen.circle(-5*i)
pen.pencolor(col[i%7])
pen.penup()
pen.goto(-300,0)
pen.pendown()
import random
for i in range(10):
val = random.randint(50,200)
pen.forward(val) # moving -drawing
angle = random.randint(20,180)
pen.right(angle)
ts = pen.getscreen()
ts.getcanvas().postscript(file="mydrawing.eps")
turtle.done()
DAY 18: SEPTEMBER 29, 2022
DAY 19: SEPTEMBER , 2022
DAY 20: SEPTEMBER 2, 2022