# JULY Weekend Data Science

print(); print(3+5*25+ 100); print(‘3+5*2-5+100 ‘)
print(‘3+5*2-5+100=’, 3 + 5*25+100) #parameters = 2
print(‘3+5*2-5+100=’,3+5*25+100, “Hello”,5*2)
# Comments – this for humans not for computer
# indentation is mandatory in Python

#Process finished with exit code 0 = Exit code 0 means no error as expected

#variable
value1 = 50 #defining a varaible called value1
# lets tale value1 and assume its value is 50
print(value1)
print(“Value1 =”,value1)
value1 = 100
print(“Value1 =”,value1)

value1 = “HELLO”
print(“Value1 =”,value1)

#Basic types of data in Python
# type()
value1 = 50
print(type(value1)) # <class ‘int’>

# int -> integer: -9999999, -87866,0,1,1000,4534563463
#
value1 = 50.0
print(type(value1)) #<class ‘float’>
# e.g. of float: 0.0, -9,0, 89.8777777777777777
print(5+3)
print(5+3.0)
## indentation, ; variables, int, float, type()

# 3. complex
# square root of -1 called complex numbers, example:
num1 = 5j
print(type(num1) ) # <class ‘complex’>
print(num1)
print(num1 * num1)
print(“===========”)
#4. str – string (text)
num1 = “hell” \
“o”
print(num1)
print(type(num1) ) #<class ‘str’>

num1 = ‘5.6’
print(type(num1) )
num1 = “””hello”””
print(type(num1) )
num1 = ”’How
are
you?”’
print(type(num1) )
print(num1)

# 5. bool (boolean): True or False
val1 = True
print(type(val1))

# # # #
# variable names in Python – should always begin with alphabet
# it accepts, alphabets, digits and _
a=5
b=10
c=a+b
print(c)

awetrwetwetwe=5
cYTIUYOYUOJJDHJGN= awetrwetwetwe + bveryaDAGDBBB
print(cYTIUYOYUOJJDHJGN)

num1 = 10
num2 = 5
total = num1 + num2
print(total)

# # # # #
cost_of_each_pen = 59
total_pens = 16
total_cost = cost_of_each_pen * total_pens
print(“Total cost = “,total_cost)
print(“Cost of each pen is”,cost_of_each_pen,“so the cost of”,total_pens,“pens will be”,total_cost)
#above output using format string (f-string)
print(f”Cost of each pen is {cost_of_each_pen} so the cost of {total_pens} pens will be {total_cost})
print(“Cost of each pen is {cost_of_each_pen} so the cost of {total_pens} pens will be {total_cost}”)

total_pens = 3
total_cost = 100
cost_of_each_pen = total_cost / total_pens
print(“Total cost = “,total_cost)
print(“Cost of each pen is”,cost_of_each_pen,“so the cost of”,total_pens,“pens will be”,total_cost)
#above output using format string (f-string)
print(f”Cost of each pen is {cost_of_each_pen:.2f} so the cost of {total_pens} pens will be {total_cost})
print(“Cost of each pen is {cost_of_each_pen} so the cost of {total_pens} pens will be {total_cost}”)

name,country,position = “Virat”,“India”,“Opener”
print(f”Player {name:>15}, plays for the country {country:^20} at {position:<20})
name,country,position = “Manbagwama”,“New Zealand”,“Wicket-Keeper”
print(f”Player {name:>15}, plays for the country {country:^20} at {position:<20})

# operators: Arithematic operations
## + – * / // (integer division) ** (power) %(modulus – remainder)
num1 = 56
num2 = 3
print(num1 + num2)
print(num1 – num2)
print(num1 * num2)
print(num1 / num2)

print(num1 // num2)
print(num1 % num2)
print(num1 ** num2)

print(100 ** (1/2))

# Relational, Logical, Membership

## Assignments ##
# WAP to calculate area and perimeter of a rectangular field when length and breadth are given
# WAP to calculate area and circumference of a circular field when radius is given

## DAY 2 : Recording Basic Python

# Comparison / Relational Operators
# check relationship: > < >= <= == !=
# output is bool (True / False)
var1, var2, var3 = 10,20,10 #lets assign value 10 to var1
print(var1 > var2) # False
print(var1 > var3) # False
print(var1 < var2) # True
print(var1 < var3) #False
print(var1 >= var2) #False
print(var1 >= var3) #True
print(“===============”)
print(var1 <= var2) # True
print(var1 <= var3) # True
print(var1 == var2) #False – is var1 equal to var2 ?
print(var1 == var3) #True
print(var1 != var2) # True
print(var1 != var3) # False

# Logical operator: and or not
# input and output are bool
# prediction: Rohit and Surya will open the batting – False
# actual: Ishan and Surya opened the batting
# in AND, even if one is False entire thing becomes False
# prediction: Rohit or Surya will open the batting – True
# actual: Ishan and Surya opened the batting
# in OR, even if one is True entire thing becomes True
print(True and True) #True
print(False and False) #False
print(False and True) #False
print(True and False) #False

print(True or True) #True
print(False or False) #False
print(False or True) #True
print(True or False) #True

##
print(“check”)
var1, var2, var3 = 10,20,10
print(var1 > var2 and var1 > var3 or var1 < var2 and var1 == var3 or var1 != var2 and var1 <= var3)
#(T or T)
print(not True)
print(not False)

# Membership operator: in , not in
print(“i” in “india”)

# looping – when you run a block of code multiple times
## keep looping till yot get the stopping condition – WHILE loop
## exatly how many times to run a code: FOR loop

# if is to check the conditoon
num=8
# condition – usng if
if num ==8:
print(“Value is “,num)
print(“if is executed now”)

# you can have only IF
# or when you have something to talk about when IF is false – ELSE
if num ==18:
print(“Value is “,num)
print(“if is executed now”)
else:
print(“I am in ELSE”)

#WAP to check if a number is positive or not
num = 5
if num >0:
print(“Number is positive”)
else:
print(“Number is not positive”)

# WAP to check if a number is odd or even
num = 11
if num%2!=0:
print(“Its odd number”)
else:
print(“Its even number”)

## input() – take input from the user
val1 = input(“Enter your marks: “)
print(“1. Data type of val1 is: “,type(val1))
val1 = int(val1) # int() float() bool() str() complex() – explicit conversion
print(“2. Data type of val1 is: “,type(val1))
print(“Value you entered is “,val1)

## WAP a program to input value from the user and check if it has 0 at the end
## Value = 57 – it doesnt have zero at the end
## value = 60 – it should say it has zero at the end.

value = int(input(“Enter the number:”))
if value %10==0:
print(“This has zero at the end”)
else:
print(“It doesnt have zero at the end”)

# if a number is positive or negative or zero
num = int(input(“Enter a number: “))
if num == 0:
print(“Number is zero”)
elif num < 0:
print(“Number is negative”)
else:
print(“Number is Positive”)

sum = 360
avg = sum/5

if avg >= 75:
elif avg >=60:
elif avg>=50:
elif avg >=35:
else:

## DAY 3 Video: Operators and IF-ELIF-ELSE

# if the score is more than 90, invite them for tea with director
avg = 98 #98: 2 88: 2 68: 3 & #98: 2 88: 1 68: 3

if avg >=80:
if avg >= 90:
print(“You are invited for tea @5pm auditorium”)
if avg >=95:
print(“You win President Award!”)
print(“Excellent result”)
print(“Great going!”)
elif avg >=60:
elif avg >=40:
elif avg >=30:
else:
print(“Sorry you have failed”)
print(“Try again next time”)

# find the highest number of the given 3 numbers
Num1 = 99
Num2 = 78
Num3 = 123
if Num1 > Num2:
if Num1 > Num3:
print(f”For the assignment given by Swapnil Num1={Num1} value is highest”)
if Num2 > Num1:
if Num2 > Num3:
print(f”For the assignment given by Swapnil Num2={Num2} value is highest”)
if Num3 > Num1:
if Num3 > Num3:
print(f”For the assignment given by SwapnilNum3={Num3} value is highest”)
## ##
num1 = 198
num2 = 198
num3 = 168

if num1 > num2:
if num1 > num3:
print(“{num1} is greater”)
else:
print(“{num3} is greater”)
else:
if num2 >num3:
print(“{num2} is greater”)
else:
print(“{num3} is greater”)

###
num1 = 98
num2 = 128
num3 = 168
high = num1
if high < num2:
high = num2
if high <num3:
high = num3
print(f”{high} is the highest”)

# WAP to input 3 sides of a triangle and find if its a equilateral, isoceles or scalene
num1 = 128
num2 = 128
num3 = 128
s1=num1; s2=num2; s3=num3
if s1==s2:
if s2==s3:
print(“As all 3 sides of triangle is equal hence it is an equilateral triangle”)
else:
print(“As 2 sides of an triangle are equal hence it is an isosceles triangle”)
else:
if s2==s3 or s3==s1:
print(“As 2 sides of an triangle are equal hence it is an isosceles triangle”)
else:
print(“As no sides are equal it is an scalene triangle”)

num1 = 128
num2 = 108
num3 = 128

if num1 == num2:
if num1 == num3:
print (“equilateral triangle”)
else:
print(“isoscales triangle”)
else:
if num2 == num3 or num1==num3:
print (“isoscales triangle”)
else:
print(“scalene triangle”)

## below: bad example of the code
num1 = 128
num2 = 108
num3 = 128

if num1 == num2 and num1==num3:
print (“equilateral triangle”)
if (num1 == num2 and num2!=num3) or (num1==num3 and num3!=num2) or (num2==num3 and num3!=num1):
print (“isoscales triangle”)
if (num1 !=num3 and num1!=num2) or (num2 !=num1 and num2!=num3) or (num3 !=num1 and num2!=num3):
print(“scalene triangle”)

# for loop
# range(a,b,c): a=start, b< end (upto, not equal to), c = increment
#range(2,12,3)# generates range of values- 2,5,8
# range(a,b) default c value is ONE
#range(5) #default start = 0, increment =1: 0,1,2,3,4

for counter in range(10):
print(counter)

# while: loops until the given condition
z=0
while z<=10:
print(z)
z=z+ 1

## DAY 4 Video: IF -ELIF - ELSE practice Problems

### Click here to practice Python condition programs

# divisible by 100 & 400 – leap year, divisible by 100 but not 400 – not a leap year
# divisible by 100 but divisible by 4 – leapyear

year = 400
if year %100==0:
if year %400==0:
print(“Leap Year”)
else:
print(“Not a leap year”)
else:
if year %4==0:
print(“Leap Year”)
else:
print(“Not a leap Year”)

####
a,b,c,d = 40,10,20,5
small = a
if b <small:
small=b
if c <small:
small=c
if d <small:
small=d

num=str(1234567)
print(“Number of characters = “,len(num))
num = 158
length = 1
a = num//10
if a!=0:
length+=1 # length = length + 1
num = num//10

a = num//10
if a!=0:
length+=1 # length = length + 1
num = num//10

a,b,c=20,10,30

if a < b:
a,b=b,a
if b < c:
if a>c:
print(c, “is second highest”)
else:
print(a,“is second highest”)
else:
print(b,“is second highest”)

eng = 85
maths,science,ss = 90,90,80
if eng >=80:
if ss>=80:
if maths>=80 and science >= 80:
print(“Science Strean”)
else:
print(“Humanities Stream”)
elif maths >= 50 and science >= 50:
print(“Commerce”)

else:
# loops – repeat multiple times
# for: used when you know how many times to repeat
# while: in which conditions to repeat

#range(): which generates range of values
# range(=start, <end, increment)
# range(3,11,2): 3,5,7,9
# range(=start, <end) : increment is default 1
# range(5,9): 5,6,7,8
# range(<end): default start = 0 & increment is 1
# range(4): 0,1,2,3

for counter in range(3,11,2):
print(“Counter = “,counter)
print(“Hello”)

#print even numbers from 6 to 20
for i in range(6,21,2):
print(i,end=“, “)
print()

# find sum of numbers between 5 and 9 both including
sum=0
for i in range(5,10):
sum+=i
print(“Sum = “,sum)

# generate first 4 multiples of 5: 5 10 15 20
num = 15
for j in range(4):
print(f”{num} * {j+1} = {num*(j+1)})

print(“WHILE : condition based repeation”)
count = 1
while count <=8:
count += 2
print(count)

# print hello till user says yes

while True:
print(“HELLO”)
ch = input(“Enter y to print again or anyother key stop: “)
if ch!=‘y’:
break

”’
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
”’
print(“Pattern 1”)
for j in range(5):
for i in range(5):
print(“*”, end=” “)
print()

”’
*
* *
* * *
* * * *
* * * * *
”’
print(“Pattern 2”)
for j in range(5):
for i in range(j + 1):
print(“*”, end=” “)
print()

”’
* * * * *
* * * *
* * *
* *
*
”’
print(“Pattern 3”)
for j in range(5):
for i in range(5 – j):
print(“*”, end=” “)
print()

”’
Assignment 1:
* * * * *
* * * *
* * *
* *
*

Assignment 2:
*
* *
* * *
* * * *
* * * * *

Assignment 3: Multiplication Table:

1 * 1 = 1 2 * 1 = 2 … 10 * 1 = 10
1 * 2 = 2 2 * 2 = 4 10 * 2 = 20

1 * 10 = 10 2 * 10 = 20 10 * 10 = 100
”’

## Check if Prime or not
num = 53
isPrime = True
for i in range(2, num // 2 + 1):
if num % i == 0:
isPrime = False
break

if isPrime:
print(f”{num} is Prime”)
else:
print(f”{num} is not Prime”)

import time
curr = time.time()
line = 0
## Generate Prime numbers between 20000 and 30000
for num in range(20000,30001):
isPrime = True
for i in range(2,num//2+1):
if num % i==0:
isPrime = False
break

if isPrime:
if line >= 20:
print()
line = 0
print(num, end=“,”)
line+=1
end = time.time()
print(\n\nTotal time taken to generate prime numbers is “,end-curr,“seconds”)
print(“Time is: “,time.time())

## Day 5 Video: LOOPS in Python

”’
1*1 = 1 2 * 1 = 2 …
1 * 2..

1 * 10

”’
s=0
for i in range(1,11,1):
s += 1 # s=s+1
for j in range(1,11):
print(f”{j:<2}*{i:>2}={j*i: <3}, end=” “)

print()

print(“S = “, s)
## WHILE LOOP
num = 1
ch = “y”
while ch==“y”:
num+=1
ch=input(“Enter y to continue or anyother key to stop: “)

print(“num = “,num)
##
while True:
print(“Now, pick up the option:”)
print(“2. Subtraction”)
print(“3. Multiplication”)
print(“4. Division”)
print(“5. Quit”)
choice = int(input(“Enter your option from the above menu:”))

if choice>=1 and choice <=4:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))

if choice==1:
print(“Addition of given numbers: “,num1+num2)
elif choice==2:
print(“Subtraction of given numbers: “,num1-num2)
elif choice==3:
print(“Multiplication of given numbers: “,num1*num2)
else:
print(“Division of given numbers: “,num1/num2)
elif choice==5:
break
else:
print(“Invalid option, try again!”)

##
”’
Guess the number game!
Computer v Human

Module: has collection of related functions
randint(1,100) – will return random integer number between 1 and 100 (both including)
”’
import random

num = random.randint(1, 100)
attempt = 0
while True:
guess = int(input(“Guess the number: “))
if guess < 1 or guess > 100:
print(“Invalid guess, try again”)
continue

attempt += 1
if num == guess:
print(f”Congratulations! You guessed it right in {attempt} attempts.”)
break
elif num < guess:
print(f”Your {guess} is higher.. try with a lower guess!”)
else:
print(f”Your {guess} is lower.. try with a higher guess!”)
”’
Guess the number game!
Computer v Computer

Module: has collection of related functions
randint(1,100) – will return random integer number between 1 and 100 (both including)
”’
import random
import time

start = time.time()
num = random.randint(1,100)
low,high =1,100
attempt = 0
while True:
guess = random.randint(low,high)
attempt+=1
if num==guess:
end = time.time()
print(f”Congratulations! You guessed it right in {attempt} attempts and in {end-start} seconds.”)
break
elif num < guess:
print(f”Your {guess} is higher.. try with a lower guess!”)
high = guess-1
else:
print(f”Your {guess} is lower.. try with a higher guess!”)
low = guess + 1

## ### ### ##
”’
WAP a Program to generate prime numbers from 1 till user continue to ask
2
you want more? y
3
you want more? y
5
you want more? y
7
you want more? y
11
you want more? n
Thank you

”’
num = 1
while True:
num+=1
isPrime = True
for i in range(2,num//2+1):
if num%i==0:
isPrime=False
break
if not isPrime:
continue
print(num)
ch=input(“you want more (y for yes)?”)
if ch!=“y”:
break
## ##
## STRINGS
str1 = ‘Hello’ # one line text
str2 = “Hi there” # one line text
str3 = ”’How are you?
Where are you?
How you doing?”’ # multiline text
str4 = “””I am fine
I am here
i am great””” # multiline text
print(type(str1),type(str2),type(str3),type(str4))
print(str1,\n,str2,\n,str3,\n,str4)

# \n is used for newline
# \ – escape character { this will add power / remove power if you have power}
# \\ – will make one \
print(\\n is used for newline \\t is used for Tab spaces \\c has not meaning”)

# \\n \\t \\c
print(\\\\n \\\\t \\\\c”)

## DAY 6 Video: WHILE Loop - Example

## STRING
str1 = “hello 5”
str2 = “how are you”
# he asked,”how are you?”
print(‘he asked,”how are you?”‘)
print(“he asked,\”how are you?\”)
print(str1 + ” “+ str2)
print((str1+” “)*5)

for i in str1:
print(i)

# len() – will tell you the length of the variable
print(f”Number of elements in {str1} is”,len(str1))

for i in range(len(str1)):
print(i, ” – “,str1[i])

# indexing: accessing the member from a string /data collection
str1 = “helloshnrtmd”
print(str1[0])
last_idx = len(str1) – 1
print(str1[-1])
# str1[0] = “H” – error

# string is immutable – you cant edit
a=5
a=6
str1 = “hello”
str1 = “Hello”
print(“ell”, str1[1:4], str1[-4:-1])
print(“Hell”,str1[0:4],str1[:4], str1[:-1])
print(“ello”,str1[1:5],str1[1:], str1[-4:])

# Functions (global) and Methods (specific to the class)
str1 = “HelLo how are you”
str2 = “hello”
anything =
print(“Lower: “,str1.lower())
print(“Uppercase: “,str1.upper())
print(“STR1 = “,str1)
print(“Title Case: “, str1.title())
print(str2.islower())
print(str2.upper().isupper())
print(str2.isalnum())
print(str2.isdigit())

num1 = input(“Enter length of the rectangle: “)
if num1.isdigit():
num1 = int(num1)
else:
print(“Invalid number”)

# modify below program to accept space also
name = input(“Enter your name: “)
if name.isalpha():
print(“Name accepted”)
else:
print(“Invalid name”)

## DAY 7 Video: String tutorial - Part 1

# modify below program to accept space also
name = “Sachin Tendulkar”
if name.isalpha():
print(“Name accepted”)
else:
print(“Invalid name”)

output = name.split() #split by default will split on ‘ ‘
output_str = “”.join(output)
print(output_str)
if output_str.isalpha():
print(name,“Name accepted”)
else:
print(“Invalid name”)

print(“Strip —“)
txt = ” 2 4 6 8 “
print(txt.strip(), “length is”,len(txt.strip()))

# replace find count
print(“blank spaces are:”,txt.count(” “))
txt2 = “Twinkle Twinkle Twinkly Star”
print(“Count Twin: “,txt2.count(“Twin”))
print(“Find Twin: “,txt2.find(“Twin”))

# Print the position of all the occurrences
st=0
for i in range(txt2.count(“Twin”)):
cnt = txt2.find(“Twin”,st)
print(“Find Twin: “, cnt)
st = cnt+1

txt2 = “Twinkle Twinkle Twinkly Star”
txt3 = txt2.replace(“Twin”,“Quin”)
print(txt3)
txt3 = txt2.replace(“Twin”,“Quin”,2)
print(txt3)
print(“Check if txt2 starts with t: “,txt2.startswith(“t”))
print(“Check if txt2 starts with t: “,txt2.startswith(“T”))
print(“Check if txt2 starts with t: “,txt2.endswith(“r”))
print(“Check if txt2 starts with t: “,txt2.endswith(“R”))

# LIST: linear mutable ordered collection
l1 = []
print(type(l1))
l1 = [3,4,6,8,9]
print(“Getting last 3 values:”)
print(l1[2:])
l1[0]=0
print(l1)

l2 = [“Hello”, 45, 66.6, 5j , True, [5,10,15,20]]
print(l2)
print(type(l2))
print(type(l2[3]))

print([2,4,6]+[4,8,12])
print([2,4,6] * 5)

###
for i in l2:
print(i)

fare=[]
fare.append(50) # append is used to add members to a list at the end
fare.append(60)
fare.append(45)
fare.insert(1,77)
fare.insert(1,44)
print(“Fare = “,fare)

fare.pop(2)
print(“Fare = “,fare)
fare.remove(60)
print(“Fare = “,fare)
fare.clear()
print(“Fare = “,fare)

marks = []
tot = 0
for i in range(5):
m = int(input(“Enter marks = “))
marks.append(m)
tot+=m

print(“Marks = “,marks)
print(“Total marks is”,sum(marks))
print(“Total = “,sum(marks)/len(marks))

## DAY 8 Video String Tutorial Part 2 and List Tutorial 1

#LIST

”’
## Assignment: Implement Stack and Queue operations using List
Stack is called as – Last in First out structure (LIFO)

Queue: First In First Out (FIFO)

”’
l1 = [2,4,8,14,16]
num= 140
if l1.count(num) >0:
print(“Index: “,l1.index(num))
else:
print(f”{num} is not in the list”)

print(l1.index(14,2,6))
print(“0. L1 = “,l1)
l2 = l1.copy() # shallow copy – creates another copy
l3 = l1 # deep copy – another name for same data
print(“1. L1 = “,l1)
print(“1. L2 = “,l2)
print(“1. L3 = “,l3)
l1.append([18,20])
l1.append(20)
print(“2. L1 = “,l1)
print(“2. L2 = “,l2)
print(“2. L3 = “,l3)

l1.extend(l3) # l1 = l1 + l3
print(l1)

l4 = [5,9,1,4,2,3,6]
l4.reverse()
print(l4)
l4.sort()
print(l4)
l4.sort(reverse=True)
print(l4)

# [[4,6,8],[9,5,2],[5,9,1]] – find highest value at each position.
l1 = [[5, 6, 8], [5, 0, 0], [5, 9, 1]]
print(“the largest element is”, max(l1))

data = []
for i in range(3):
temp = []
for j in range(3):
val = int(input(“Enter value: “))
temp.append(val)
data.append(temp)

print(“Data = “,data)
# data = [[5, 4, 3], [6, 7, 5], [9, 8, 7]]
max_list = [-999,-999,-999]
for i in range(3):
for j in range(3):
if max_list[i] < data[j][i]:
max_list[i] = data[j][i]

print(max_list)

# Assignment 2: Find the highest element for each of the sub-list

# TUPLE: Linear immutable Ordered collection
t1 = (1,2,3)
print(type(t1))
print(t1.count(3))
print(t1.index(3))
# indexing is exactly same as Str/List
for i in t1:
print(i)
a,b,c = t1
print(a,b,c)
d = [(1,2,3,4,5,6),(1,2,3,4,5,6),(1,2,3,4,5,6),(1,2,3,4,5,6)]
t1 = list(t1)
t1 = tuple(t1)

## ##
# Dictionary: Linear mutable unordered collection
# dictionary is your key:value (key value pairs)
d1 = {“Name”:“Sachin”,“Runs”:21000,3:“Mumbai”, True:“Mumbai Indians”}
print(d1)
print(d1[“Name”])
d1[“Name”] = “Sachin Tendulkar”
print(d1)

d2 = d1 #deep copy
d3 = d1.copy() #shallow copy
print(“1. D1 = “,d1)
print(“1. D2 = “,d2)
print(“1. D3 = “,d3)
t = {“Country”:“India”}
d1.update(t)
print(“2. D1 = “,d1)
print(“2. D2 = “,d2)
print(“2. D3 = “,d3)

print(d1.keys())
print(d1.values())
print(d1.items())

for i in d1.keys():
print(i)
print(“================”)
for i in d1.values():
print(i)
print(“================”)
for i in d1.items():
print(i)
print(“================”)

for i,j in d1.items():
print(i,“:”,j)
print(“================”)

d1.pop(“Name”)
print(d1)
d1.popitem()
print(d1)

## DAY 9 List Tutorial Part 2, Tuple and Dictionary part 1

## 7th Oct 2023
list1=[“Maths”,“Physics”,“Chemistry”]
Students_marks = {}
for i in range(3):
key = input(“Enter the Roll No. of the Student:”)
marks_list = []
for j in range(3):
marks = int(input(f”Enter the marks in {list1[j]}: “))
marks_list.append(marks)
t = {key:marks_list}
Students_marks.update(t)

print(“Details of marks are:\n,Students_marks)
# {‘101’: [67, 78, 89], ‘105’: [69, 71, 90], ‘110’: [90, 45, 76]}
”’
Assignment: Extend the above program to find:
1. Total of each student
2. Highest marks obtained among the given students
3. Give roll no of topper of each subject
”’
# Dictionary : unordered mutable collection
d1 = {10:“ONE”, 20:“TWO”,30:“THREE”}
d1.pop(20)
print(d1)

d2 = d1
d3 = d1.copy()
print(“1. D1 = “,d1)
print(“1. D2 = “,d2)
print(“1. D3 = “,d3)
d1.update({40:“Four”})
d1.update({50:“Five”})
print(“2. D1 = “,d1)
print(“2. D2 = “,d2)
print(“2. D3 = “,d3)

# SET : unordered collection
set1 = {5,8, 8, 5, 5,12}
print(type(set1))
print(set1)
set1.update({1,2,3})
print(set1)
set1.pop()
print(“After pop: “,set1)

l1 = [5,10,10,15,15,15,20,20,20,20]
l1 = list(set(l1))
print(“List l1 = “,l1)

# SET OPERATIONS
set1 = {1,3,5,7,6}
set2 = {2,4,6,8,7}
print(set1)
print(set2)
print(“UNION”)
print(set1.union(set2))
print(set1 | set2)
print(“INTERSECTION”)
print(set1.intersection(set2))
print(set1 & set2)
print(“SET1 – SET2”)
print(set1.difference(set2))
print(set1 – set2)
print(“SET2 – SET1”)
print(set2.difference(set1))
print(set2 – set1)

print(“SYMM SET1 – SET2”)
print(set1.symmetric_difference(set2))
print(set1 ^ set2)
print(“SYMM SET2 – SET1”)
print(set2.symmetric_difference(set1))
print(set2 ^ set1)

print(set1.isdisjoint(set2))
set4 = {10,20,30}
print(set1.isdisjoint(set4))

d1 = {“Good”:{“Excellent”,“Positive”,“Nice”}}
print(d1)

# one line loops
words = ‘abcdefghijklmnopqrstuvwxyz’
# go through words list and save to another list
words2 =[]
for w in words:
words2.append(w)

print(“Words 2: “,words2)

words3 = [w*2 for w in words]
print(“Words 3: “,words3)

words = ‘abcdefghijklmnopqrstuvwxyz’
words3 = [w*2 for w in words]
print(“Words 3: “,words3)

# one line conditions
num1 = 50
#check if its odd or even
result = “even” if num1%2==0 else “odd”
print(f”{num1} is {result})

# Functions
”’
Inbuilt functions: print(), type(), int(),…
User defined functions: we create our own functions
One line function:
”’

#this is how you define a function by name three_sentences()
def three_sentences():
print(“Who are you?”)
print(“How are you?”)
print(“Where are you?”)

def three_sentencesv1(var_name):
print(f”Who are you, {var_name}?”)
print(f”How are you, {var_name}?”)
print(f”Where are you, {var_name}?”)

add = num1 + num2

#Calling the functions
three_sentences()
three_sentencesv1(“Mr Sachin”)
three_sentencesv1(“Ms Sindhu”)
print(“Output is”,result)
if result >= 0:
print(f”I got {result} sweets”)

## DAY 10: Dictionary Part 2, SETS, Functions Part 1

# Functions
# arguments:
# required – you have to provide the values for the arguments
# positional – the order of the arguments should match
# default (like non-required values)
# keyword (like non-positional)

country = “INDIA” #global variable
#function definition
def func1(num1, num2):
print(“A block of code”)
print(“Num1 =”,num1)
print(“Num2 = “,num2)
total = num1 + num2
def func2(num1, num2=1): #default value for num2
print(“A block of code”)
print(“Num1 =”,num1)
print(“Num2 = “,num2)
total = num1 * num2

def func3(num1=10, num2=5): #default value for num2
print(“A block of code”)
print(“Num1 =”,num1)
print(“Num2 = “,num2)
total = num1 * num2

def func4(x,y,num1=10, num2=5,num3=25,num4=85): #default value for num2
print(“A block of code”)
print(“Num1 =”,num1)
print(“Num2 = “,num2)
total = num1 * num2

def test():
global country #local – local will preceed global
print(“Country is”,country)
country=“india” #local – local will preceed global
print(“Country is”, country)

# variable length arguments: using * and **
# * read as a tuple
# ** read as a dictionary
def var_len_demo(num, *names, **favorite):
print(“Variable length arguments functon”)
print(“Num is”,num)
if len(names)>0:
print(“Names = “,names)
if len(favorite) > 0:
print(“Favorites = “,favorite)

result = func1(5,10)
print(“func1 Output is “,result)
result = func2(5)
print(“func2 Output is “,result)
result = func3(5,7)
print(“func2 Output is “,result)
result = func3()
print(“func2 result that we have is “,result)

result = func3(num2=15,num1=99)
print(“func2 Output is “,result)
result = func3(num2=15)
result *=10
print(“func2 Output is “,result)
print(“func4 Output is”,func4(5,6))

# wap to check if a number is prime or not
def checkprime(num):
isPrime = True
if num<2:
isPrime = False
elif num>2:
for i in range(2,num//2+1):
if num%i==0:
isPrime=False
break
else:
isPrime=True
return isPrime

for val1 in range(15,18):
result = checkprime(val1)
if result:
print(f”{val1} is a prime number”)
else:
print(f”{val1} is not a prime number”)

print(‘generate series of prime numbers between 50000 and 51000:’)
for i in range(50000,51001):
result = checkprime(i)
if result:
print(i,end=“, “)
print()
”’
Assignment:
All the programs that you have done so far – convert them
into functions – all your core logic should be in the function
and only the values to the arguments should be passed to the
function and the output displayed in the main function.
”’
def printpattern(value,num):
for i in range(num):
for j in range(num):
print(value,end=” “)
print()

printpattern(“#”,7)
test()

# calling variable length
var_len_demo(100)
var_len_demo(11, “Sachin”,“Virat”,“Rohit”,“MS”)

## DAY 11: Functions, Modules and Packages

# Class and Objects
## —————–
class Book:
total_books = 0 # class member/variable

def input_data(myname):
myname.title = “” #object variable
myname.author = “” #object variable
type = “book”
myname.mytype = type

def set_data(myname):
myname.title = “Python Programming” #object variable
myname.author = “Saurav” #object variable

b1= ‘hello’
print(“Type of b1 = “,type(b1))
print(b1.upper())
book1 = Book()
print(“Type of book1 = “,type(book1))

book1.total_books += 10
print(book1.total_books)
book1.input_data() #object function
print(“Author: “,book1.author)
book1.set_data()
print(“Author: “,book1.author)

# Class and Objects
# Program 2
## —————–
class Book:
total_books = 0 # class member/variable

def input_data(self):
self.title = “” #object variable
self.author = “” #object variable
Book.total_books +=1

def set_data(self, title,author=“Saurav”):
self.title = title #object variable
self.author = author #object variable

book2 = Book()
book2.input_data()
book2.set_data(“Python Programming”,“Sachin”)
book3 = Book()
book3.input_data()
book3.set_data(“Machine Learning”,“Rohit”)
book4 = Book()
book4.input_data()
book4.set_data(“SQL Programming”)
print(“Total books = “,book2.total_books)
print(“Total books = “,book3.total_books)
print(“Total books = “,book4.total_books)
print(“Total books = “,Book.total_books)

print(“Title = “,book2.title)
print(“Title = “,book3.title)
print(“Title = “,book4.title)
#print(“Title = “,Book.title)

## Day 12 Python Tutorial: Class and Objects in Python - I

# class and objects

class Books:
total_books = 0 #class variable

def getdata(self,title,author): #object method
self.title = title #object variable
self.writer = author
Books.total_books +=1
print(“Hello”)

def putdata(self):
print(“Title of the book: “,self.title)
print(“Author of the book: “, self.writer)

@classmethod
def CountBooks(cls):
print(“Total books in the library are:”,cls.total_books)

b1 = Books()
b2 = Books()
print(“Total books = “,b1.total_books)
print(“Total books = “,Books.total_books)
b1.getdata(“Python”,“Rohit”)
b2.getdata(“SQL”,“Virat”)
b2.putdata()
b1.putdata()
print(“Total books = “,Books.total_books)
print(“Total books = “,b1.total_books)
print(“Total books = “,b2.total_books)
b2.CountBooks()

### ### ####
# class and objects
class Library:
def libname(self):
print(“I am being called from Library”)
class Books(Library):
total_books = 0 #class variable

def __init__(self,title,author): #object method
self.title = title #object variable
self.writer = author
Books.total_books +=1
print(“Hello”)

def putdata(self):
print(“Title of the book: “,self.title)
print(“Author of the book: “, self.writer)

@classmethod
def CountBooks(cls):
print(“Total books in the library are:”,cls.total_books)

b1 = Books(“Python”,“Rohit”) #__init__()
b2 = Books(“SQL”,“Virat”)
print(“Total books = “,b1.total_books)
print(“Total books = “,Books.total_books)
#b1.getdata(“Python”,”Rohit”)
#b2.getdata(“SQL”,”Virat”)
b2.putdata()
b1.putdata()
print(“Total books = “,Books.total_books)
print(“Total books = “,b1.total_books)
print(“Total books = “,b2.total_books)
b2.CountBooks()

”’
Properties of class and objects:
1. Inheritance: inheriting properties from another class
2. Polymorphism: Multiple forms
3. Abstraction: information/implementation hiding
4. Encapsulation: data hiding
”’
b1.libname()

class text_display(Books):
def __init__(self, title, author):
print(“INIT in text_display”)
Books.__init__(self, title, author)

def display(self):
print(“Display in text_display”)

def putdata(self):
print(“Title of the book: “)
print(“Author of the book: “)

t1 = text_display(“Waste Management”,“Dhoni”)
t1.putdata()

## Day 13 Python Tutorial: Class and Objects in Python - II

# Encapsulation in Python
”’
Public members (variable or method)
Protected members (_membersname): logically these members can only
be called by the derived classes. concept is there but not enforeced
Private members (__membername): they are not accessible outside the class

”’
class Library:
def __lib_data(self):
print(“Lib data from Library”)
def get_data(self):
self.__lib_data()
class Books(Library):
def book_data(self):
print(“Book data from Books”)

def get_data(self):
Library.__lib_data(self)
print(“Get data from Books”)

class Test:
def test_data(self):
print(“Test data from Test”)

b1 = Books()
b1.get_data()
## #####

# work with external files – text files
”’
Modes of opening file:
r : read the content (default)
w : write the content by deleting previous content
a : add to the existing content (append)

r+ : read and write
w+ : write and read
a+ : append and read

Writing to a text file:
write()
writelines()

Reading the content from a text file:
”’
content = ”’Twinkle Twinkle little star
How I wonder what you are
Up above the world so high
like a diamond in the sky
”’

cont_lt = [‘Ba Ba Black Sheep\n,‘Do you have any wool?\n,
‘Yes sir yes sir\n,‘Three bags full\n]
fileptr = open(“TestNov\\abc.txt”,“a”)
if fileptr.writable():
fileptr.write(content)
fileptr.writelines(cont_lt)
else:
print(“File cant be written”)

fileptr.close()

## open the file for reading
fileptr = open(“TestNov\\abc.txt”,“r”)
# read the content
else:

print(“===================”)
print(mycontent.replace(“Twinkle”,“TWINKLE”))
mycontent = mycontent.replace(“Twinkle”,“TWINKLE”)
print(mycontent)

# go to beginning
fileptr.seek(30) #go to the position 0
print(mycontent)
fileptr.seek(0)
print(“============ Read line =================”)
print(content)
print(content)
print(content)

print(content)

fileptr.seek(0)
print(content_lines)
print(“Total number of lines = “,len(content_lines))
fileptr.seek(0)
print(“Number of characters = “,len(allcontent))
txt1 = “welcome”
print(len(txt1))
fileptr.close()

## Working with CSV files
import csv
”’
r, r+, w, w+, a, a+ : different modes of files to read
”’
fileptr = open(“TestNov/abc.csv”,“w”,newline=“”)
csv_writer = csv.writer(fileptr)
content_list = [[“SNO”,“Name”,“City”,“Runs”],
[1,“Rohit”,“Mumbai”, 3500],
[2,“Virat”,“Delhi”,4210],

for i in content_list:
csv_writer.writerow(i)
fileptr.close()

fileptr = open(“TestNov/abc.csv”,“w”,newline=“”)
csv_writer = csv.writer(fileptr,delimiter=“,”)
content_list = [[“SNO”,“Name”,“City”,“Runs”],
[1,“Rohit”,“Mumbai”, 3500],
[2,“Virat”,“Delhi”,4210],

csv_writer.writerows(content_list)
fileptr.close()
print(“Reading the CSV file\n)
fileptr = open(“TestNov/abc.csv”) #default mode is read
for i in csv_reader:
print(i)
fileptr.close()

fileptr = open(“TestNov/abc.csv”) #default mode is read
count=0
for i in csv_reader:
if count==0:
count+=1
else:
print(i[1])
break
fileptr.close()

### working with json file
json1 = {
“Player1”:[
{
“Name”:“Sachin”,
“City”:“Mumabi”,
“Runs”: 13980
}
]
}

import json
”’
dump: writing to a file
dumps: writing to screen
”’
# dump – writing to a file
fileptr = open(“TestNov/abc.json”,“w”)
json.dump(json1, fileptr,indent=4)
fileptr.close()
#load – reading json content from the file
fileptr = open(“TestNov/abc.json”,“r”)
print(“printing from the file:\n,content)
#writing in json format on the screen
print(json.dumps(content,indent=4))
fileptr.close()

json_str = “””{“Player1”: [{“Name”: “Sachin”, “City”: “Mumabi”, “Runs”: 15980}]}”””
#convert above string into json format
#above json_json content we will display on the screen
# and also save to the file
fileptr = open(“TestNov/abc.json”,“w”)
json.dump(json_json, fileptr,indent=4)
fileptr.close()

print(json.dumps(json_json,indent=4))

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

### Assingment ###
### Read India and South Africa today’s match data as a csv
## write using Python (csv.writer)
### then use reader to answer following question
### 1. Who is the top scorer
### 2. Who is the highest wicket taker
### 3. Who has the best bowling average
### 4. Who has the best strike rate

### Example
### working with json file
json1 = {
“Players”:[
{
“Name”:“Sachin”,
“City”:“Mumabi”,
“Runs”: 13980
},
{
“Name”:“Laxman”,
“Runs”: 15980
},
{
“Name”:“Rahul”,
“City”:“Bangalore”,
“Runs”: 11980
}
]
}

import json
”’
dump: writing to a file
dumps: writing to screen
”’
# dump – writing to a file
fileptr = open(“TestNov/abc.json”,“w”)
json.dump(json1, fileptr,indent=4)
fileptr.close()
#load – reading json content from the file
fileptr = open(“TestNov/abc.json”,“r”)
print(“printing from the file:\n,content)
print(content[‘Players’][2][‘Name’])
#writing in json format on the screen
fileptr.close()

## DAY 14 Python Tutorial: Encapsulation in Python & Reading External Files

#databases – store and make data manipulation easy
# databases – Oracle, SQL Server, DB2, Postgres, SQLITE, MYSQL,
# language – SQL language -Structured Query Language- to access
# relational databases you need to learn SQL
# Roles – DBA (database administrators- manage),
# Database programmers (users)
# Database architects – they are responsible for creating the
# tables and storing them

# Operations on RDBMS – Read (reading the existing content – 80%)
# Add, Edit, Delete
# DB knowledge – Physical data v logical data
# all RDBMS systems will have same logical view
# ANSI – sets the standards for relational databases

# Rules to be followed by the database to be called itself RDBMS
# – data is stored in table and in row and column format, cell
#cell should have one information

#components: Table, Views, Triggers

#creating table to store values: list of column and their dattypes, primary key

#Relational DBMS – relationship between various column values
## 1 to 1
## 1 to Many or Many to 1
## Many to Many

## like Workbench, Sample database also install
## While installing save the root user password
## – username – root
## password – learnSQL
## servername – localhost

# Tutorial: https://dev.mysql.com/doc/refman/8.0/en/numeric-types.html

# Constraints: Primary Key, Foreign Key, Unique, Not Null, Check

Create table myemployees.departments(

DID INTEGER PRIMARY KEY,

DEPT VARCHAR(10),

DEPTCODE INTEGER,

);

INSERT INTO myemployees.departments values(1,’Sales’,109,’Sunil’);

INSERT INTO myemployees.employees VALUES(1,’Rohit Sharma’,’23456′,’rohit@rohit.com’,’1985-05-21′,21000.89,1);

INSERT INTO myemployees.employees (EID, ENAME, SALARY,DID)

VALUES(2,’Virat Kohli’,20000.89,1);

select * from myemployees.employees;

## DAY 15 Working with MYSQL

”’
Database
Exception handling

”’
”’
https://www.geeksforgeeks.org/convert-python-script-to-exe-file/

”’
import csv
fname =
input(“Enter the filename: “)

fileobj =
open(fname)
delimiter=“,”)
print(“Content on the screen: “)
for row in csv_content:

print(row)
fileobj.close()

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

”’
Converting Python program to exe:
https://www.datacamp.com/tutorial/two-simple-methods-to-convert-a-python-file-to-an-exe-file

”’

# from the tkinter library
from tkinter import *
# import filedialog module
from tkinter import filedialog
from tkinter import messagebox
import csv
# to read filename
filename1 = “”

if filename1==“”:
messagebox.showerror(
“File Process”,“Filename has not be selected”)

else:

print(“I am in Else!”)
fileobj =
open(filename1)
delimiter=“,”)

print(“Content on the screen: “)

for row in csv_content:

print(row)
fileobj.close()

# Function for opening the
# file explorer window
def browseFiles():
initialdir=“/”,

title=“Select a File”,

filetypes=((“Text files”,

“*.txt*”),
(
“all files”,

“*.*”)))

filename1 = filename

# Change label contents

label_file_explorer.configure(text=“File Opened: ” + filename)

# Create the root window
window = Tk()

# Set window title
window.title(‘Selecting the file’)

# Set window size
window.geometry(“500×500”)

# Set window background color
window.config(background=“white”)

# Create a File Explorer label
label_file_explorer = Label(window,

text=“File Explorer”,

width=100, height=4,

fg=“blue”)

button_explore = Button(window,

text=“Browse Files”,

command=browseFiles)

button_process = Button(window,

text=“Analyze the file”,

# specifying rows and columns
label_file_explorer.grid(column=1, row=1)
button_explore.grid(
column=1, row=2)
button_process.grid(
column=2, row=2)

#fname = input(“Enter the filename: “)

# Let the window wait for any events
window.mainloop()

##########  CSV File ##########
import csv
#fname = input(“Enter the filename: “)
diff_list=[]

fname1=
“D:/MyApp/B1.csv”
fname2=“D:/MyApp/B2.csv”

fileobj1 = open(fname1)
fileobj2 =
open(fname2)
delimiter=“,”)
delimiter=“,”)
print(“Content on the screen: “)

list_content1=[]
for row1 in csv_content1:
list_content1.append(row1)

list_content2=[]
for row2 in csv_content2:
list_content2.append(row2)

for row1 in list_content1:

for row2 in list_content2:

#print(“ROW 1 and ROW 2: “,row1,row2)

if row1[0]== row2[0] and row2[0]!=‘id’:
temp_list = []
temp_list.append(row1[
0])

for i in range(1,5):

if row1[i].isnumeric() and row2[i].isnumeric():
temp_list.append(
int(row1[i])-int(row2[i]))
diff_list.append(temp_list)

print(“Final list:\n,diff_list)
fileobj1.close()
fileobj2.close()

#writing to a csv file
fileobj = open(“D:/MyApp/B3.csv”,“w”,newline=“”)
csv_writer = csv.writer(fileobj,
delimiter=‘,’)
csv_writer.writerow([
“ID”,“A”,“B”,“C”,“D”])
csv_writer.writerows(diff_list)
fileobj.close()

######

####  Exception handling  #####
## 3 types of errors:
# syntax errors
# logical errors
# runtime error = exception
#print(“Hello)
print(“Sum of 2 and 3 is “,2*3)

a=
5
b=10
if b==0:

else:

print(“Division is “,a/b)

#
a = “6t”

b = 4
try:
a =
int(a)
c = a/b

except ZeroDivisionError:

print(“Divide by zero is not allowed”)
except ValueError:

print(“Numerator is not a valid number”)
except Exception:

print(“Some exception has occurred , not sure what”)
else:

print(“Value of c is”,c)

finally:

print(“I am in finally”)

# ZeroDivisionError: division by zero

## DAY 19: Tkinter and Exception handling in Python

“””
Connecting to MYSQL Database

“””
import pymysql
#cursor is database object to take commands from python to DB
curobj = conn.cursor()

table1 = ”’
Create table books(
ID Integer Primary Key,
TITLE Text,
PRICE Integer
)
”’
#curobj.execute(table1)
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(1,”Python Programming”, 390)”’
#curobj.execute(insert1)
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(2,”SQL Programming”, 290)”’
#curobj.execute(insert1)
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(3,”Java Programming”, 490)”’
#curobj.execute(insert1)
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(4,”C++ Programming”, 395)”’
#curobj.execute(insert1)
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(5,”C# Programming”, 492)”’
#curobj.execute(insert1)

up1 = ”’Update Books set title=”Java Language Programming” where ID=3”’
curobj.execute(up1)
del1 = ”’Delete from Books where ID=4”’
curobj.execute(del1)
conn.commit()
select1 = “Select * from books;”
curobj.execute(select1)
output = curobj.fetchall()
#print(“Total rows = “,output)

for rows in output:
print(rows)

curobj.close()

## LAST DAY VIDEO: Working with Database

## Database – type is RDBMS – relational database management system
#table is where data is stored
# server can have multiple databases:
#SQLITE3 free database, which comes with Python installation
# doesnt have username password, cant be accessed from outside

import sqlite3
conn = sqlite3.connect(“DECDATA.SQLITE”)
# SQLITE3 DB data types tutorial:
# https://www.sqlite.org/datatype3.html
table1 = ”’
Create table books(
ID Integer,
TITLE Text,
PRICE Integer
)
”’

#cursor is database object to take commands from python to DB
curobj = conn.cursor()
#curobj.execute(table1) – already run
“””
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(1,”Python Programming”, 390)”’
curobj.execute(insert1)
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(2,”SQL Programming”, 290)”’
curobj.execute(insert1)
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(3,”Java Programming”, 490)”’
curobj.execute(insert1)
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(4,”C++ Programming”, 395)”’
curobj.execute(insert1)
insert1 = ”’Insert into books(ID,TITLE,PRICE) values(5,”C# Programming”, 492)”’
curobj.execute(insert1)
conn.commit()
“””
“””
up1 = ”’Update Books set title=”Java Language Programming” where ID=3”’
curobj.execute(up1)
conn.commit()
“””
“””
del1 = ”’Delete from Books where ID=4”’
curobj.execute(del1)
conn.commit()
“””

select1 = “Select * from Books”
output = curobj.execute(select1)
for rows in output:
print(rows[1],rows[2])
curobj.close()