FREE PYTHON TRAINING BY BRC WARRIORS - AUG TO SEP 2022
DAY 0 – ORIENTATION (AUGUST 12, 2022)
Download The Python Installer From Here (We Will Install Python 3.9.9):
https://www.python.org/downloads/release/python-399/
Download & Install IDE for Python Programming
Follow The Steps From Here: https://learn.swapnil.pw/python/pythonides/
DAY 1: PYTHON BASICS (AUGUST 15, 2022)
print(3+4+5) #Python will evaluate
print('3+4+5') #Python will print as it is
print('Hello how are you?')
#this is a sample comment
#comments are put in hash
print("Good evening")
#there are two types of translators in programming
#language - COMPILER & INTERPRETER
#Constant v Variable
x = 5
x = 7
x = 9.5
# x is a variable which can change its value
# x is the variable name
# you can add number to variable name
x1 = 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 name
first_num = 50
print(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.99999999
val1 = 5
val2 = 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 j
val3 = 5j
print(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 & False
val5 = True
print(type(val5))
#Basic data types: int, float, complex, bool,str
#WAP to calculate area and perimeter of a rectangle
length = 10
breadth = 12
area = length * breadth
print("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
DAY 2: PYTHON OPERATORS(AUGUST 16, 2022)
#Program done on 16th
pi = 3.14
r = 5
area = pi*r**2 # ** for power
circumference = 2 * pi * r
print("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 newline
print("Hello",end=" ") # end will make \n visible
print("Good Evening")
val1 = 59
val2 = 25
print(val1 + val2) #addition
print(val1 - val2) #subtraction
print(val1 * val2) #multiplication
print(val1 / val2) #division
print(val1 ** val2) # power
print(val1 // val2) # integer division
print(val1 % val2) #modulo - remainder
## These were arithematic operations
#Comparison Operators
## input are integer values and output is a boolean value (T/F)
val1 = 12
val2 = 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/F
print(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 True
val1 = 15
val2 = 19
print(val1 !=val2 and val1 > val2) #True and False = FALSE
# OR - even if one nalue is True entire result will be True
print(val1 !=val2 or val1 > val2) # TRUE or FALSE - True
print(not True)
print(not False)
val1 = 30
print(val1 % 3)
#INPUT
a= input("Enter a value: ") #interactive input - you dont have to give fixed value
a = int(a) #int() str() float() complex() bool()
print("Input value is ",a)
print("Data type of input value is ", type(a))
DAY 3: PYTHON OPERATORS(AUGUST 17, 2022)
#
avg = 40
#you have passed
if 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 zero
if 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 negative
num = -10
if 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- F
marks1 = 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 + marks5
avg = total /5
print(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 medal
if 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 75
a,b,c = 85, 75,95
l1,l2,l3 = a,a,a
if 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,b
else: #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,a
print(f"{l1} <= {l2} <={l3}")
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 order
num1,num2,num3 = 80,10,40
b1,b2,b3 = num1,num1,num1
#logic to find highest, second highest and lowest values
if 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, num2
else: #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 value
print(f"{b1} >= {b2} >= {b3}")
############ LOOPS #######
## FOR Loop - how many times you need to execute
print("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,7
print("3rd For loop: ")
for i in range(3,8,2):
print("Hello: ",i) #generated values: 3, 5, 7
print("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,2
print("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
Day 5: 19 AUGUST 2022
#for loop when we know how many times to run the loop
# while is based on condition
i = 1
while i <=5:
print(i)
i+=1
user = "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 = 5000
end = 10000
while 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 next
print()
"""
*
* *
* *
* *
* *
* * * * * *
"""
n = 8
for 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, current
else:
print("Invalid input")
DAY 6 : 22 AUGUST 2022
https://play.google.com/store/apps/details?id=com.hachiweb.story_mantra&hl=en_IN&gl=US
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
https://play.google.com/store/apps/details?id=com.hachiweb.story_mantra&hl=en_IN&gl=US
DAY 7: AUGUST 23, 2022
#String
## its a text that Python uses
greet1 = '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 fine
I am going home
Where 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 ZERO
print(greet1[0]) #position 1 = Index 0
print(greet1[0]+greet1[4]+greet1[7])
#counting or indexing starts from zero from left to right
# len(greet1) = 9
print(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 character
print(greet1[-1] + greet1[-3]+greet1[-5])
#indexing sequence of characters
greet1 = "Hello Bye"
print(greet1[0:3]) #first 3 characters
print(greet1[2:5]) #llo
print(greet1[-7:-4]) #llo using -ve indexing
size = len(greet1)
print(greet1[-size:-size+4]) #first 3 characters
print(greet1[:-size+4]) #if left side is blanks, then its starting from 0
print(greet1[6:9]) #last 3 characters using +ve indexing
print(greet1[-3:]) #last 3 characters using -ve indexing
print(greet1[:]) #print from first to last
# Inbuilt Methods in String
#functions part of a class is called methods
#here class name is String
greet1 = "Hellobe Hello7Hello*y"
print(greet1.isalpha()) #True/False
print(greet1.isalnum())
print(greet1.isupper()) #check if its upper case
print(greet1.islower()) #check if its lower case
print(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 value
str1 = "H"+str1[1:] #this is fine because we are creating new string variable
print(str1)
DAY 8: 24 AUGUST 2022 – String Methods – II and List – I
DAY 9 – 25 AUGUST 2022: LIST – 2 and TUPLE INTRO
Click here to watch data 9 video
DAY 10: AUGUST 26, 2022
Day 11: August 27, 2022
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 done
print("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 value
def 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 sum
print(addition_type2()) #print directly
result = 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 output
def 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 values
print(addition_type3(56,21)) #print directly
a = 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 directly
a = 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 functions
def input_val():
n1, n2 = 40, 30
return n1,n2
def calculation(n1,n2):
add = n1 + n2
sub = n1 - n2
mul = n1 * n2
div = n1 / n2
return add, sub,mul,div
def 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 variable
x = 50 #global variable
def 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 global
display_info2() #when there is no local, global is called
display_info3()
#WAP to input value and check if the number is odd or even
def 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 False
print("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 number
def generate_fibonacci(n1, n2):
return n1 + n2
n1 = 0
n2 = 1
print("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 function
help(help)
help(input)
help(print)
Day 13: August 30, 2022
#Example of Function that takes REQUIRED POSITIONAL arguments
def 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 provided
def 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 right
def 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 created
def 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 numbers
start_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 itself
def 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
August 31, 2022: HOLIDAY
Day 14: September 1, 2022
#1 Sep 2022
#Decorators and some inbuilt functions
def display_details(name,about):
print("Name: ",name)
print("About: ",about)
#example 2
def 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_fun2
if __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 datetime
print("Current time: ", datetime.datetime.now()) #current system time
print("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 random
print(random.randint(10,20))
print(random.random())
var = "hello"
DAY 15: September 2, 2022
# CLASS & OBJECTS
class 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)
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) class
class 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()
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 not
class 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.isPrimeVar
if __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=", ")
DAY 18: September 6, 2022
#SQLITE 3:
import sqlite3 as sq
con = 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 => SELECT
select1 = "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()
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 sq
from datetime import date #datatime has datetime, date and time
con = 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 query
while 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':
break
select1 = "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;
DAY 20: September 8, 2022
import os
print(os.name)
#current working directory
print(os.getcwd())
print(os.listdir())
filefound = False
for 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 datetime
content = Path("C:/Users/Hp/PycharmProjects")
#iterate through given directory
for 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 number
print(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 line
print(file_obj.readline(7000))
#reading option 3:readlines() - you can read any number of lines
print(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 file
file_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()
DAY 21: September 9, 2022
###########################
###### WORKING WITH JSON #
############################
#JSON files - how to work with them
#JavaScript Object Notation
data = '''
{
"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 / dumps
import json
data_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 csv
file_handle = open("D:/dataset/csvdata.csv")
csv_obj = csv.reader(file_handle,delimiter = '|')
row_count = 0
header = []
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()
DAY 22: September 10, 2022
import threading
import time
def 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 lock
import threading
import time
#global variable
x=0
def increment():
global x
x+=1
def 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 values
a=10
b=2
c=a/b #ZeroDivisionError
#num1 = int(input("Enter a number: ")) #ValueError
file_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 try
try:
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 try
try:
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
div = num1 / num2
except 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")
DAY 24: September 13 2022
### NUMPY
## Matrix like structure
import numpy as np
data = range(16)
#range() takes 3 parameters: start val =0, end = 16(upto/excluding), increment =1
mat1 = 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 column
print(mat5[1,1]) #left of , is for rows and right is for columns
#first row
print(mat5[0,:]) #: start from 0 and go upto end
print(mat5[0])
#second and third row for first and second column
print(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) #addition
print(np.add(mat5,mat6))
print("#perform subtraction:")
print(mat5 - mat6) #addition
print(np.subtract(mat5,mat6))
print("#perform multiplication:")
print(mat5 * mat6) #addition
print(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 steps
print(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 flat
for e in mat6.flat:
print(e)
import matplotlib.pyplot as plt
x = np.arange(0, 3*np.pi,0.3)
y = np.sin(x)
plt.plot(x,y)
plt.show()
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 = -12
import numpy as np
# A = Coefficient matrix
A = [[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 = Ouput
O = [[-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 calculated
det_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 pd
player_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/swapnilsaurav
data_set = pd.read_csv("https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/Mall_Customers.csv")
print(data_set)
print(data_set.head()) #first 5 rows
print("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 - iloc
print("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)"]])
DAY 27: September 16 2022
#Plotting a Histogram Graph
import matplotlib.pyplot as plt
import numpy as np
data1 = 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 Matplotlib
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(50,10,100000)
plt.hist(data)
plt.savefig("hist1.png")
plt.show()
#Boxplot using Matplotlib
import matplotlib.pyplot as plt
import numpy as np
data = 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 Matplotlib
import matplotlib.pyplot as plt
import numpy as np
data = 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 chart
import matplotlib.pyplot as plt
import numpy as np
fruits = ['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 matplotlib
import matplotlib.pyplot as plt
import numpy as np
jan = [112,98,67,45]
feb = [82,88,47,65]
plt.scatter(x=jan,y=feb)
plt.show()
#Heatmap using matplotlib
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random((30,30))
#print(data)
plt.imshow(data, cmap='hot')
plt.show()
DAY 28: September 17 2022
Problem 1: Area of a Circle
from math import pi |
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 : “) |
Program 3: Accepts an integer (n) and computes the value of n+nn+nnn.
a = int(input(“Input an integer : “)) |
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): |
Program: Create a histogram from a given list of integers
def histogram( items ): histogram([2, 3, 6, 5]) |
Program: Concatenate all elements in a list into a string
def concatenate_list_data(list): 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): if x % y == 0: for k in range(int(y / 2), 0, –1): print(gcd(12, 17)) |
Program: Future value of a specified principal amount, rate of interest, and a number of years
amt = 10000 future_value = amt*((1+(0.01*int)) ** years) |
Program: Program to locate Python site-packages.
import site; |
Program: Find out the number of CPUs using
import multiprocessing |
Program: Parse a string to Float or Integer
n = “246.2458” |
Program: List all files in a directory in Python
import glob |
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): return str[0:2] + str[-2:] print(string_both_ends(‘Thunder’)) |
Program: Add ‘ing’ at the end of a given string. If the given string already ends with ‘ing’ then add ‘ly’ instead
def add_string(str1): if length > 2: return str1 print(add_string(‘ab’)) |
Program: Strip a set of characters from a string
def strip_chars(str, chars): print(“\nOriginal String: “) |
Program: Format a number with a percentage
x = 0.25 |
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(“,”)] |
Program: Function to create the HTML string with tags around the word(s)
def add_tags(tag, word): |
Program: Sort a string lexicographically
def lexicographi_sort(s): print(lexicographi_sort(‘This is a long sentence’)) |
Program: Reverse words in a string
def reverse_string_words(text): |
Program: Program to get the largest number from a list
def max_num_in_list( list ): |
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): 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’] print(color) |
Program: Difference between the two lists
list1 = [1, 2, 3, 4] |
Program: Sieve of Eratosthenes method, for computing prime number
def prime_eratosthenes(n): 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} |
Program: Merge two Python dictionaries
d1 = {‘a’: 100, ‘b’: 200} |
Program: Sum all the items in a dictionary
my_dict = {‘data1’:100,‘data2’:-54,‘data3’:247} |
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])) print(‘Maximum Value: ‘, my_dict[key_max]) |
Program: Reverse a tuple
#create a tuple |
Program: Find maximum and the minimum value in a set
#Create a set |
Program: Construct a specified pattern, using a nested for loop
n = 5; for i in range(n, 0, –1): |
* * * * * * * * * * * * * * * * * * * * * * * * * |
Program: Prints each item and its corresponding type from a list
datalist = [1452, 11.23, 1+2j, True, ‘w3resource’, (0, –1), [5, 12], |
Program: Fibonacci series between 0 to 50
x, y = 0, 1 while y < 50: |
Program: Calculate the number of digits and letters in a string
s = raw_input(“Input a string: “) |
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: “) if x: |
Program: Program to print alphabet pattern ‘A’.
result_str=“”; |
*** * * * * ***** * * * * * * |
Program: A Math Quiz Program
import random correct= False correct= False correct= False print(“Thanks for playing!”) |
Program: Multiply all the numbers in a list
def multiply(numbers): |
Program: Calculate the factorial of a number
def 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): |
Program: Program for binary search
def binary_search(item_list, item): print(binary_search([1, 2, 3, 5, 8], 6)) |
Program: Bubble sort
def bubbleSort(nlist): nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70] |
Program: Selection sort
def selectionSort(nlist): temp = nlist[fillslot] nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70] |
Program: Shell sort
def shellSort(alist): print(“After increments of size”, sublistcount, “The list is”, nlist) sublistcount = sublistcount // 2 def gap_InsertionSort(nlist, start, gap): current_value = nlist[i] while position >= gap and nlist[position – gap] > current_value: nlist[position] = current_value nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70] |
Program: Quick sort
def quickSort(data_list): def quickSortHlp(data_list, first, last): quickSortHlp(data_list, first, splitpoint – 1) def partition(data_list, first, last): leftmark = first + 1 done = False while leftmark <= rightmark and data_list[leftmark] <= pivotvalue: while data_list[rightmark] >= pivotvalue and rightmark >= leftmark: if rightmark < leftmark: temp = data_list[first] return rightmark data_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] |
Program: Counting sort algorithm
def counting_sort(array1, max_val): for a in array1: print(counting_sort([1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7)) |
Program: Program to calculate the sum of a list of numbers using Recursion.
def list_sum(num_List): 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): |
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): |
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 find_index(*x): print(” index of a | a | b | sum of squares | index “) |
Program: Program to calculate the sum of the positive integers of n+(n-2)+(n-4)… (until n-x =< 0)
def sum_series(n): print(sum_series(6)) |
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): print(harmonic_sum(7.0)) |
Program: Program to find the greatest common divisor (gcd) of two integers.
def Recurgcd(a, b): if low == 0: print(Recurgcd(28, 14) |
Program: Python script to display the various Date Time formats
import time |
Program: Find the date of the first Monday of a given week
import time |
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 subsetsRecur(self, current, sset): 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 get_String(self): def print_String(self): str1 = IOString() |
Program: Get the class name of an instance
import itertools |
Program: A class constructed by a radius and two methods which will compute the area and the perimeter of a circle
class Circle(): def area(self): def perimeter(self): NewCircle = Circle(8) |
Program: Count the frequency of words in a file
from collections import Counter 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): file_read(‘test.txt’) |
Program: Get the file size of a plain file
def file_size(fname): print(“File size in bytes of a plain file: “, file_size(“test.txt”)) |
Program: Match a string that contains only upper and lowercase letters, numbers, and underscores
import re def text_match(text): print(text_match(“The quick brown fox jumps over the lazy dog.”))
|
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”) |
Program: Abbreviate ‘Road’ as ‘Rd.’ in a given string
import re |
Program: Convert camel case string to snake case string
def camel_to_snake(text): print(camel_to_snake(‘PythonExercises’)) |
Program: Split a string with multiple delimiters
import re |
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 Graph
import matplotlib.pyplot as plt
import numpy as np
data1 = 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 plt
import pandas as pd
dataset = 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 pd
import matplotlib.pyplot as plt
data_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].values
print(X)
#Target:
y = data_df.iloc[:,1].values
#pip install scikit-learn package
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
#training the model
regressor.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)