Free Python Training by BRC Warriors (Aug-Sep 2022)

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/

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

 

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


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

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

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

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

# String
# isupper, islower,istitle

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

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

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

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

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

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


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

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

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

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

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

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

st1 = [65789054699087697576]
st2 = [65789094699087697576]
st3 = [65789054695087697576]
st4 = [65789054699287697576]
highest_marks = []

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

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

 

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


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

list1[1] = 100
print(list1)

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

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

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

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

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

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

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

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

Click here to watch data 9 video

DAY 10: AUGUST 26, 2022

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# union, intersection, subset, difference, superset

 

Day 11: August 27, 2022

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

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

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

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

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

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

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

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

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


myaddition()

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

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

 

Basic Python Exercises

 

Problem 1: Area of a Circle

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

 

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

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

 

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

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

 

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

print(abs.__doc__)

 

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

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

 

Program: Create a histogram from a given list of integers

def histogram( items ):
   
for n in items:
        output =

       
times = n
       
while( times > 0 ):
          output +=
‘*’
         
times = times – 1
       
print(output)

histogram([2, 3, 6, 5])

 

Program: Concatenate all elements in a list into a string

def concatenate_list_data(list):
    result=

   
for element in list:
        result +=
str(element)
   
return result

print(concatenate_list_data([1, 5, 12, 2]))

 

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

def gcd(x, y):
    gcd =
1

    if x % y == 0:
       
return y

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

print(gcd(12, 17))
print(gcd(12, 66))

 

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

amt = 10000
int = 3.5
years = 7

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

 

Program: Program to locate Python site-packages.

import site;
print(site.getsitepackages())

 

 

Program: Find out the number of CPUs using

import multiprocessing
print(multiprocessing.cpu_count())

 

Program: Parse a string to Float or Integer

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

 

Program: List all files in a directory in Python

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

 

 

Data Types Programs

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

def string_both_ends(str):
   
if len(str) < 2:
       
return

    return str[0:2] + str[-2:]

print(string_both_ends(‘Thunder’))
print(string_both_ends(‘Bird’))
print(string_both_ends(‘A’))

 

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):
    length =
len(str1)

    if length > 2:
       
if str1[-3:] == ‘ing’:
            str1 +=
‘ly’
       
else:
            str1 +=
‘ing’

    return str1

print(add_string(‘ab’))
print(add_string(‘abc’))
print(add_string(‘string’)) 

 

Program: Strip a set of characters from a string

def strip_chars(str, chars):
   
return “”.join(c for c in str if c not in chars)

print(\nOriginal String: “)
print(“The quick brown fox jumps over the lazy dog.”)
print(“After stripping a,e,i,o,u”)
print(strip_chars(“The quick brown fox jumps over the lazy dog.”, “aeiou”))
print() 

 

Program: Format a number with a percentage

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

 

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

items = input(“Input comma separated sequence of words: “)

words = [word for word in items.split(“,”)]
print(“,”.join(sorted(list(set(words)))))

 

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

def add_tags(tag, word):
   
return “<%s>%s</%s>” % (tag, word, tag)
print(add_tags(‘i’, ‘Python’))
print(add_tags(‘b’, ‘Python Tutorial’))

 

Program: Sort a string lexicographically

def lexicographi_sort(s):
   
return sorted(sorted(s), key=str.upper)

print(lexicographi_sort(‘This is a long sentence’))
print(lexicographi_sort(‘ThisIsASingleWord’))

 

Program: Reverse words in a string

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

 

Program: Program to get the largest number from a list

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

 

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

def last(n): return n[-1]

def sort_list_last(tuples):
   
return sorted(tuples, key=last)

print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))

 

Program: Print a list after removing specified elements

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

print(color)

 

Program: Difference between the two lists

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

 

Program: Sieve of Eratosthenes method, for computing prime number

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

print(prime_eratosthenes(100))

 

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

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

 

Program: Merge two Python dictionaries

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

 

Program: Sum all the items in a dictionary

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

 

Program: Get the maximum and minimum value in a dictionary

my_dict = {‘x’: 500, ‘y’: 5874, ‘z’: 560}

key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min =
min(my_dict.keys(), key=(lambda k: my_dict[k]))

print(‘Maximum Value: ‘, my_dict[key_max])
print(‘Minimum Value: ‘, my_dict[key_min])

 

Program: Reverse a tuple

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

 

Program: Find maximum and the minimum value in a set

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

 

Conditional statements and loops Programs

 

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

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

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

        *  

      *  *  

    *  *  *  

  *  *  *  *  

*  *  *  *  *  

  *  *  *  *  

    *  *  *  

      *  *  

        *

 

 

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

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

 

Program: Fibonacci series between 0 to 50

x, y = 0, 1

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

 

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

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

 

Program: Check the validity of a password

Validation:

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

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

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

·        Minimum length 6 characters.

·        Maximum length 16 characters.

 

import re

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

if x:
   
print(“Not a Valid Password”)

 

Program: Program to print alphabet pattern ‘A’.

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

  *** 

 *   *

 *   *

 *****

 *   *

 *   *

 *   *

 

Program: A Math Quiz Program

import random
import math
print “Welcome to Math Quiz World”
num1= random.randint(1, 10)
num2= random.randint(
1, 10)
num3= random.randint(
1, 10)
list=[num1, num2, num3]
maxNum=
max(list)
minNum=
min(list)
sqrtOne= math.sqrt(num1)

correct= False
while
(correct == False):
    guess1=
input(“Which number is the highest? “+ str(list) + “: “)
   
if maxNum == guess1:
       
print(“Correct!”)
        correct =
True
    else
:
       
print(“Incorrect, try again”)

correct= False
while
(correct == False):
    guess2=
input(“Which number is the lowest? ” + str(list) +“: “)
   
if minNum == guess2:
       
print(“Correct!”)
        correct =
True
    else
:
       
print(“Incorrect, try again”)

correct= False
while
(correct == False):
    guess3=
raw_input(“Is the square root of ” + str(num1) + ” greater than or equal to 2? (y/n): “)
   
if sqrtOne >= 2.0 and str(guess3) == “y”:
        
print(“Correct!”)
        correct =
True
    elif
sqrtOne < 2.0 and str(guess3) == “n”:
       
print(“Correct!”)
        correct =
True
    else
:
       
print(“Incorrect, try again”)

print(“Thanks for playing!”)

 

Functions Programs

Program: Multiply all the numbers in a list

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

 

Program: Calculate the factorial of a number

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

 

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

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

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

 

 

Search and Sorting Programs

Program: Program for binary search

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

print(binary_search([1, 2, 3, 5, 8], 6))
print(binary_search([1, 2, 3, 5, 8], 5))

 

Program: Bubble sort

def bubbleSort(nlist):
   
for passnum in range(len(nlist) – 1, 0, –1):
       
for i in range(passnum):
           
if nlist[i] > nlist[i + 1]:
                temp = nlist[i]
                nlist[i] = nlist[i +
1]
                nlist[i +
1] = temp

nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
bubbleSort(nlist)
print(nlist)

 

Program: Selection sort

def selectionSort(nlist):
   
for fillslot in range(len(nlist) – 1, 0, –1):
        maxpos =
0
       
for location in range(1, fillslot + 1):
           
if nlist[location] > nlist[maxpos]:
                maxpos = location

        temp = nlist[fillslot]
        nlist[fillslot] = nlist[maxpos]
        nlist[maxpos] = temp

nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
selectionSort(nlist)
print(nlist) 

 

Program: Shell sort

def shellSort(alist):
    sublistcount =
len(alist) // 2
   
while sublistcount > 0:
       
for start_position in range(sublistcount):
            gap_InsertionSort(alist, start_position, sublistcount)

        print(“After increments of size”, sublistcount, “The list is”, nlist)

        sublistcount = sublistcount // 2

def gap_InsertionSort(nlist, start, gap):
   
for i in range(start + gap, len(nlist), gap):

        current_value = nlist[i]
        position = i

        while position >= gap and nlist[position – gap] > current_value:
            nlist[position] = nlist[position – gap]
            position = position – gap

        nlist[position] = current_value

nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
shellSort(nlist)
print(nlist)

 

Program: Quick sort

def quickSort(data_list):
    quickSortHlp(data_list,
0, len(data_list) – 1)

def quickSortHlp(data_list, first, last):
   
if first < last:
        splitpoint = partition(data_list, first, last)

        quickSortHlp(data_list, first, splitpoint – 1)
        quickSortHlp(data_list, splitpoint +
1, last)

def partition(data_list, first, last):
    pivotvalue = data_list[first]

    leftmark = first + 1
   
rightmark = last

    done = False
    while not
done:

        while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
            leftmark = leftmark +
1

        while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
            rightmark = rightmark –
1

        if rightmark < leftmark:
            done =
True
        else
:
            temp = data_list[leftmark]
            data_list[leftmark] = data_list[rightmark]
            data_list[rightmark] = temp

    temp = data_list[first]
    data_list[first] = data_list[rightmark]
    data_list[rightmark] = temp

    return rightmark

data_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
quickSort(data_list)
print(data_list)

 

Program: Counting sort algorithm

def counting_sort(array1, max_val):
    m = max_val +
1
   
count = [0] * m

    for a in array1:
       
# count occurences
       
count[a] += 1
   
i = 0
   
for a in range(m):
       
for c in range(count[a]):
            array1[i] = a
            i +=
1
   
return array1

print(counting_sort([1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7))

 

Recursion Programs

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

def list_sum(num_List):
   
if len(num_List) == 1:
       
return num_List[0]
   
else:
       
return num_List[0] + list_sum(num_List[1:])

print(list_sum([2, 4, 5, 6, 7])) 

 

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

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

 

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

     1

    1 1

   1 2 1

  1 3 3 1

 1 4 6 4 1

1 5 10 10 5 1

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

 

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

memo = {0:0, 1:1}
def fib(n):
   
if not n in memo:
        memo[n] = fib(n-
1) + fib(n-2)
   
return memo[n]

def find_index(*x):
  
“”” finds the natural number i with fib(i) = n “””
  
if len(x) == 1:
     
# started by user
      # find index starting from 0
     
return find_index(x[0],0)
  
else:
      n = fib(x[
1])
      m = x[
0]
     
if  n > m:
        
return 1
     
elif n == m:
        
return x[1]
     
else:
        
return find_index(m,x[1]+1)

print(” index of a |    a |     b | sum of squares | index “)
print(“=====================================================”)
for i in range(15):
   square = fib(i)**
2 + fib(i+1)**2
  
print( ” %10d |  %3d |   %3d | %14d | %5d ” % (i, fib(i), fib(i+1), square, find_index(square)))

 

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

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

print(sum_series(6))
print(sum_series(10))

 

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

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

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

print(harmonic_sum(7.0))
print(harmonic_sum(4.0))

 

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

def Recurgcd(a, b):
    low =
min(a, b)
    high =
max(a, b)

    if low == 0:
       
return high
   
elif low == 1:
       
return 1
   
else:
       
return Recurgcd(low, high % low)

print(Recurgcd(28, 14)

 

Date Time Programs

 

Program: Python script to display the various Date Time formats

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

 

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

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

 

 

Class Programs

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

Input : [4, 5, 6]

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

 

class py_solution:
   
def sub_sets(self, sset):
       
return self.subsetsRecur([], sorted(sset))

    def subsetsRecur(self, current, sset):
       
if sset:
           
return self.subsetsRecur(current, sset[1:]) + self.subsetsRecur(current + [sset[0]], sset[1:])
       
return [current]

print(py_solution().sub_sets([4, 5, 6]))

 

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

class IOString():
   
def __init__(self):
       
self.str1 = “”

    def get_String(self):
       
self.str1 = raw_input(“Please enter a string: “)

    def print_String(self):
       
print(self.str1.upper())

str1 = IOString()
str1.get_String()
str1.print_String()

 

Program: Get the class name of an instance

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

 

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

class Circle():
   
def __init__(self, r):
       
self.radius = r

    def area(self):
       
return self.radius ** 2 * 3.14

    def perimeter(self):
       
return 2 * self.radius * 3.14

NewCircle = Circle(8)
print(NewCircle.area())
print(NewCircle.perimeter())

 

File Input Output Programs

Program: Count the frequency of words in a file

from collections import Counter
def word_count(fname):
   
with open(fname) as f:
       
return Counter(f.read().split())

print(“Number of words in the file :”, word_count(“readme.txt”))

 

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

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

file_read(‘test.txt’)

 

Program: Get the file size of a plain file

def file_size(fname):
   
import os
    statinfo = os.stat(fname)
   
return statinfo.st_size

print(“File size in bytes of a plain file: “, file_size(“test.txt”))

Regular Expression Programs

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

import re

def text_match(text):
    patterns =
‘^[a-zA-Z0-9_]*$’
   
if re.search(patterns, text):
       
return ‘Found a match!’
   
else:
       
return (‘Not matched!’)

print(text_match(“The quick brown fox jumps over the lazy dog.”))
print(text_match(“Python_Exercises_1”))

 

 

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

import re

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

 

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

import re
street =
’36 Charungee Road’
print(re.sub(‘Road$’, ‘Rd.’, street))

 

Program: Convert camel case string to snake case string

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

print(camel_to_snake(‘PythonExercises’)) 

 

Program: Split a string with multiple delimiters

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

 

 

Some More Programs to Test Your Skills

1.      Design a simple Battleship game. It is a strategy type guessing game between you and the computer. The program should create a 5*5 board and computer will conceil its battleship in a perticular row and column (generated using random number). You will be calling “shots” by guessing where the computer has conceiled its battleship. If you guess the position right then computer’s fleet is destroyed and you win.

 

2.      Generate random password for your gmail ID

Password should be a combination of LOWERCASE_CHARS, UPPERCASE_CHARS, DIGITS and SPECIALS CHARS (‘!’, ‘@’, ‘#’, ‘$’, ‘%’, ‘^’, ‘&’, ‘*’)

 

3.      Print All Integers That Aren’t Divisible by Either 2 or 3 and Lie between 1 and 50

 

4.       Number Reverser: This Python number reverser script will reverse any given number. So, 1234 becomes 4321.

 

5.      URL String Parser: Read a URL string and parse it to get information. Example:

www.cardetails.com?model=x&color=black&package=signature&interior=brown&wheels=alloy

one can parse the domain name, model, color, package, interior and wheels information from the above URL. Output should look something like this:

{‘model’: ‘x’, ‘color’: ‘black’, ‘package’: ‘signature’, ‘interior’: ‘brown’, ‘wheels’: ‘alloy’}

Model: x

Color: black

Package: signature

Interior: brown

Wheels: alloy

 

6.      Hangman Program: Write a program to guess the secret word. Enter a word as input and start guessing the game. Initially  _ will be printed to show the number of characters in the word and then as the user guess it correctly the characters appear on the screen. Max wrong guess is 10 and if the guess is correct then chance is not lost.

 

7.      Write a program that prints the numbers from 1 to 100.

 

But for multiples of three print “Fizz” instead of the number

and for the multiples of five print “Buzz”.

For numbers which are multiples of both three and five print “FizzBuzz”.

 

8.      Dice Roller program for your game of ludo: write a program to generate random number generated between 1-6 (or any range you’d like if you tweak the code), and also you can change the number of dice you want to roll.

 

9.      Search a Computer For Specific Files

In this example, we will see how to use the os.walk() module function to walk a directory tree, and the fnmatch module for matching file names.

 

What is OS.walk?

It generates the file names in a directory tree by walking the tree either top-down or bottom-up.

For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

        dirpath                # is a string, the path to the directory.

        dirnames             # is a list of the names of the subdirectories in dirpath (excluding ‘.’ and ‘..’).

        filenames            # is a list of the names of the non-directory files in dirpath.

        To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

 

The fnmatch module is purely a string matching operation.

Simple Matching: fnmatch() compares a single file name against a pattern and returns a boolean indicating whether or not they match. The comparison is case-sensitive when the operating system uses a case-sensitive file system.

 

Filtering: To test a sequence of filenames, you can use filter(). It returns a list of the names that match the pattern argument.


NO VIDEO - PRACTICE DAY- Practice Above Programs Please

Day 29 : Setember 19, 2022

#Plotting a Histogram 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)
 
Thats the end of this training. hope you enjoyed learning with me, i enjoyed interacting with you. If you need any help or you have question for me, please post the question here and I will try to answer them as soon as possible.