Swapnil Saurav

## Day 1 Introduction and Print()

print(‘5 + 3 =’, 5+3)

pi = 3.1 # variable
g = 9.8
# area of a circle = pi * r square

# Write a program to find area and perimeter of a rectangle by taking length and breadth as input
length = 21
perim = 2 * (length + breadth)
print(“Area of rectangle =”,area)
print(“Perimeter of rectangle =”,perim)

#Write a program to find area and perimeter of a square
side = 35
area = side * side
perim = 4 * side
print(“Area of square =”,area)
print(“Perimeter of square =”,perim)

#Find total and average of five numbers
num1 = 78
num2 = 82
num3 = 79
num4 = 91
num5 = 59
total = num1 + num2 + num3 + num4 + num5
avg = total / 5
print(“Total = “,total,”Average is”,avg)

## Day 2: Variables and examples

#Find total and average of five numbers
num1, num2, num3,num4,num5 = 78,82,79,91,59
total = num1 + num2 + num3 + num4 + num5
avg = total / 5
print(“Total = “,total,“Average is”,avg)
# find the value of 2x square -10x +30, when x = 8
x = 8
y = 2 * x * x – (10 * x) + 30 # expression
print(“Value of y =”,y)

#different types
# basic data types – they can store only one value at a time
# integer (int) – numbers without decimal values
num1 = 5
num2 = 0
num3 = –99 #<class ‘int’>
print(“1. “,type(num1)) #type(num1) – this is first to be called and then print() is called

# float (float) – decimal values
num1 = 5.0
num2 = 0.9
num3 = –99.1 #<class ‘float’>
print(“2. “,type(num1))

# string (str)
var1 = “Hello”
var2 = ‘Good Evening’
var3 = ”’Hi there”’
var4 = “””Python learning”””
print(type(var1), type(var2),type(var3),type(var4))

# boolean (bool) – True & False
var1 = True
var2 = False
print(type(var1), type(var2))
# complex (complex): complex numbers are square root of negative numbers
# square root of -25 = 5i = 5j
var1 = 5j
print(type(var1))

## Operations

#Arithematics operations (maths op)

#Relational operations

#logical operations (and/or/not)

## Access all videos from here

print(‘Hello’)
print()   #comment is for human being
#sdfsdfdsfsdfdsf
print(‘hello again hhjvjbhjhlbbuihuhuhuhu’)
print(‘5+3’)
print(5+3)
print(“4+6=”,4+6)

# y = x + 5, find y when x is 3

# 5 is constant – you cant change its value
# x, y are variables – their values can change
# y dependent variable because its value depends on x
# x is independent variable because you can assign any value to it

x = 3
y = x+ 5
print(“When X is “,x,“then Y is “,y)

# write a program to calculate area of a rectangle

l = 5
b = 8
area = l * b
print(” Length is”,l,“breadth is”,b,“and area is”,area)
# f-string format string
print(f“Length is {l} and breadth is {b} so the area is {area})

#calculate area and circumference of a circle and print the output as:
# Circle with a radius will have area of area and circumference of circumference
# arithematic
val1 , val2 = 25,20
print(val1 + val2)
print(val1 – val2)
print(val1 * val2)
print(val1 / val2)
print(val1 // val2) # integer division
print(val1 % val2) # mod – remainder
print(5 ** 3) #power

#relational operators: > < >= <= == !=
#output is always – True or False
val1, val2, val3 = 25,20,25
print(val1 > val2) #T
print(val1 > val3) #F
print(val1 >= val3) #T
print(val1 < val2) #F
print(val1 < val3) #F
print(val1 <= val3) #T
print(val1 == val2) #F
print(val1 != val3) #F
print(val1 == val3) #T

# Logical operators: input &output are bool: and , or, not
print(“Logical operators”)
print(True and True) #I did both the tasks
print(False and True)
print(True and False)
print(False and False)

print(True or True) #T
print(False or True) #T
print(True or False) #T
print(False or False) #F

print(not True)
print(not False)

r= –5
if r>0:
area = 22/7*(r**2)
print(“area of the circle is”,area)
else:
print(“Invalid data”)

num=4
if num>0:
print(“Positive”)
elif num<0:
print(“Negative”)
else:
print(“Neither positive not negative”)
# wap to check if a number is divisible by 3 or not
# wap to check if a number is odd or even
# for: when you know how many times you need to repeat something
# while:
# range(=start, < end, =increment) range(3,9,2): 3,5,7
for counter in range(3,9,2):
print(“HELLO, The counter value is”,counter)
##
for i in range(1,101): #when increment is not given, default value is 1
print(i)

#Generate even numbers from 2 to 100 (both inclusive)
n=12
for i in range(n): #when start number is not given, default value is zero
print(“* “,end=“”)
print()

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

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

”’
* * * *
* * *
* *
*
”’
for j in range(n):
for i in range(n-j):
print(“* “,end=“”)
print()

”’
* * * *
*
*
* * * *
”’
for j in range(n):
if j==0 or j==n-1:
for i in range(n):
print(“* “,end=“”)
print()
else:
for k in range(n-j-1):
print(” “,end=” “)
print(“*”)

#while
cont = “y”
while cont==“y”:
print(“Hello from While”)
cont = input(“Do you want to continue: hit y for yes anyother key for no:”)

## Video Recording

num = 10
while num >0:
print(“hello”)
num=num-1

ch=‘y’
while ch==‘y’ or ch==“Y”:
print(“I am fine”)
ch=input(“Do you want to continue (y for yes):”)

while True:
print(“How are you?”)
ch=input(“Enter n to stop:”)
if ch==“n”:
break #that will throw you out of the loop

# guessing game
num = 45

while True:
guess = int(input(“Guess the number (1-100): “))
if guess<1 or guess>100:
continue
if num==guess:
print(“Congratulations… You have guessed it correctly!”)
break
elif num<guess:
print(“Incorrect! You have guessed higher number”)
else:
print(“Incorrect! You have guessed lower number”)

print(“WELCOME TO MY LIBRARY APPLICATION”)
while True:
print(“1. Issue the Book”)
print(“2. Return the Book”)
print(“3. Add new Book to the library”)
print(“4. Remove a book from the library”)
print(“5. Exit”)
choice = input(“Enter you choice: “)
if choice==“1”:
print(“Given book has been issued!”)
elif choice==“2”:
print(“Book has been returned to the library!”)
elif choice==“3”:
print(“Added the book to the library!”)
elif choice==“4”:
print(“Removed the book from the library database!”)
elif choice==“5”:
print(“Have a good day!”)
break
else:
print(“Invalid option! Try again”)
continue `####str1 = 'HELLO'str2 = "I am fine"str3 = '''Where are you going?How long will you be here?What are you going to do?'''str4 = """I am hereI will be here for next 7 daysI am going to just relax and chill"""print(type(str1),type(str2),type(str3),type(str4))print(str1)print(str2)print(str3)print(str4)# What's you name?str5 = "What's your name?"print(str5)#He asked,"Where are you?"str6 = 'He asked,"Where are you?"'print(str6)#He asked,"What's your name?"#escape sequence  \print('''He asked,"What's your name?"''')print("He asked,\"What's your name?\"")print('nnnnn\nnn\tnn')print("\FOlder\\newfolder")# \n is used to print newline in pythonprint("\\n is used to print newline in python")# \\n will not print newline in pythonprint("\\\\n will not print newline in python")str1 = "Hello You"str2 = "There"print(str1 + str2)print(str1 *5)for i in str1:    print("Hello")#indexingprint(str1)print("last element: ",str1)print("last element: ",str1[-1])print("second element: ",str1[-8])print("ell: ",str1[1:4])print("ell: ",str1[-8:-5])print("First 3: ",str1[:3])print("First 3: ",str1[:-6])print("Last 3: ",str1[6:])print("Last 3: ",str1[-3:])#Methods - exactly same as your functions - only difference is they are linked to a classimport timestr1 = "HELLO"print(str1.replace("L","X",1))sub_str = "LL"str2 = "HELLO HOW WELL ARE YOU LL"cnt = str2.find(sub_str)print("Count = ",cnt)if cnt<0:    print("Sorry, no matching value hence removing")else:    print("Value found, now replacing")    for i in range(5):        print(". ",end="")        time.sleep(0.5)    print("\n")    print(str2.replace(sub_str,"OOOO"))out_res = str2.split("LL")print("Output Result = ",out_res)out_str = "LL".join(out_res)print(out_str)print(str2.title())print(str2.lower())print(str2.upper())str3 = 'hello how well are you ll'print(str3.islower())print(str3.isupper())num1 = input("Enter a number: ")if num1.isdigit():    num1 = int(num1)else:    print("Invaid input")ename = input("Enter your first name: ")if ename.isalpha():    print("Your name is being saved...")else:    print("Invaid name")#WAP to count of vowels in a sentencepara1 = "Work, family, and endless to-do lists can make it tough to find the time to catch up. But you'll never regret taking a break to chat with your friend, Frost reminds us. Everything else will still be there later."sum=0for l in para1:    if l=='a' or l=='A' or l=='e' or l=='E' or l=='i' or l=='I' or l=='o' or l=='O' or l=='u' or l=='3':        sum+=1print("Total vowesl = ",sum)sum=0for l in para1.lower():    if l=='a' or l=='e'  or l=='i' or l=='o' or l=='u':        sum+=1print("Total vowesl = ",sum)sum=0for l in para1.lower():    if l in 'aeiou':        sum+=1print("Total vowesl = ",sum)`
#Strings – indexing
str1 = “Hello”
print(“=>”, str1+str1+str1)

#methods in Python
print(str1.isdigit())

num1 = input(“Enter a number: “)
if num1.isdigit():
num1 = int(num1)
print(num1)
else:
print(“Sorry you have entered a invalid number”)

else:
print(“Username is not valid, enter again!”)
txt1 = “Hello how are you are you are doing”
print(“lower: “,txt1.islower()) #isupper(), istitle()
print(“title: “,txt1.title())
print(“title: “,txt1.istitle())
# islower() -> lower(), isupper() -> upper(), istitle() -> title()
print(“=> “,txt1.split())
print(“=> “,txt1.split(“o”))
txt_list1 = [‘Hello’, ‘how’, ‘are’, ‘you’, ‘doing’]
txt_list2 = [‘Hell’, ‘ h’, ‘w are y’, ‘u d’, ‘ing’]
print(“Join = “, ” “.join(txt_list1))
print(“Join = “, “o”.join(txt_list2))
print(“”,txt1.count(“are”,10,25))
print(“”,txt1.count(“hello”))
print(” “,txt1.replace(“are”,“is”)) COMPLETE THE PYTHON COURSE FROM HERE:

# List: linear ordered mutable collection
list1 = [5,6.1,“Hello”,True,[2,4,9]]

# mutable means you can edit the list
list1 = 6.9
print(“List 1 = “,list1)

# non mutables (immutable) objects cant be edited eg. String
str1 = “Hello”
#str1= “Z” #TypeError: ‘str’ object does not support item assignment
print(“You can iterate through the list:”)
for i in list1:
print(i)

list2 = [3,6,9,12]
list3 = [4,8,12,16]
print(“list2 + list3: “,list2 + list3)

print(“last member = “,list1[-1])
print(“First 4 values = “,list1[:4])
print(“Number of elements in List 1 = “,len(list1))

### Methods in List ###
list2 = [3,6,9,12]
list2.append(18)
print(“List 2 after append: “,list2)
list2.append(15)
print(“List 2 after append 2: “,list2)

# add the element at a specific position
list2.insert(1,24)
print(“List 2 after insert: “,list2)

## removing
list2.pop(2) #pop takes the index value
print(“List 2 after pop: “,list2)
list2.remove(18) #remove takes the value of the element to remove
print(“List 2 after remove: “,list2)

list4 = list2
list5 = list2.copy()
print(“1. List 2 = “,list2)
print(“1. List 4 = “,list4)
print(“1. List 5 = “,list5)
list2.append(30)
list2.append(40)
print(“2. List 2 = “,list2)
print(“2. List 4 = “,list4)
print(“2. List 5 = “,list5)

print(“10 in the list = “,list2.count(10))
list2.reverse()
print(“List after reverse = “,list2)
list2.sort() #sort in the ascending order
print(“Sorted list = “,list2)

list2.sort(reverse=True) #sort in the descending order
print(“Sorted list = “,list2)

list2.clear()
print(“List after clear = “,list2)
# Tuples – linear ordered immutable collection

t1 = (4,6,7,8)
print(type(t1))
for i in t1:
print(i)
t1 = list(t1)
t1.append(10)
t1 = tuple(t1)
# Dictionary : key:value pair

dict1 = {}
print(type(dict1))
dict1 = {3:“Sachin”,“Second”:2,True:False,“Flag”:True}
# 3 ways – keys, values, items
for k in dict1.keys(): #keys
print(“Key = “,k,” and value is”,dict1[k])
for values in dict1.values():
print(“Value is”,values)

# iterate through items:
for item in dict1.items():
print(item,“: key is”,item,“and value is”,item)

# only a dictionary can be added to a dictionary
temp = {“City”:“Mumbai”}
dict1.update(temp)
print(“Dictionary 1: “,dict1)

#dictionary – mutable [list is mutable, tuple and string – immutable]
dict1=“Tendulkar”
print(“Dictionary 1: “,dict1)

#copy
dict2 = dict1
dict3 = dict1.copy()
print(“1. Dict1 = “,dict1)
print(“1. Dict2 = “,dict2)
print(“1. Dict3 = “,dict3)
dict1.update({“Team”:“India”})
dict3.update({“Runs”: 12908})
dict2.update({“Wickets”: 432})

print(“2. Dict1 = “,dict1)
print(“2. Dict2 = “,dict2)
print(“2. Dict3 = “,dict3)

dict1.clear()
print(dict1)
##### Django Learning with Jeswanth

All videos are available here:    https://www.youtube.com/playlist?list=PLF9fJE4vTtTLnXYzr_19r1NVRWuNV892t

## BASIC INFORMATION

For Basic information like installation, software to use, history, refer this link:

#Server DB Server(Modal – SQL) Controller (Python) View (HTML, Javascript)

print(‘Hello There’);print(“How are you?”)

print(5+3);
print ( “5+3=”,5+3,“and 6*2 =”, 6*2 )

## DAY 1 Video here

# y = x+5, find the value of y when x is 4
# 5 is constant – value will remain 5
# x,y – their value can change – variables
# x independent variable, we can put any value
# y is dependent variable (on x), it can take multiple values but that depends on x

#calculate area and perimeter of a rectangle
l=50
b=85
#input values
# input – process (formula) – output (display the result)
area = l * b
perimeter = 2*(l+b)
print(“Rectangle with length”,l,“and breadth”,b,“has an area of”,area,“and perimeter of”,perimeter)

# f-string – formatting the string
print(f”Rectangle with length {l} and breadth {b} has an area of {area} and perimeter of {perimeter})

#calculate area and circumference of a circle
r = 13
area = 3.14 * r * r #pi is constant value 3.14
c = 2*3.14*r
#area and c are dependent variables
print(“Circle with radius”,r,“will have area of”,area,“and circumference of”,c)
print(f”Circle with radius {r} will have area of {area:.1f} and circumference of {c:.4f})

name,team,pos=“Virat”,“India”,“Captain”
print(f”Player’s name is {name:<10} from the team {team:^10} and represents as {pos:>15} at the event.”)
name,team,pos=“Manbgwabe”,“Zimbabwe”,“Wicket-Keeper”
print(f”Player’s name is {name:<10} from the team {team:^10} and represents as {pos:>15} at the event.”)

#numeric data types – int, float n complex
var1 = 50 #int – integer, numbers without decimal point
print(type(var1)) #type() – will give the type of the data that is stored
var1 = 50.0 #float
print(type(var1))
var1 = 5j # complex
# square root of -1 : i (in python we say j)
print(type(var1))
print(5j * 5j)
#text type – string (str)
”’ This is a
multi line
comment in python”’
var1 =‘5’
print(type(var1)) #<class ‘str’>
var1 = True #bool – True or False
print(type(var1))

## DAY 2 Video Here

# 5 types: int, float, bool, str,complex
#arithematic
val1, val2 = 20,3
print(val1 – val2) #subtracting
print(val1 * val2) #multiplying
print(val1 / val2) #dividing – gives a float value
print(val1 // val2) # integer division – gives integer value
print(val1 ** val2) #power
print(val1 % val2) #mod – remainder

# 20/3 = 6 2/3
#conditional / relational operators: > < >= <= == !=
# output: True or False
val1, val2,val3 = 20,3,20
print(val1 > val2) #True
print(val1 >= val3) #T
print(val1 > val3) # F
print(val1 < val3) #
print(val1 <= val3) #T
print(val1 == val3)
print(val1 != val3)

# logical operator: and or not
#input is boolean and output is also boolean
print(False and False)
print(False and True)
print(True and False)
print(True and True)
print(“===============”)

print(False or False)
print(False or True)
print(True or False)
print(True or True)
print(not True)
print(not False)
print(“========”)
val1, val2,val3 = 20,3,20
print(val1 >= val3 and val1 > val3 or val1 < val3 and val1 <= val3 or val1 == val3)
# T
num= 0
if num>0:
print(“Positive”)
elif num<0:
print(“Negative”)
else:
pass

print(“Thank you”)

####
avg =75
# if avg>=50: You have passed!
if avg>=50:
print(“You’ve passed!”)
if avg >= 70:
if avg>=90:
print(“You win special award”)
elif avg >= 85:
elif avg >= 60:
else:
else:
print(“You’ve not passed!”)
#LOOPS – repeating a block of code
## FOR Loop: used when you know how many times to execute a code
## WHILE Loop: beforehand you are not sure how many times but repeat based on some condition

## DAY 3 VIDEO

# for: when you know how many times you need to repeat something
# while:
# range(=start, < end, =increment) range(3,9,2): 3,5,7
for counter in range(3,9,2):
print(“HELLO, The counter value is”,counter)
##
for i in range(1,101): #when increment is not given, default value is 1
print(i)

#Generate even numbers from 2 to 100 (both inclusive)
n=12
for i in range(n): #when start number is not given, default value is zero
print(“* “,end=“”)
print()

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

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

”’
* * * *
* * *
* *
*
”’
for j in range(n):
for i in range(n-j):
print(“* “,end=“”)
print()

”’
* * * *
*
*
* * * *
”’
for j in range(n):
if j==0 or j==n-1:
for i in range(n):
print(“* “,end=“”)
print()
else:
for k in range(n-j-1):
print(” “,end=” “)
print(“*”)

#while
cont = “y”
while cont==“y”:
print(“Hello from While”)
cont = input(“Do you want to continue: hit y for yes anyother key for no:”)

## DAY 4 Video

##### DS-Weekend-022023
print(“Hello”,5+4,end=” “)
print(“6+3=”,6+3,end=\n)
print(“How are you?”,end=\n)

print(“This line \n for new line”) ;
# integer – int
a=5;
print(type(a))
#string – str

#boolean – bool

#float

#complex

a = 3+5j
print(a*a) # -16 +30j

#####
#1. WAP to find area and perimeter of a rectangle
# input: what you give to the computer
# process: what is the ask from the computer
# output: what you get back in return
# process: area = length * breadth and perimeter as 2*(length + breadth)
# output: print the answers (area and perimeter) on to the screen

length = 25
print(“Area = “,area)
print(“Perimeter = “,perimeter)

length , breadth,name = 25, 15,“Sachin” #implicit conversion
print(“Area = “,area,“and Perimeter = “,perimeter)

#unpack

#input() – to get input value from the user
length = input(“Enter the length value = “) #implicit into str
length = int(length) #explicit conversion to int
print(“Data type of length is “,type(length))
# f string – format string
print(f”A rectangle with length {length} and breadth {breadth} has an area of {area} and perimeter of {perimeter})
# f-string expanded to float and str
total_cost = 100
num_units = 33
print(f”Total cost came to Rs {total_cost} for {num_units} pens so the cost of each pen is Rs {total_cost/num_units:.2f})
print(f”{3.69:.1f})

player = “Virat”
position = “captain”
country = “India”
print(f”Player {player:.<12} is {position:X^15} of {country:->12} team”)

player = “Mbanwaweba”
position = “wicket-keeper”
country = “Zimbabwe”
print(f”Player {player:<12} is {position:^15} of {country:>12} team”)
#Arithematic operations
val1 = 7
val2 = 3
print(val1 – val2) # subtract
print(val1 * val2) # multiply
print(val1 / val2) # division
print(val1 % val2) # remainder
print(val1 // val2) # integer division
print(val1 ** val2) # power
print(int(10 ** (1/2)))

#binary value
print(bin(10)) #0b1010
print(hex(0o12)) #0xa
print(oct(10)) #0o12
print(int(0b1010))

# binary operators: << >> & |
#Shift
print(10 <<3) # 1010
print(int(0b101000))
print(10 >> 2)
#Relational or conditional: > < <= >= == !=
val1 = 10
val2 = 20
val3 = 10
print(val1 > val2) # is val1 greater than val2? – False
print(val1 >= val2) # is val1 greater than or equal to val2? – False
print(val1 >= val3) # is val1 greater than or equal to val3? – True
print(val1 > val3) # is val1 greater than val3? – False
print(val1 < val3) #False
print(val1 <= val3) #True
print(“val1 == val3: “,val1 == val3)
print(val1 != val3)
print(“A40” > “90”)

# Logical operator: and or not
#input and output both are bool values
# and – both have to True to result into True (otherwise its False)
print(“T and T: “, True and True)
print(“T and F: “, True and False)

# or (+)
print(“F or T : “, False or True)
# 2+5*3 = ?
val1 = 10
val2 = 20
val3 = 10
print(val1 <= val3 or val1 > val3 and val1 > val2) # = ?
# T

print(bin(15))
print(“15 & 10 = “, 15&10)
print(“15 | 10 = “, 15|10)

#print(f”15 | 10 = 15{|}10″, )

print(f”val1 <= val3 or val1 > val3 and val1 > val2 = {val1 <= val3 or val1 > val3 and val1 > val2})
#print(f”True {and} False”)
l = int(input(“Enter the value of length: “))
b = int(input(“Enter the value of breadth: “))

#conditional statements checks the value
if l>0 and b>0:
area = l * b
perimeter = 2*(l+b)
print(f”Rectangle with length {l} and breadth {b} has area of {area} and perimeter of {perimeter})

#another set of if condition
if l>0 and b>0:
area = l * b
perimeter = 2*(l+b)
print(f”Rectangle with length {l} and breadth {b} has area of {area} and perimeter of {perimeter})
else:
print(“Sides of rectangle doesnt look valid”)

#
# Check is a number is positive and if positive chck if divisible by 5

value = 50
if value > 0:
print(f”{value} is positive”,end=” “)
if value %5==0:
print(“and its divisible by 5”)
elif value <0:
print(f”{value} is negative”)
else:
print(f”{value} is neither positive nor negative”)

marks1, marks2,marks3,marks4,marks5 = 96, 96,96,96,95

#assign grade on the basis on avg marks:
# avg>90: A, 75-90: B, 60-75: C, 50-60:D, <50: E
avg = (marks1 + marks2+marks3+marks4+marks5)/5
print(“Average: “,avg)
if avg>=90:
#print(“Result: You have Passed”)
elif avg>=75:
#print(“Result: Passed”)
elif avg>=60:
elif avg>=50:
else:
print(“Result: Failed”)

#
print(“===================”)
flag = 0 #didnt win dean’s award
if avg>=50:
#print(“Result: You’ve passed!”)
if avg >= 90:
if avg >=95:
flag=1
elif avg >= 75:
elif avg >= 60:
else:
print(“Result: You’ve passed!”)
else:
print(“Result: Sorry You’ve failed!”)
if flag==1:
print(“You win special dean’s award”)

## checking the greater number between 2 values
val1,val2 = 40,20

if val1 > val2:
print(f”{val1} > {val2})
elif val1 < val2:
print(f”{val2} > {val1})
else:
print(f”{val2} = {val1})

#########
val1,val2 , val3 = 50, 90,20

if val1 > val2:
#print(f”{val1} >= {val2}”)
if val1 > val3:
if val3 > val2:
print(f”{val1} >= {val3} >= {val2})
else:
print(f”{val1} >= {val2} >= {val3})
else:
print(f”{val3} >= {val1} >= {val2})
else:
#print(f”{val2} >= {val1}”)
if val2>val3:
if val1 > val3:
print(f”{val2} >= {val1} >= {val3})
else:
print(f”{val2} >= {val3} >= {val1})
else:
print(f”{val3} >= {val2} >= {val1})

#LOOPS- to execute block of code multiple times

#range(a,b,c): a=starting (=), b= ending value (<), c=increment
#range(5,30,5): 5,10,15,20,25
#range(a,b) c is default = 1
#range(4,10): 4,5,6,7,8,9
#range(b), a is default = 0, c is default = 1
#range(4): 0,1,2,3
#FOR Loop – when we know how many times to run

print(“i” in “India”) #True
print(“A” in “India”) #False because A is not in India

for counter in range(5,10,3):
print(“In For Loop:”,counter)

for counter in “India”:
print(“In For Loop:”,counter)

#Run a loop 5 times:
for i in range(5):
print(“i = “,i)

#a way of printing even numbers upto 20
for i in range(0,21,2):
print(i,end=“, “)
print()

for i in range(1,101):
if i %5==0:
print(i,end=“, “)
print()

# WHILE Loop –
ch=“n”
#extry controlled loop
while ch==“y”: #while will execute if the condition is True
print(“How are you?”)
ch=input(“Enter y to continue, anyother key to stop: “)

#exit controlled
while True:
print(“I am fine”)
ch = input(“Enter n to stop, anyother key to stop: “)
if ch==“n”:
break
###
”’
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
”’

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()

”’
* * * * *
* * * *
* * *
* *
*
”’
num=10
for j in range(num):
for i in range(num-j):
print(“*”,end=” “)
print()

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

#Multiplication table
for j in range(1,11):
for i in range(1,11):
print(f”{i:<2} * {j:<2} = {j*i:<2},end=” “)
print()

#match and case
ch = input(“Enter you favorite programming language: “)
match ch:
case “Python”:
print(“You are on Data Scientist track”)
case “Java”:
print(“You are on Mobile App Developer track”)
case “Javascript”:
print(“You are on Web Developer track”)

#Program to take input marks and find avg
ch=“y”
sum=0
counter=0
while ch==“y”:
marks = int(input(“Enter marks: “))
counter+=1
sum+=marks # sum=sum+marks
ch=input(“Do you have more marks to add? y for yes: “)
avg = sum/counter
print(f”Total marks= {sum} and Average marks ={avg})

#
# guessing number game – human v computer
import random
num = random.randint(1,100) #both start and end is inclusive
attempt = 0
while True:
val = int(input(“Guess the number (1-100): “))
if val<1 or val>100:
print(“Invalid number!”)
continue #take you to the beginning of the loop
attempt+=1
if val==num:
print(f”You have guessed it correctly in {attempt} attempts”)
break #throw you out of the loop
elif val <num:
else:

##
# guessing number game – computer v computer
import random
num = random.randint(1,100) #both start and end is inclusive
attempt = 0
start,end=1,100
while True:
val = random.randint(start,end) #int(input(“Guess the number (1-100): “))
if val<1 or val>100:
print(“Invalid number!”)
continue #take you to the beginning of the loop
attempt+=1
if val==num:
print(f”You have guessed it correctly in {attempt} attempts”)
break #throw you out of the loop
elif val <num:
start = val + 1 #guess a higher number
else:
end = val – 1 #guess a lower number

### Using IF Condition in one single line – one line condition
# Ternary operator: condition logic should not be more than 1 line

val1, val2 = 30,40

var1 = val1 if val1 > val2 else val2
print(“1. Higher number is “,var1)

var1 = “val1 is higher” if val1 > val2 else “val2 is higher”
print(“2. Message: “,var1)

### One line for loop
#square the values greater than 5 and cube the values for others
for i in range(10):
if i >5:
val = i**2
else:
val = i**3
print(val)

#Above code can be implemented in one line:
print(“Using one line loop and condition:”)
for i in range(10): print(i**2) if i>5 else print(i**3) ## Assignment Programs

Exercise 1: Write a program in Python to display the Factorial of a number.

Exercise 2: Write a Python program to find those numbers which are divisible by 7 and multiples of 5, between 1500 and 2700 (both included).

Exercise 3: Write a Python program to reverse a number.

Exercise 4: Write a program to print n natural number in descending order using a while loop.

Exercise 5: Write a program to display the first 7 multiples of 7.

Exercise 6: Write a Python program to convert temperatures to and from Celsius and Fahrenheit.

[ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ]

Expected Output :

60°C is 140 in Fahrenheit

45°F is 7 in Celsius

Exercise 7: Write a Python program that iterates the integers from 1 to 50. For multiples of three print “Fizz” instead of the number and for multiples of five print “Buzz”. For numbers that are multiples of three and five, print “FizzBuzz”.

Sample Output :

fizzbuzz

1

2

fizz

4

buzz

Exercise 8: Write a Python program to print the alphabet pattern ‘A’.

Expected Output:

***

*   *

*   *

*****

*   *

*   *

*   *

Exercise 9: Write a Python program to print the alphabet pattern ‘G’.

Expected Output:

***

*   *

*

* ***

*   *

*   *

***

#String
name = “Sachin” \
“Cricket God”
name1 = ‘Virat’
name2 = ”’Rohit
Captain of Team India”’
name4=“””Dhoni
won the world
cup for India
in multiple formats of the
game”””

print(name)
print(name2)
print(name4)

#substring- subset of data – indexing
name = “Sachin Tendulkar”
print(name)
print(name)
print(“SCI => “,name+name+name)
print(“First 3 characters: “,name[0:3], name[:3]) #nothing on left on : means start from zero
print(“chin => “,name[2:6])
print(“kar =>> “, name[13:16])
#len()
print(“Total characters in name is”,len(name))
print(name, name[len(name)-1], name[-1])
print(“First character using backward indexing: “,name[-16], name[-len(name)])

print(“kar using backward indexing=>> “, name[-3:]) #when left black on the right means go upto end

fname = “Sachin”
age = 49
print(“First name of the player is “+fname)
print(“Age = “+str(age))

for i in range(5):
print(“* “*(5-i))

#Data structures
# list, tuple, dictionary, sets

print(“Print all characters: “,name,name[:])

# Strings are immutable: TypeError: ‘str’ object does not support item assignment
val = “HELLO”
val = “hELLO”

for i in txt:
print(“* “*(5– txt.index(i)))

## is…() – return either True or False
txt = “highway route number. I AM driving there. since one month”
print(“txt.isupper: “,txt.isupper())
print(“txt.islower: “,txt.islower())
print(“Alphabet & Numeric”,txt.isalnum())
print(“Alphabet & Numeric”,txt.isalpha())
print(“Alphabet & Numeric”,txt.isdigit())

print(txt.upper())
print(txt.lower())
print(txt.title())
print(txt.capitalize())

# split()
print(txt.split(‘o’))
out = [‘highway’, ‘route’, ‘number.’, ‘I’, ‘AM’, ‘driving’, ‘there.’, ‘since’, ‘one’, ‘month’]
print(“====”)
out2 = ” “.join(out)
print(out2)

txt = “I am driving on highway route on number fifteen.”
print(txt.lower().count(“i”))
start_pos=0
for i in range(txt.lower().count(“i”)):
print(txt.lower().index(“i”,start_pos),end=“, “)
start_pos=txt.lower().index(“i”,start_pos) + 1
print()

print(txt.replace(“on”,“over”,1))
print(txt)
#strings are immutable

#LIST
l1 = [2,3,5.5,True,“Hello”,[4,8,12]]
print(len(l1))

print(type(l1))
print(type(l1))
print(type(l1[-1]))

print(l1[-2].upper())
l2 = [False,5,115]
l3 = l1 + l2
print(l3*3)

#lists are mutable
l2 = “How are you?”
print(l2)

for i in l2:
print(i,end=“, “)
print(\n\n### Methods”)
### Methods
l1 = [2,4,6,8,10,2,14]
print(l1.index(2,2))
print(l1.count(2))
print(“1. Current list = “,l1)
print(l1.pop(2)) #removes index element
print(“2. Current List = “,l1)
print(l1.remove(14)) #removes value element
print(“3. Current List = “,l1)
l1.append(21) #adds at the end of the list
print(“4. Current List = “,l1)
l1.insert(3,31) #takes position and the value
print(“5. Current List = “,l1)
#below creating 2 new lists based on l1 values
l2 = l1 #deep copy
l3 = l1.copy() #shallow copy
print(“1. L1 = “,l1)
print(“1. L2 = “,l2)
print(“1. L3 = “,l3)
l1.append(42)
l2.append(52)
l3.append(62)
print(“2. L1 = “,l1)
print(“2. L2 = “,l2)
print(“2. L3 = “,l3)
l1.extend(l3)
print(l1)
l1.reverse()
print(l1)
l1.sort() #increasing order
print(l1)
l1.sort(reverse=True) #decreasing order
print(l1)

#definition: List is an ordered linear mutable collection
subject_list = [‘Maths’,‘Science’,‘English’,‘Social Science’,‘German’]
marks_list = []
sum=0
for i in range(5):
#marks = int(input(“Enter marks in Subject “+str(i+1)+”: “))
marks = int(input(“Enter marks in Subject ” + subject_list[i] + “: “))
sum+=marks
marks_list.append(marks)
print(“Marks obtained in each subject = “,marks_list,“and total marks = “,sum)

sum=0
for i in marks_list:
sum+=i
print(“Total marks = “,sum)

#Reduce, Map, Filter => later after functions
# TUPLE:
#definition: Tuple is an ordered linear immutable collection
t1 = ()
t1 = (5,)
t1 = (5,4)
t1 = (5,6,7,8.0,“9”)
print(type(t1))
#tuples are converted to list and vice-versa
t1 = list(t1)
t1.append(45)
t1 = tuple(t1)
#tuples are faster than list for reading

#packing
t1 = (3,30,“Hello”) #packing
#unpacking
a,b,c = t1
print(a,b,c)

print((2,3,99) > (3,1)) #checks one by one member untill it finds the greater value  #List – linear ordered mutable collection
# dictionary – ordered collections – key:value pair

dict1 = {}
print(type(dict1))
dict1 = {“name”:“Sachin”,“city”:“Mumbai”,“Runs”:12345,“name”:“Tendulkar”}
print(dict1)
print(dict1[‘name’])
dict2 = {(“Team IPL”,“Team Ranji”):“Mumbai Indians”}
dict1.update(dict2)
print(dict1)

for i in dict1.keys():
print(i, dict1[i])
print(“Iterating through values:”)
for i in dict1.values():
print(i)
print(“Iterating through items (key,value):”)
for i,j in dict1.items():
print(i,j)
for i in dict1.items():
print(list(i))

print(“Printing the values: “)
print(“Keys :”,dict1.keys())
print(“Values:”,dict1.values())
print(“Items:”,dict1.items())

dict1.pop(‘Runs’)
print(“After pop: “,dict1)
dict2 = dict1 #deep copy
dict3 = dict1.copy() # shallow copy
t_dict = {“Country”:“India”}
dict1.update(t_dict)
print(“Printing all 3 Dictionaries: “)
print(“Dict1: “,dict1)
print(“Dict2: “,dict2)
print(“Dict3: “,dict3)
#dict1[‘name’]=”Tendulkar”
t_dict = {“name”:“Tendulkar”}
dict1.update(t_dict)
for i in range(2):
print(“Dict1 before popitem: “,dict1)
dict1.popitem()
print(“Dict1 after popitem: “,dict1)

”’
Write a program to input Roll no. and marks of 3 students in 3 subjects
{101:[], 102:[]}

”’
dict_marks={}

for i in range(3):
t_dict = {}
roll=int(input(“Enter the Roll number:”))
t_list=[]
for j in range(3):
marks=int(input(“Enter the marks for Roll no.”+str(roll)+” in Subject “+str(j+1)+” :”))
t_list.append(marks)
t_dict = {roll:t_list}
dict_marks.update(t_dict)
print(“Final data:”,dict_marks)

”’
Assignment program:
from the below dictionary find the topper for each subject:
{100: [55, 66, 78], 102: [90, 87, 54], 105: [67, 76, 87]}

e.g. Highest in Subject 1: 102 with 90 marks
Highest in Subject 2: 102 with 87 marks
Highest in Subject 3: 105 with 87 marks
”’
#Example 2:
master_dict = {}

for k in range(2):
for i in t_dict.keys():
j=input(“Enter the client’s “+i+” :”)
t_dict[i] = j
master_dict.update(t_dict)
print(“Master Dictionary information: \n,master_dict)

##################################################
# SETS
set1 = {}
print(type(set1))
set1 = {“Apple”,“Banana”,“Mango”,“Grapes”,“Guava”}
print(type(set1))
set2 = {“Mango”,“Grapes”,“Guava”,“Apple”,“Banana”}

set1 = {1,2,3,4,5,6}
set2 = {1,3,5,7,9}
print(“Union:”)
print(set1 | set2)
print(set1.union(set2))
print(“Intersection:”)
print(set1 & set2)
print(set1.intersection(set2))
print(“Minus – difference”)
print(set1 – set2)
print(set2.difference(set1)) #set2 – set1
print(“Symmetric Difference”)
print(set1 ^ set2)
print(set1.symmetric_difference(set2))
print(“Set1 before pop:”,set1)
set1.pop()
print(“Set1 after pop:”,set1)

list1 = [1,2,3,4,1,2,3,1,2,1]
list1 =list(set(list1))
print(type(list1))
print(list1)
#################### FUNCTIONS ##############################
def myquestions():
”’this is a sample function to demonstrate how function works
it doesnt take any parameter nor does it return anything
-written on 22nd april”’
print(“how are you?”)
print(“Where are you going?”)

def mycalc1(a,b,c):
print(“MY CALC 1”)
print(f”A,B and C values are {a},{b},{c})
total = a+b+c
print(total)

def mycalc2(a,b=0,c=9):
print(“MY CALC 2”)
print(f”A,B and C values are {a},{b},{c})
total = a+b+c
print(total)

def myfunc1(a,*b,**c):
print(“A = “,a)
print(“B = “,b)
print(“C = “,c)

myquestions()
print(myquestions.__doc__)
print(“Doc for print”)
print(input.__doc__)
#doc – first line of code inside the function, must be multiline comment
print(\n\n\n)
mycalc1(10,50,90) #required positional arguments
mycalc2(3,7,19) #calling default arguments
mycalc1(c=1,a=7,b=3) #use keywords to avoid positional

print(“Calling variable length arguments:”)
myfunc1(10,1,2,3,4,5,6,7,8,9,0,4,5,66,44,333,33, name=“Sachin”,age=43,runs=19890)

def myfun1(a,b,c):
#
global x
print(“X = “,x)
x = 5
print(“X = “, x)

x=50
myfun1(5,10,15)
print(“in Main x = “,x)
###
def isPrime(n):
check= True
for i in range(2,n//2+1):
if n%i==0:
check=False
break
return check

check = isPrime(51)
if check:
print(“51 number is prime”)
else:
print(“51 number is not prime”)

#generate list of prime number between 1000 and 2000

for i in range(1000,2001):
out =isPrime(i)
if out:
print(i) def myfunc1():
“””This is a sample function to see the working of a function”””
print(“How are you?”)
print(“Where do you live?”)

def myfunc2(a,b,c): # required positional arguments
print(f”Values of a,b and c are {a},{b} and {c} respectively”)
total = a+b+c
print(“Total is “,total)

def myfunc3(a,b=0,c=0): # a & b required positional and c is positional not required (default)
print(f”Values of a,b and c are {a},{b} and {c} respectively”)
total = a+b+c
print(“Total is “,total)

def isPrime(n):
”’isPrime is a function that takes a parameter n and
check and prints if its a prime number of not”’
prime = True
for i in range(2,n//2 +1):
if n%i==0:
prime=False
break
return prime

if __name__ ==“__main__”:
myfunc1()
print(“————-“)
print(myfunc1.__doc__)
# doc string: a multi line string and first line in the function
print(print.__doc__)
print(int.__doc__)

myfunc2(5, 10, 15) # required positional
print(“Calling My Func3 below:”)
myfunc3(10, 20)
myfunc3(10, 20, 30)

n = 11
out = isPrime(n)
if out:
print(n, “is a prime number”)
else:
print(n, “is not a prime number”)

# I want to print a list of all the values that are prime between 100 and 500
print(“Printing list of prime numbers from 100 to 500:”)
for k in range(100, 501):
if isPrime(k):
print(k)

# We are talking about non-positional (or KEYWORD arguments)
print(“Working on keyword arguments:”)

myfunc2(b=45, c=50, a=70) # for keyword – use same arguments that are already there

# Module:

P5.py file:

from p4 import myfunc2
print(“Hello : “,n)
if n==0:
return 100

# 5! = 5 * 4!

def myfacto(n):
if n==1:
return 1
return (n * myfacto(n-1))

###### decorators

def outer():
print(“Line one of outer”)
def inner():
print(“Line 1 of inner”)
print(“Line two of outer”)
inner()
print(“Line three of outer”)

def myouter11():
print(“This is line 1 from myouter 11”)
def myouter22():
print(“This is line 1 from myouter 22”)
def myouter33():
print(“This is line 1 from myouter 33”)
def myouter2(var1):
print(“This is line 1 from myouter 2”)
var1()
print(“This is line 2 from myouter 2”)

if __name__ ==‘__main__’:
out = myfacto(50)
print(“Factorial of 4 is”, out)
outer()
myouter2(myouter33)

P6.py:

#import p5 as SuperFunctions
from p5 import mytask, myfacto, myfunc2
from MyPack1 import modul1
modul1.myfunc1()

myfacto(10)
# one line for loop
print(“Option 1”)
for i in range(5):
print(“Hello”)
print(“Option 2”)
for i in range(5): print(“Hello”)
print(“Option 3”)
list1 = [2,4,6,8,10]
for i in list1: print(i)
print(“Option 4”)
prod=1
for i in range(1,10): prod*=i
print(prod)
print(“Option 5”)
mylist1 = [i for i in range(1,10)]
print(“Mylist1 = “,mylist1)

# one line if condition
print(“Condition Option 1”)
num=-5
if num>0:
print(“Positive”)
else:
print(“Not positive”)
output = “Positive” if num>0 else “Not Positive”
print(“Option 1 output = “,output)

print(“Condition Option 1 with Loops”)
### calculate cube of values between 1 and 9
print([num**3 for num in range(1,10)])
### calculate cube of values between 1 and 9 if the value is odd
print([num**3 for num in range(1,10) if num%2==1])
# one line function
print(“one line function Option 1”)
myfun1 = lambda x,y:print(“Total = “,x+y)
myfun1(10,20)
print(“one line function Option 2”)
friends=[“Rohit”,“Rahul”,“Surya”,“Kohli”]
batting = lambda team: [print(“Now batting:”,x) for x in team]
batting(friends)

#MAPS, FILTER & REDUCE
input = [2000,3000,100,200,5000,6000,3000,900,600,500,230,8000]
# all the three concepts works on list – input is a list and output depends upon the task
## 1. map – if there is a single logic (formula) that you need to apply on entire list values
#example: convert these feet into metres: divide by 3.1
some_func = lambda num:num/3.1
out = list(map(some_func,input))
print(“Output = “,out)

# Filter: if there is a single logic (condition) based on whicch you select subset
## subset of values are created when the condition returns True
out = list(filter(lambda x: (x//100)>=10,input))
print(“Filtered values are: “,out)

# Reduce: takes entire data in a list and reduces them to just 1 single value based on the given formula
from functools import reduce
print(“Sum of all the values are: “,reduce(lambda a,b:a+b, input))

## PROJECT 1: Working with Dictionary

## Project 1: Create a menu option for billing
## Dictionary: {Item_code: [“Item_Description”,price]}
## create bills for each individual: {item_code: [quantity, price, total_cost]}
from datetime import date, datetime, timedelta, timezone
import time
start = time.time()
for i in range(1000000):
out = i**3+500*i**2+9
time.sleep(1)
end = time.time()

print(“Total time taken by the program to run: “,end-start)

from datetime import datetime
currenttime= datetime.now()
print(“Current time: “,currenttime)
print(“Date: “,currenttime.strftime(“%y-%m-%d”))
print(“Get: “,currenttime.year, currenttime.day, currenttime.minute)
print(“out: “,currenttime.today())
print(“Weekday: “,currenttime.weekday())

from datetime import timedelta,datetime
print(“Yesterday: “,currenttime-timedelta(days=1))
print(“Next week: “,currenttime+timedelta(days=7))
class BookMagazine:
__publisher = “Eka Publishers”
def __init__(self, title,page):
print(“Publisher is: “,BookMagazine.__publisher)
self.title=title
self.pages=page
class Books(BookMagazine):
total_books = 0 # class level variable – all objects and class will return same value
#object level variables will be inside object methods
def __init__(self, title,author,page):
BookMagazine.__init__(self,title, page)
self.author=author
Books.total_books +=1

def display_book(self):
print(“Dummy Function: Book Created”)
print(“Title = “, self.title)
if self.author==“”:
print(“There is no author name declared”)
else:
print(“Author = “, self.author)
print(“Pages = “, self.pages)

@classmethod
def display_count(cls):
print(“Total book count = “,cls.total_books)
##
b1=Books(“Python Programming”,“Swapnil Saurav”,330)
print(“B1 Display”)
b1.display_book()

b2=Books(“Data Science”,“Swapnil Saurav”,550)
print(“B2 Display”)
b2.display_book()

b3=Books(“Data Visualization”,“Swapnil Saurav”,250)
b3.display_book()
print(b1.total_books)

print(Books.total_books)

#Today’s assignment; Using Class and objects perform addition, subtraction, multiplication,
# and division. Each of these should have unique functions. init should take in 2 input values
# from the user
# Implement atleast one of these: class variable and method, object variable and method

class Magazines(BookMagazine):
def __init__(self,title,pages,genre):
BookMagazine.__init__(self,title,pages)
self.genre = genre

class Library:
def lib_fun1(self):
print(“Printing from Library class:”)
#print(“Publishers = “,BookMagazine.__publisher) #throws error as private members cant be accessed
print(“Total Books = “,Books.total_books)

#print(Books.__publisher) #throws error as private members cant be accessed
#print(b2.)
l1= Library()
l1.lib_fun1()
#Access Modifiers:
## private: only the members of the same class can access
## protected: (one _ variable name): _name, _pub => only derived class can be called
### concept of protected is there but practically its not yet updated

## public: any member can call members of any class
class Books:
total_books=0
def __init__(self,title,author):
self.title = title
self.author = author
Books.total_books +=1
def display_data(self):
print(f”Title = {self.title} and Author = {self.author})

b1 = Books(“Python Programming”,“Saurav”)
print(type(b1))
b1.display_data()
b2 = Books(“Machine Learning”,“Saurav”)
b2.display_data()
l1 = []
print(type(l1))

##############
#Errors
# Syntax errors – when you dont follow Python rules
# print 5

#logical errors – wrong logic.. a + b = 4 *2

# Exception errors – runtime errors
num1=0
try:
num1 = int(input(“Enter a number: “))
#10/0
except (ValueError, ZeroDivisionError):
print(“You have not entered a valid number, hence exiting…”)
except Exception:
print(“Some error has occured, please retry!”)
else:
print(num1) # ValueError
finally:
print(“Error or No error I will be called”)
#10/0: ZeroDivisionError
num1=0
while True:
try:
num1 = int(input(“Enter a number: “))
break
except (ValueError, ZeroDivisionError):
print(“You have not entered a valid number, hence exiting…”)
except Exception:
print(“Some error has occured, please retry!”)
else:
print(num1) # ValueError
finally:
print(“Error or No error I will be called”)

# Assertion Error
def print_data(num):
#perform this only when num >100
assert (num>100), “Value entered is too small to process”
return num**num
try:
out = print_data(100)
except AssertionError:
print(“Give larger value and run again”)
else:
print(“Output is “,out)

#########

### create my own exception
class TooSmallValue(Exception):
def __init__(self,value=0,min=100):
self.value = value
self.min = min

#driving code
value = int(input(“Enter a value >100: “))
try:
if value <=100:
raise TooSmallValue
except TooSmallValue:
print(“TooSmallValue: Give larger value and run again”)
else:
print(“Output is “,value*value)

######### WORKING WITH OPERATING SYSTEMS

import os
os_name = os.name
print(os.name)
if os_name==‘nt’:
print(“You are using a Windows machine”)
elif os_name==‘posix’:
print(“This is Mac or Linux or Unix machine”)
else:
print(“not sure which OS you are using”)

## Some OS specific command
#os.rename(“infy.py”,”infy_apr.py”)
#os.mkdir(“TEST”)
from pathlib import Path
import os

path_loc = Path(“C:/Users/HP/PycharmProjects/pythonProject/”)
for p in path_loc.iterdir():
print(p, ” : Is it a directory: “, p.is_dir())

# Text file processing
fileobj=open(“file1.txt”,“a+”) # read(r), write (w), append (a): r+ w+ a+
print(“Entire content:”)
print(content)
fileobj.seek(5) #move to first character
print(“First 10 characters:”)
# readline will read maximum one line at a time that too current
fileobj.seek(0)
print(“Line: \n,line)
print(lines)
fileobj.seek(0)
print(lines)
else:

if fileobj.writable():
lines = [‘Twinkle Twinkle Little Star\n,‘How I wonder\n,
‘What you are\n,‘Up Above the World\n]
fileobj.writelines(lines)
fileobj.close()

######### CSV Files
import csv

fileobj = open(“D:/datasets/tcs_stocks.csv”) # default mode is r (read)
print(list(csv_file))
fileobj.seek(0)
for i in csv_file:
for j in i[:2]:
print(j, end=” “)
print()

fileobj.close()

# create a csv file
row1 = [‘Sachin’,‘Mumbai’,222]
row3 = [‘Rahul’,‘Bangalore’,333]
import csv
fileobj = open(“sample1.csv”,‘w’,newline=)
row_writer = csv.writer(fileobj,delimiter=‘|’)
row_writer.writerow(row1)
row_writer.writerow(row2)
row_writer.writerow(row3)
fileobj.close()

###### JSON #############
import json
fileoj = open(“json1.json”,“r”)
#print to check if we got the content or not – this is not how to
#display the json content
print(type(content))
#we will use json dumps to display on to the screen
print(json.dumps(content, indent=4, sort_keys=True))
fileoj.close()

fileoj = open(“json2.json”,“w”)
content1 = ‘{“Name”:”Virat”,”Game”:”Cricket”}’
print(type(content1))
print(type(content1))
print(json.dumps(content1, indent=4, sort_keys=True))
json.dump(obj=content1,fp=fileoj, indent=4)
fileoj.close()

############ DATABASE ################

# structured v unstructured
# Name, Age, Country, Runs, Wickets

## Library Application
# Table 1: Books
## Columns: BookID (INTEGER), BookTitle (TEXT), Price (FLOAT), Copies (INTEGER)

# Table 2: Members
#Columns: MemberID (INTEGER), Name (TEXT), Email (TEXT), Phone (TEXT), Address (TEXT)

#Relationship:
# one to one:
# one to many / many to one:
# many to many:

# Table 3: BOOKSMEMBERS
# columns: TID (INTEGER), BOOKID(INTEGER) , MID(INTEGER),
# ISSUEDATE (DATE), RETURNDATE (DATE)

# OLTP – Online Transaction Processing (normal ) – Reading + (Editing done in bulk)
# OLAP – Online Analytical Processing (Analytics) – Reading

# CRUD : Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE)

# Roles in DBMS:
## Database Design (ER diagram, create tables) – SQL
## Application Developers: SQL – CRUD #### Working with Databases #########
”’
# Constraints: Keys (Primary Key, Foreign Key), NOT NULL, UNIQUE, CHECK, DEFAULT

Table 1: Publisher
Create Table Publisher(
PUBID int Primary Key,
Name varchar(25));

INSERT INTO Publisher Values (101, ‘Hyderabad’,’Eka Publishers);
INSERT INTO Publisher Values (102, ‘Mumbai’,’Best Publishers);

Table 2: Books:

Create Table Books(
BookID int Primary Key,
Author varchar(25) NOT NULL,
Title varchar(25) NOT NULL,
Price float(7,2),
Available bool Default 1,
PubID int,
CHECK(Price>=0.0),
Foreign Key (PubID) references Publisher(PubID)
);

INSERT INTO Books (BookID, Author, Title, PubID) Values (101,’Swapnil’,’Python Programming’,101);

INSERT INTO Books (BookID, Author, Title, PubID) Values (102,’Saurav’,’Machine Learning’,101);

Table 3: Member
Create Table Member(
MEM_ID Int Primary key,
Memb_date Date,
Memb_Type varchar(1),
Name varchar(30),
Expiry_date date);

INSERT INTO MEMBER(MEM_ID, Name) Values(101,’%s’)
INSERT INTO MEMBER(MEM_ID, Name) Values(102,’%s’)
INSERT INTO MEMBER(MEM_ID, Name) Values(103,’%s’)

Table 4: BooksMember

Create table BooksMember(
BMID Int Primary Key,
MEMID int Foreign Key References MEMBER(MEMID),
BOOKID int Foreign Key References BOOKS(BOOKID),
BORROW_DATE Date,
RETURN_DATE Date,
);

”’
import pymysql
cursor = db_connect.cursor()
#cursor.execute(‘Drop table Publisher;’)
tab1 = ”’
Create Table Publisher(
PUBID int Primary Key,
Name varchar(25));
”’
#cursor.execute(tab1)
tab2 = ”’
Create Table Books(
BookID int Primary Key,
Author varchar(25) NOT NULL,
Title varchar(25) NOT NULL,
Price float(7,2),
Available bool Default 1,
PubID int,
CHECK(Price>=0.0),
Foreign Key (PubID) references Publisher(PubID)
);
”’
#cursor.execute(tab2)

tab3 = ”’
Create Table Member(
MEM_ID Int Primary key,
Memb_date Date,
Memb_Type varchar(1),
Name varchar(30),
Expiry_date date);
”’
#cursor.execute(tab3)
tab4 = ”’
Create table BooksMember(
BMID Int Primary Key,
BORROW_DATE Date,
RETURN_DATE Date,
MEM_ID int,
BOOKID int,
Foreign Key (MEM_ID) References MEMBER (MEM_ID),
Foreign Key (BOOKID) References BOOKS (BOOKID));
”’
#cursor.execute(tab4)

########### CRUD Create (Insert), Read (Select), Update, Delete ###
## Peforming Create – using Insert
list_insert = [“INSERT INTO Publisher Values (101, ‘Hyderabad’,’Eka Publishers’);”,
“INSERT INTO Publisher Values (102, ‘Mumbai’,’Best Publishers’);”,
“INSERT INTO Books (BookID, Author, Title, PubID) Values (101,’Swapnil’,’Python Programming’,101);”,
“INSERT INTO Books (BookID, Author, Title, PubID) Values (102,’Saurav’,’Machine Learning’,101);”]
list_insert = []
for statement in list_insert:
cursor.execute(statement)
db_connect.commit() # to save the changes

# Insert by dynamic query

#Remove the multi line comment to practice:
”’
name1 = input(“Enter the Member 1 name: “)
insert1 = “INSERT INTO MEMBER(MEM_ID, Name) Values(101,’%s’)”%(name1)
cursor.execute(insert1)
name2 = input(“Enter the Member 2 name: “)
insert2 = “INSERT INTO MEMBER(MEM_ID, Name) Values(102,’%s’)”%(name2)
cursor.execute(insert2)

name3 = input(“Enter the Member 3 name: “)
insert3 = “INSERT INTO MEMBER(MEM_ID, Name) Values(‘%d’,’%s’)”%(103,name3)
cursor.execute(insert3)
db_connect.commit()
”’
## Update existing value in Member table
update1 = “Update Member Set Name=’Sachin Tendulkar’ where mem_id=101”
cursor.execute(update1)
## Delete existing member from Member table
delete1 = “Delete from Member where mem_id=102”
cursor.execute(delete1)
db_connect.commit()
select1 = “Select * from Member”
cursor.execute(select1)
results = cursor.fetchall()
for r in results:
print(r)
db_connect.close()

”’
https://livesql.oracle.com/

create an account and start practicing
”’

— Reading all the rows and columns

select * from HR.Employees;

— All the rows but given columns only

Select Employee_ID, FIRST_NAME, EMAIL from HR.Employees;

— Restricted columns and restricted rows

Select Employee_ID, FIRST_NAME, EMAIL from HR.Employees where Employee_ID =120;

select first_name||’ has a salary of \$’||  salary “Salary Information” , email from hr.employees order by email;

select first_name||’ has a salary of \$’||  salary “Salary Information” , email, HIRE_DATE from hr.employees order by HIRE_DATE, email desc;

select first_name, last_name, email, salary from hr.employees where salary > 10000  and salary <18000;

select first_name, last_name, email, salary from hr.employees where salary between 10000 and 18000;

select first_name, last_name, email, salary from hr.employees where salary in (17000, 11000, 13500);

select count(*) from hr.employees

select avg(salary) from hr.employees

select * from HR.Employees;

select * from hr.departments;

select first_name, last_name, email, to_char(hire_date, ‘Month DD, YYYY’), round(months_between(sysdate, hire_date)) Tenure_in_months from hr.employees;

select * from dual;

select 3+3 from HR.Employees where rownum<2;

select 3+3, abs(-80), to_date(‘May 14, 2023 08:01 P.M.’, ‘Month DD, YYYY HH:MI P.M.’) from dual

select Decode(3+5,8,’CORRECT’,’INCORRECT’)  from dual;

— Aggregate functions

select JOB_ID, count(*), round(avg(salary)), round(sum(salary)) TOTAL_SALARY from hr.employees group by JOB_ID having count(*)>=5;

— JOINING TABLES

select FIRST_NAME , LAST_NAME, t1.DEPARTMENT_ID, t2.DEPARTMENT_ID, Department_name, HIRE_DATE from HR.Employees t1, hr.departments t2 where t1.department_id = t2.department_ID;

— SUB QUERY

select * from HR.Employees where Employee_ID in (select employee_id from hr.employees);

select * from HR.Employees where Employee_ID = (select employee_id from hr.employees where rownum < 2);

— SET OPERATIONS

select * from HR.Employees where salary <11000

INTERSECT

select * from HR.Employees where salary >20000

import numpy as np
x = range(16)
print(type(x))
x = np.reshape(x,(8,2))
print(type(x))
print(x)
print(“Y:”)
y = [[3,4,5],[2,1,2],[9,0,1],[2,2,2]]
y = np.array(y)
print(y)
print(y[2,0])
print(y[-2,-3])

print(y[1:3,1:])
z = [[3,4,1],[2,3,2],[2,7,1],[2,9,2]]
z = np.array(z)
print(“=======================”)
print(z)
print(y)
print(y + z)

print(y – z)
print(np.subtract(y,z))

print(y * z)
print(np.multiply(y,z))

print(y /z)
print(np.divide(y,z))

y = [[3,4,5,3],[2,1,2,2],[9,0,1,1],[2,2,2,4]] # 4 * 4
y = np.array(y)
z = [[3,4,1],[2,3,2],[2,7,1],[2,9,2]] # 4 * 3
z = np.array(z)
print(y @ z) #matrix multiplication
print(np.matmul(y,z))

”’
x + y = 35
2x + 3y = 90
Find x and y ?
”’
# coefficient
coeff = np.array([[1,1],[2,3]])
#variable matrix
solution = np.array([,])
## coeff * variable = solution
# variable = inv(coeff) * solution
det_coeff = np.linalg.det(coeff)
print(“Determinant of Coefficient matrix = “,det_coeff)
if det_coeff !=0:
variable = np.linalg.inv(coeff) @ solution
print(“Solution is: x = “,int(variable[0,0]), “and y = “,int(variable[1,0]))

import pandas as pd

y = [[3,4,5,3],[2,1,2,2],[9,0,1,1],[2,2,2,4]]
y1 = np.array(y)
y2 = pd.DataFrame(y)
print(y1)
print(y2)
print(“Y2: \n,y2.loc[0:2,1:3])
y2 = pd.DataFrame(y,columns=[“January”,“February”,“March”,“April”])
print(y2)
y2 = pd.DataFrame(y,columns=[“January”,“February”,“March”,“April”],
index=[“Banana”,“Apple”,“Guava”,“Mango”])
print(y2)
print(“Y2: \n,y2.loc[[“Guava”,“Mango”],[“January”,“February”,“March”]])
# loc, iloc

## Reference Book- Numpy, Pandas and Projects

data = [[“January”,1500,1900],[“February”,1900,1800],[“March”,1500,1800],[“April”,1000,1500],[“May”, 2300,2500]]
import pandas as pd
data_df = pd.DataFrame(data, columns=[“Month”,“Runs Scored”,“Runs Given Away”])
print(data_df)
print(data_df[“Runs Scored”].mean())
print(data_df[“Runs Given Away”].sum())
print(data_df[data_df[‘Month’]==“March”])
print(data_df[data_df[‘Month’].isin([“January”,“April”,“May”])])
print(data_df.iloc)
print(data_df.loc[[0,2,4],[“Month”,“Runs Given Away”]])

print(device_df.shape)
print(usage_df.shape)
new_df = pd.merge(device_df, usage_df,on=“use_id”) #how=inner
print(new_df)

new_df = pd.merge(device_df, usage_df,on=“use_id”, how=“left”) #how=inner
print(new_df)
new_df = pd.merge(device_df, usage_df,on=“use_id”, how=“right”) #how=inner
print(new_df)
new_df = pd.merge(device_df, usage_df,on=“use_id”, how=“outer”) #how=inner
print(new_df)
# 159+81+113 = 353

## CLASS NOTES HERE (BELOW CODE)

# Univariate: Histogram, Bar chart,

# Bivariate: Scatter

import pandas as pd
print(data.shape)
print(data.dtypes)

import matplotlib.pyplot as plt
import seaborn as sns
data_30 = data.columns[:30]
#print(data_30)
color_list=[“#00FF00”,“#FF0000”]
sns.heatmap(data[data_30].isnull(), cmap=sns.color_palette(color_list))
plt.show()
import numpy as np
”’
for i in data.columns:
missing_cnt = np.mean(data[i].isnull())
print(f”{i} has {missing_cnt*100}% of missing values”)
”’
for i in data.columns:
missing_cnt = np.mean(data[i].isnull())
if missing_cnt >0.8:
print(f”{i} has {missing_cnt*100}% of missing values”)

## Company has more than 94% missing data – so lets drop it
# axis = 0 – row & axis = 1 – column
data = data.drop([‘company’], axis=1) # column company will be dropped
print(“Shape after dropping company: “,data.shape)
for i in data.columns:
#check for row missing
missing = data[i].isnull()
num_missing = np.sum(missing)
if num_missing > 0:
data[f’{i}_ismissing’] = missing
missing_cnt = np.mean(data[i].isnull())
if missing_cnt >0.8:
print(f”{i} has {missing_cnt*100}% of missing values”) #company is not there now
print(“Shape after adding _ismissing columns: “,data.shape)
# create a new column which will store the missing number of values for each row
is_missing_col = [col for col in data.columns if “ismissing” in col]
data[“num_missing_cnt”] = data[is_missing_col].sum(axis=1)
print(data[“num_missing_cnt”])
# selecting rows with more thab 12 missing values
index_missing_col = data[data[‘num_missing_cnt’]>12].index
data = data.drop(index_missing_col, axis=0)
print(“Shape after removing missing rows: “,data.shape)

# find the missing values:
cols_num = data.select_dtypes(include=[np.number])
all_num_cols = cols_num.columns.values
for i in all_num_cols: #list of columns which are numeric
missing_cnt = np.mean(data[i].isnull())
if missing_cnt >0.00:
#print(f”{i} has {missing_cnt*100}% of missing values”)
med = data[i].median()
data[i] = data[i].fillna(med)

”’
children has 2.0498257606219004% of missing values – FLOAT
babies has 11.311318858061922% of missing values – FLOAT
agent has 13.687005763302507% of missing values – FLOAT

meal has 11.467129071170085% of missing values – CAT
country has 0.40879238707947996% of missing values – CAT
deposit_type has 8.232810615199035% of missing values – CAT

”’

#handle categorical values
data[‘agent’] = pd.Categorical(data.agent)
mode = data[‘agent’].describe()[‘top’]
data[‘agent’] = data[‘agent’].fillna(mode)

data[‘meal’] = pd.Categorical(data.agent)
mode = data[‘meal’].describe()[‘top’]
data[‘meal’] = data[‘meal’].fillna(mode)

data[‘country’] = pd.Categorical(data.agent)
mode = data[‘country’].describe()[‘top’]
data[‘country’] = data[‘country’].fillna(mode)

data[‘deposit_type’] = pd.Categorical(data.agent)
mode = data[‘deposit_type’].describe()[‘top’]
data[‘deposit_type’] = data[‘deposit_type’].fillna(mode)

print(“Final check for missing values:”)
for i in all_num_cols: #list of columns which are numeric
missing_cnt = np.mean(data[i].isnull())
if missing_cnt >0.00:
print(f”{i} has {missing_cnt*100}% of missing values”)

## ADVANCED PYTHON LIBRARY FOR PLOTTING

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

url = “https://www.hubertiming.com/results/2017GPTR10K”
from urllib.request import urlopen
html_code = urlopen(url)

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_code,“lxml”)
print(soup.title)
all_a = soup.find_all(‘a’) # returns as a list of all values
print(all_a)

import re
rows = soup.find_all(‘tr’)
list_rows = []
for row in rows:
row_td = row.find_all(‘td’)
row_td = str(row_td)
#row_td = BeautifulSoup(row_td,”lxml”).get_text()
#print(row_td)
pattern = re.compile(<.*?>)
row_td = (re.sub(pattern,“”,row_td))
list_rows.append(row_td)

#Data clearning
list_rows = list_rows[5:] #removing not required rows
# 2. convert into dataframe
data_df = pd.DataFrame(list_rows)

# 3. split into different columns
data_df = data_df.str.split(‘,’,expand=True)
print(data_df)

”’
<tr>
<td> – data
”’
main_df = pd.concat(main_df)
print(“=============\n\n)
main_df = main_df.rename(columns=main_df.iloc)
main_df = main_df.drop(main_df.index)
main_df = main_df.dropna(axis=0, how=“any”)
#remove [ from first col and ] from last column
main_df.rename(columns={‘[Place’ : ‘Place’}, inplace=True)
main_df.rename(columns={‘ Team]’ : ‘Team’}, inplace=True)
main_df[‘Place’] = main_df[‘Place’].str.strip(‘[‘)
main_df[‘Team’] = main_df[‘Team’].str.strip(‘]’)
print(main_df)
print(main_df.info())

## Above code available here (Click to access)

import numpy as np
import pandas as pd
url=“D:\\datasets\\OnlineRetail\\order_reviews.csv”
print(list(reviews_df.columns))

## 1. convert entire text to lowercase
## 2. compatibility decomposition
## 3. convert into utf8
## 4. removing accent
## 5. sentences into words
## 6. remove stop words

import unicodedata
import nltk

## Function to perform steps 1 to 6
def basic_nlp_analysis(text):
text = text.lower()
#Below code will perform:
## 2. compatibility decomposition
## 3. convert into utf8
## 4. removing accent
text = unicodedata.normalize(‘NFKD’,text).encode(‘ascii’, errors=‘ignore’).decode(‘utf-8’)
## 5. sentences into words
words = nltk.tokenize.word_tokenize(text)

## 6. remove stop words
STOP_WORDS = set(w for w in nltk.corpus.stopwords.words(‘portuguese’))
words = tuple (t for t in words if t not in STOP_WORDS and t.isalpha())

return words

commented_reviews = reviews_df[reviews_df[‘review_comment_message’].notnull()].copy()
print(commented_reviews[‘review_comment_message’])
# will apply basic nlp operations on the column
commented_reviews[‘review_comment_words’] = commented_reviews[‘review_comment_message’].apply(basic_nlp_analysis)

print(commented_reviews[‘review_comment_words’])

## About Probability and Probability distribution - Book

INFERENTIAL STATS:

Predicting for the population from the sample data

Led by probability – an event you are interested in / total possible outcome

1/6

Discrete and Continuous

Bayes theorem – p (probability of success) & q (probability of failure)

q = 1-p

Probability (1 time event) and Probability distribution (repetition)

Toss coin one after another: Sample Space: TT, HH, TH, HT = 2/4

Toss 2 coins at the same time: Sample Space: TT, HH, TH

## REFER HYPOTHESIS TESTING HERE

##### Weekend DS Batch April 2023

`#1. Python programming-  Python interpreter (python.org)#2. Data analytics - desriptive stats#3. Python visualization#4. Database & SQL (OLTP)#5. Inferential stats#6. warehousing (OLAP)#7. machine learning (using Python)#8.Visualization using Power BI  ====>#9. Machine learning using R programming#10. Intro Tableau# each topic will have a project#assignments - they will not have code# go through job description of the jobs you are interested in and put them in an excel# you X against topics you know#how to build your resume/profile#################### 1. Software to install: Python interpreter from Python.org# 2. IDE - Integrated Development Environment##  pycharm, vs code, jupyter, colab (online)print("Hello Everyone",end=". ");  #this is comment which will not be executed by Python.print("wiefsisdkjnsjdosidviosdosdiv");print("Hello","How are you?","I am fine");print("5+4=",5+4,"another equation: 6+4=",6+4)# f-string (format string)print(f"5+4={5+4} another equation: 10/3={10/3:.2f}",end="")#data type-what kind of value is it? - integer(int), float, complex,string (str), boolean(bool)print()var1=5  #<class 'int'>print(type(var1))var1="HEllo"print(type(var1)) #<class 'str'>var1=5.0  #<class 'float'>print(type(var1))var1=5j  #<class 'complex'>print(type(var1))print(var1 * var1)#boolvar1 = True  #Falseprint(type(var1))var1= "true"`
`print("HELLO")# 1. INSTALLATION - getting your computer ready# a. you can practice online at Google Colab (colab.reaserch.google.com)# b. install all software on your machine -## i. install Python : python.org and download the version of your choice## ii. you can program on Python but its very easy to do## iii. Another software to make it user friendly - IDE## integrated development environment - you can practice##  eg Pycharm (jetbrains.com), VS Code , Notebooks like Jupyter, etc`
print(‘Hello’,end=“\n”);print(“Good Morning”, end=“.     \n3.”);  # end has invisible new line
print(“Hope you are doing well”,end=“\n”);
print(‘Hello’,end=“\n”)
print(“Good Morning”, end=“.     \n3.”);  # end has invisible new line
print(“Hope you are doing well”,end=“\n”)
`print("HELLO", end="\n")print("Good Morning")# variables - we variable to store data and use it again and again when we want itvar1 = 5# single line comment# integer means - numbers without decimal part- includes _ve , +ve & zero# type() - it gives the data type of the variableprint(type(var1))  # integer - int# basic data types in Python- integer, float, string, boolean & complex# basic = single valueprint(var1)var1 = 5.0 #floatprint(type(var1))var1 = 5+2jprint(type(var1))print(var1 * var1)  # 25 -4 +20jprint(2j * 2j)var1 = "7890"print(type(var1))  # str -> stringvar2 = '5.4t'print(var2)print(type(var2))#bool -> boolean : True / Falsevar1 = Truevar2 = Falseprint(type(var1))### use these values/ variables# Arithematic operations - input as numbers and output are also numbers# +  - * /   //   **  %(modulo)var1 = 14var2 = 5print(f"{var1} + {var2} : ",var1 + var2)print("{var1} + {var2} : ",var1 + var2)print(f"var1 + var2 : ",var1 + var2)print(f"{var1} - {var2} : ",var1 - var2)print(f"{var1} * {var2} : ",var1 * var2)print(f"{var1} / {var2} : ",var1 / var2)print(f"{var1} // {var2} : ",var1 // var2) #integer divisionprint(f"{var1} % {var2} : ",var1 % var2) #remainder from divisionprint(f"{var1} ** {var2} : ",var1 ** var2) #power- var1 to the power var2print(f"{var1} ** {var2} : ",var1 * var1* var1*var1*var1)# round() - round it off to the nearest integer value###  round(5.1) = 5 , round(5.6) = 6# floor() - rounds it off to the lowest integer value###  floor(5.1) = 5 , floor(5.6) = 5  => similar to integer division# ceil() - rounds it off to the higher integer value###  ceil(5.1) = 6 , ceil(5.6) = 6`
`# types of variables (data types) - Basic data types - they can store only one value at a timevar1 = 5  # integer - intvar1 = 5.0 # floatvar1 = 5j #complexvar1 = "5" #string - strvar1 = False #boolean - bool# arithematic operators:  + - *  /   //  %(mod)  ** (power)# Comparison operators: numeric as input and output is boolnum1, num2 = 10,20print(num1, num2)#  >   >=    <=   <   ==  !=print("num1==10: ",num1==10) # is num1 equal to 10 ?print("num1!=10: ",num1!=10) # is num1 not equal to 10?print(num1 > num2)print(num1 < num2)print(num1 >= 10)print(num1 <= num2)# Logical operators#input values and output values - are all boolean#operations =  and  or  notprint("not True: ",not True)print("not False: ",not False)# and -> both values have to be True for it to be True else its Falseprint(True and False)#tell: I will do this work and that work#actual: I did only this work#did I meet my committment ? - NO# or - both values have to be False to be False otherwise its always True#tell: I will do this work or that work#actual: I did bothprint("OR = ", True or False)num1,num2 = 10,20print("==> ",num1==10 and num1!=10 or num1 > num2  and num1 < num2 or num1 >= 10 or num1 <= num2)# Trueradius = 4pi = 3.14area_of_circle = pi * radius**2circumference = 2 * pi * radiusprint("Area of a circle with radius",radius,"is",area_of_circle,"square unit and circumference is",circumference,"unit")# f - string is for formattingprint(f"Area of a circle with radius {radius} is {area_of_circle} square unit and circumference is {circumference} unit")# Assignment -# 1. WAP to find area and perimeter for a square# 2. WAP to find area and perimeter for a rectangle# for both the programs, display output is complete message as we have done above with circle.# to check given number is an odd or even ?# 5 - odd, 6 - evennum1 = 5if num1 % 2==0:    print("EVEN Number")else:    print("ODD Number")` num=0
if num>0:
print(“Number is positive”)

if num>0:
print(“Number is positive”)
else:
print(“Number is not positive”)
num=11
if num>0:
print(“Number is positive”)
if num%2==0:
print(“Its even”)
else:
print(“Its odd”)
elif num<0:
print(“Number is negative”)
else:
print(“Neither positive nor negative”)

#WAP to check if a number is Odd or Even

#WAP to assign grade based on marks obtained
avg = 85
#avg>=85: A, 70-85: B, 60-70: C, 50 to 60: D, <50- E

#LOOPS are used to repeat multiple times
#FOR – when u know exactly how many times to repeat
# range(start(=),stop(<),increment(=)) = range(5,25,5): 5,10,15,20
for counter in range(5,25,5):
print(counter)

# range(start(=),stop(<)) = range(5,10) default increment = 1: 5,6,7,8,9
for counter in range(5,10):
print(counter)

# range(stop(<)) = range(4) DEFAULT start= 0,default increment = 1: 0,1,2,3
for counter in range(4):
print(counter)

#WHILE – till a condition is true
count = 10
while count<=15:
print(“Value = “,count)
count=count+1
for v in range(1,11):
for r in range(1,11):
print(f”{r:<2} * {v:<2} = {v*r:<2},end=” “)
print()

”’
*
* *
* * *
* * * *
* * * * *
”’
for i in range(5):
for j in range(4-i):
print(” “,end=“”)
for k in range(i+1):
print(“*”,end=” “)
print()

############# Assignment
”’
* * * * *
* * * *
* * *
* *
*
”’
#Guessing game: Computer v Human
import random
#guess = 25
guess = random.randint(1,100)
counter = 0
while True:
num = int(input(“Guess the number between 1 and 100: “))
if num<1 or num>100:
print(“Invalid guess, try again!”)
continue
counter+=1
if num==guess:
print(f”Congratulations! You got it right in {counter} attemmpts.”)
break #throw you out of the loop
elif num<guess:
print(“Incorrect, You’re guess is lower!”)
else:
print(“Incorrect, You’re guess is higher!”)

#Guessing game: Computer v Computer
import random
#guess = 25
guess = random.randint(1,100)
counter = 0
start,end=1,100
while True:
#num = int(input(“Guess the number between 1 and 100: “))
num = random.randint(start,end)
if num<1 or num>100:
print(“Invalid guess, try again!”)
continue
counter+=1
if num==guess:
print(f”Congratulations! You got it right in {counter} attemmpts.”)
break #throw you out of the loop
elif num<guess:
print(“Incorrect, You’re guess is lower!”)
start=num+1
else:
print(“Incorrect, You’re guess is higher!”)
end=num-1

###############
txt = “Hello”
# indexing
print(txt) #counting in Python starts from zero
print(txt)
print(txt[-1]) `#variables are used to store some valuesvar1 = 50var2 = 100print(var1 + var2)var1 = 500var2 = 100print(var1 + var2)#Basic#datatypes: str, int, float, bool, complexvar1 = "HELLO" # str - you have the value in quoationprint(type(var1))var1 = 100  #without any decimal part - integer(int)print(type(var1))var1 = 100.0  #float valueprint(type(var1))var1 = True #bool - Falseprint(type(var1))var1 = 5j  #complex (python)=imaginary (maths)var2 = var1 * var1 #implicit conversion into complex since var1 is also complexprint(var2)print(type(var1))#var1 = 100var2 = 3.5var3 = var1 + var2 #implicit conversion into float since var2 is a floatprint()str1 = "55"str1 = int(str1) #explicit conversion#int(), str(), float(), bool(), complex()var1 = 0;var1 = bool(var1);print(var1);  #False - boolvar1 = "";var1 = bool(var1);print(var1) ; #False - boollen = float(input("Enter length of the rectangle: "))breadth = float(input("Enter breadth of the rectangle: "))area = len * breadthprint("Area of the rectangle is ",area)print(f"Rectangle with length = {len} and breadth = {breadth} has an area of {area:.1f}")player = "Imbababonbeta"country = "Zimbabwe"position = "wicket-keeper"print(f"Player {player:<16} plays for {country:^10} and is {position:>15} of the team")player = "Rohit"country = "India"position = "captain"print(f"Player {player:<16} plays for {country:^10} and is {position:>15} of the team")#Player Imbababonbeta plays for Zimbabwe and is wicket-keeper of the team#Player Rohit         plays for  India    and is       captain       of the team`
`##########  OPERATORS### ARITHMETIC OPERATORS: + - * /## input values have to be numeric (int, float, complex)var1 = 50var2 = 20print(var1 + var2)print(var1 - var2)print(var1 * var2)print(var1 / var2)#  ** power, 5 ** 4 =>  5 * 5 * 5 * 5print(var1 ** var2)  # 50 to the power of 20# how to find square root of 21 ?print(21 ** 0.5)  #4.58257569495584#cube root of 21 =print(21 ** (1/3))#  //  - integer divisionprint(10 / 3)print("Integer Division = ",10 // 3)# % Modulo - remainder#20 / 3 = 6 + 2/3print(20 % 3)print(50 % 30) # 20 is remainder# Comparison operators: compare the values (bigger/smaller)# input as numeric and output is BOOLvar1 = 15var2 = 25print(var1 > var2)  #false` `#Arithematic operations: + - * / , **, // and % (modulo)## input as numbers and output was numbers#Comparison operators: input are the numbers / output - bool#  >   >=   <   <=   ==  !=val1 = 30val2 = 40val3 = 30print(val1 > val2) #is leftside val greater than rightside value?print(val1 > val3) #Falseprint(val1 >= val3) #is val1 greater than or equal to? - Trueprint(val1 < val2)  #print(val1 <= val3) #print(val1 == val3)  # == is for asking question, are they equal?print(val1 == val2)  #Falseprint(val1 != val3)  #Falseprint(val1 != val2) #True#bool operators - Logical operators : Input and Output- bool#Prediction 1: Sachin and Laxman are going to do this job - F#Prediction 2: Sachin or Laxman are going to do this job - T#Actual: Sachin and Rahul did the job#AND - even one False will make output False#OR - even one TRUE will make output True#NOT - oppositeval1 = 30val2 = 40val3 = 30print("==>: ",val1 > val2 or val1 > val3 and val1 >= val3 or      val1 < val2 and val1 <= val3 or val1 == val3 and val1 == val2 or      val1 != val3 or val1 != val2)#T#membership operator - inprint(5 in [2,4,5,6,8])#bitwise operator - works by converting the numbers to boolean# binary equivalent of 33 ?print(bin(33))   #0b100001print(int(0b101111011111))# and (&) or (|)  >> (right shift)  << (left shift)print(22 & 33)  #0print(33 & 22)   #0print(bin(33), bin(22))## 33 = 100001## 22 = 010110##  (&) 000000##  (|) 110111print(int(0b110111))   #55print(33 | 22)  # 55##print(55 >>2)# 55 = 110111 >> 1 = 11011 >> 1 = 1101print(int(0b1101))  #13print(55 << 2)  # 110111 << 1 = 1101110 << 1 = 11011100#### if - checking conditionsval1 = 30if val1 > 0:    print("Value is positive")    print("Positive Positive Positive")print("Thank you for using my program")# 300 pts## ? 300print("You win")print("You lose")print("Tied")`
`#TUPLE - immutable version of Liststr1 = "hello"str2 = 'Good evening' \       'How are you?'str3 = '''Hello therehope you are doing goodwe shall meet soon'''str4 = """I am finehow are you"""print(str2)print(str3)print(type(str1))#functions (global) v methods (belong to a class)str1 = "hello"print(str1.islower())print(str1.isupper())#isdigit()val1 = input("Enter length of the rectangle: ")if val1.isdigit():    val1 = int(val1)    print(val1)else:    print("Sorry, this is not a valid number")name1 = "Sachin Tendulkar"print(name1.isalpha())txt1 = "hello@123"print(txt1.isalnum())###str1 = "HellOOO how are YOU?"print(str1.lower())#### Build a game - guessing number  ####import randomnum = 55attempt = 0low,high = 1,100while True:    #guess = int(input("Enter the number: "))    guess = random.randint(low, high)    attempt+=1    if guess ==num:        print(f"You got it in {attempt} attempts!")        break    elif guess > num:        print(f"Hint: Your value {guess} is higher")        high=guess-1    else:        print(f"Hint: Your value {guess} is lower")        low=guess+1str1 = "Hello"print(str1[-1] , str1[len(str1)-1])print(str1)print("Length = ",len(str1))# range(a,b,c) - a=initial value, b = ending value, c=increment# range(2,14,3) - 2,5,8,11print(str1[0:4], str1[:4])print(str1[-5:-1], str1[:-1])# lloprint(str1[2:5], str1[2:])print(str1[-3:])vowel_count = 0str1 = "This is a Sample STATEMENT to test"for i in str1:    #print("Hello: ",i)    if i in 'aeiouAEOIU':        vowel_count+=1print(f"Total vowels in '{str1}' is {vowel_count}")# strings are immutablestr1 = "Hello"str1=str1+'E'+str1[2:]print("New str1 = ", str1)str2 = "This is a Sample STATEMENT to test"str3="This,is,a,sample,text2,work,on,it"output1 = str2.split()output1 = str3.split(',')print(output1)print(str2)print("Index: ",str2.index('i',3,len(str2)))str4='abcd abc ab a'#find all indices of btot = str4.count('ab')print("Total bs = ",tot)srt = 0for i in range(3):    print(str4.index('ab',srt))    srt=str4.index('ab',srt)+1`  `### LIST: linear ordered mutable collectionl1 = []print(type(l1))l1=[3,"Hello",False,5.0, [2,4,6]]l1.append(45)`
`#collection - stores multiple values with single variable name#List, Tuple, Dictionary and Set#List - linear collectionl1 = [5,"Hello",False,[4,8,12]]print(type(l1))   #<class 'list'>#accessing (similar to strings)print(l1)print(type(l1))print(l1[-1])l2 = [5.6,"Good Evening"]print(l1+l2)print(l2 * 3)l3=[-1]*10print(l3)for i in l1:    print(i)for i in range(len(l1)):    print(l1[i])l4=[]#read the value from the user and if its number only then add to this listval1 = input("Enter a number: ")if val1.isdigit():    l4.append(int(val1))print("After first step, L4 looks like: ",l4)l5 = []l5.append(100)l5.append(200)l5.insert(1,300)  # takes- pos, valuel5.insert(1,400)print("After addition: ",l5)l5.pop(2) #input as position(index)l5.remove(200) #takes values as inputprint(l5)### Stack & Queue #### Stack - LIFO data structurestack=[]while True:    print("Enter your options: ")    print("1. Display Your Stack")    print("2. Add a member to the stack")    print("3. Remove a member from the stack")    print("4. Exit")    ch=input("Choice : ")    if ch=="1":        print("Content of the stack is:\n",stack)    elif ch=="2":        pass    elif ch=="3":        pass    elif ch=="4":        break    else:        print("Sorry I dont understand you, try again!")# Queue: First element added is the first one to go - FIFO (First In First Out)l6 = [100,200,300,400,100,200,300,100,200,100]print(l6.index(100))  #elementprint(l6.index(100, 2))  # element with start positionprint(l6.index(100, 5,8))  # element with start and end posprint("count = ",l6.count(200))#Deep and Shallow copyl7 = l6 #Deep copy - 2 names for same set of valuesl8 = l6.copy() #creates a duplicate copy -print("1. L6 = ",l6)print("1. L7 = ",l7)print("1. L8 = ",l8)l6.append(500)l7.append(600)l8.append(700)print("2. L6 = ",l6)print("2. L7 = ",l7)print("2. L8 = ",l8)# list is linear ordered mutable collectionl6 = 110  #edit the value unlike stringprint(l6)l7 = [2,4,6,8,10]print(l6+l7) #l6 and l7 retains original valuesl6.extend(l7) #l6 will get l7 valuesprint(l6)print("Before Reverse: ",l6)l6.reverse()print("After Reverse: ",l6)l6.sort()print("After Sort: ",l6)l6.sort(reverse=True)print("After Reverse Sort: ",l6)l6.clear()print("Last: ",l6)str1 = "HELLO HOW ARE YOU"print(str1.split())print(str1)  #didnt change as it is immutablel6.append(66)print(l6) #existing list got changed as it is mutable`
`#Sequential searchlist1 = [12,14,8,6,10,20,4,10,16,18,2]num = 10count_num=0count_index = []for i in range(len(list1)):    if list1[i]==num:        count_num+=1        count_index.append(i)print(f"Number of values = {count_num} and indices are: {count_index}")# Binary Searchlist1 = [12,14,8,6,10,20,4,10,16,18,2]list1.sort()num = 22first = 0last = len(list1)-1isFound = Falsewhile True:    mid = (first+last) // 2    if list1[mid] ==num:        isFound = True        break    elif list1[mid] <num:        first = mid+1    else:        last = mid-1    if first> last:        breakif isFound:    print("Number is in the list")else:    print("Number is not in the list")Q_LIST = ["What is 1+3? (a) 4 (b) 8 (c) 2 (d) 10",          "What is 4+3? (a) 5 (b) 7 (c) 12 (d) 16",          "What is 4*3? (a) 6 (b) 8 (c) 12 (d) 16"]A_LIST = ["A","B","C"]import randomq_no = random.randint(0,2)print("Let's play the Quiz!")print(Q_LIST[q_no])inp=input("Your answer please (select a/b/c/d) : ")if inp.upper() ==A_LIST[q_no]:    print("Congratulations! You win")else:    print("Sorry, thats not right")### input: 29  3  2023  output: 29th March 2023months= ["January","February","March","April","May","June","July","August",         "September","October","November","December"]date_ending = ['st','nd','rd']+17*['th']+['st','nd','rd'] + 7*['th']+['st']month_val = 3print(months[3-1])date = 21print(str(date)+date_ending[date-1])`
`#Tuple - linear ordered immutable collectiont1 = ()print("type 1 = ",type(t1), len(t1))t1 = (1,)print("type 1 = ",type(t1), len(t1))t1 = (1,2,3,4,1,2,3,1,2,1)  #packcingprint("type 1 = ",type(t1), len(t1))print("4th member - ", t1)print("2s = ",t1.count(2))print("Position of 3 = ",t1.index(3))t2 = (2,4,6,8)a,b,c,d = t2  #unpackingprint(c,d,b,a)# you can convert tuple to list and list to tuplet2 = list(t2)t2 = tuple(t2)# Tuple like String, is immutable#advantage is - working with Tuples is faster than reading through a list#####  DICTIONARY# Dictionary - mutable collection of key-value paird1 = {}print(type(d1))d1 = {"Advait":[45,34,89,81],"Saurav":[12,42,23,44]}print(d1["Advait"])d2 = {False: 45,45:"Cricket","Name": "Sachin",10:"Zeeeero"}# dictionary should have unique keysprint(d2)d2.update(d1)print("After Update: ", d2)print("Only Keys = ",d2.keys())print("Only Values = ",d2.values())print("Only Items = ",d2.items())for j in d2.keys():    print(j," = " ,d2[j])print("Printing Items: ")for i,j in d2.items():    print("Key:",i," & Value: ",j)# to remove: pop(), popitem()#popitem removes the last updated KEY (not value)d3 ={1:"Hello",2:"Hola",3:"Namaste",4:"Bon Jor"}print("D3 = ",d3)d3.popitem()print("After Popitem: ",d3)d3 ={1:"Hello",2:"Hola",3:"Namaste",4:"Bon Jor",1:"Good Morning"}print("D3 = ",d3)d3.popitem()print("2. After Popitem: ",d3)d3.pop(1)print("1. After Pop = ",d3)actors = {"David":32,"Tim":42,"Rebecca":21,"Mary":45}male = {"David":"LA","Tim":"NY"}female = {"Rebecca":"SD","Mary":"WS"}# David who is a male of 32 years lives in LAfor name in actors.keys():    print_sentence=name +" who is a "    for male_city in male.keys():        if name==male_city:            print_sentence+="male of "+str(actors[name]) +" years lives in "+ male[name]    for female_city in female.keys():        if name==female_city:            print_sentence+="female of "+str(actors[name]) +" years lives in "+ female[name]    print(print_sentence)`
# \$100 – \$57
total_amount = 28
#initially
Rs_5 = 2
Rs_2 = 2
Rs_1 = 2+3 #initial 2 plus change of 3
initial_total = 5*Rs_5 + 2 *Rs_2 + 1*Rs_1

yet_to_be_accounted = total_amount – initial_total

print(“yet_to_be_accounted: “,yet_to_be_accounted)
# 12
Rs_5 += yet_to_be_accounted //5
yet_to_be_accounted%=5
Rs_2 += yet_to_be_accounted //2
yet_to_be_accounted%=2
Rs_1 += yet_to_be_accounted

print(“Total Rs 5 stamps = “,Rs_5)
print(“Total Rs 2 stamps = “,Rs_2)
print(“Total Rs 1 stamps = “,Rs_1)
#SETS
A = {1,5,2,6,9}
B = {6,9,11,14,15}
print(A)

# LIST, TUPLE, SETS => They can be converted to each others form\
l1 = [2,4,6,8,4,6,8,2,6,8]
l1 = list(set(l1))
print(l1)

#they are returning result as a new set, values of A and B will not change
print(A.union(B))
print(A.intersection(B))
print(A.difference(B))

#___update modifies the main set
A.update(B)
print(A)
print(A.intersection_update(B))
print(A.difference_update(B)) `# SET - sets - linear unordered mutable collection - doesnt allow duplicateset1 = {'Apple','Grapes','Banana','Orange'}print(type(set1))set1.add('Cherry')set2 = {"Pineapple","Mango","Apple","Orange"}# two ways to removeset1.remove("Banana")set1.discard("Apple")#set1.remove("Rose") - if value isnt there throws errorset1.discard("Rose")  #doesnt throw errorprint("1. Set1: ",set1)set1.pop()set1.update(set2)  #unionprint("2. Set1: ",set1)set1.clear()print("3. Set1: ",set1)### SET FUNCTIONS  ####set1 = {'Apple','Grapes','Banana','Orange'}set2 = {"Pineapple","Mango","Apple","Orange"}#UNIONprint("UNION")print(set1 | set2)print(set1.union(set2))print("INTERSECTION")print(set1 & set2)print(set1.intersection(set2))print("DIFFERENCE")print(set1 - set2)print(set1.difference(set2))print(set2 - set1)print(set2.difference(set1))print("SYMMETRIC DIFFERENCE")print(set1 ^ set2)print(set2 ^ set1)print(set1.symmetric_difference(set2))#update() will update the values of main set# set1.union(set2) - this gives a new set as output# set1.update(set2) - set1 is updated with the values# union - update()set1.update(set2)print(set1)# intersection: intersection_update()set1.intersection_update(set2)print(set1)# difference_update()set1.difference_update(set2)print(set1)#symmetric_difference_update()set1.symmetric_difference_update(set2)print(set1)# set, list, tuple => they are inter-convertiblelist1 = [3,6,9,12,3,6,9,3,6,3]list1 = list(set(list1))print(list1)set1 = {'Apple','Grapes','Banana','Orange'}set1 = list(set1)set1.index("Grapes")set1 = set(set1)set1 = tuple(set1)set1 = set(set1)print(set1.issubset(set2))#list1 = [3,6,9,12,3,6,9,3,6,3]list2 = [3,6,9,12,15]#does all the elements of list2 present in list1?t_list1 =set(list1)if set(list1).issuperset(set(list2)):    print("yes, list2 value exists in list1")else:    print("No, list2 has additional elements")`
# MAP FILTER REDUCE
#MAP – large set of data and you want to apply same formula over all the values
list1 = [-3,-6,-15,0,5,999,67,34]
#find square of all these values
list2 = []
for i in list1:
list2.append(i*i)
print(list2)

# one line function / lambda function

result = list(map(lambda x:x**2,list1))
print(“Map result = “,result)

# FILTER -used to filter out data from a list based on a condition
# logic of the function in filter should be designed such a way that you get either True or False
result = list(filter(lambda x:x>=0,list1))
print(“Filter result = “,result)

#filter out numbers divisible by 3
result = list(filter(lambda x:x%3==0,list1))
print(“2. Filter result = “,result)

#Reduce
#import functools as ft
from functools import reduce
result = reduce(lambda x,y:(x+y)/2, list1)
print(“3. Result from Reduce: “,result)

# function
def my_qs():
print(“How are you today?”)
print(“Where do you live?”)

my_qs()
# function that doesnt take any input argument nor does it return
def mysum1():
a,b,c=10,20,30
sum=a+b+c
print(“Sum is”,sum)
#function with input arguments
def mysum2(a,b,c): #required positional arguments
print(“A,B and C are: “,a,b,c)
sum=a+b+c
#print(“Sum is”,sum)
return sum

out = mysum2(9,18,27)
print(“Out =”,out)

def mysum3(a,b,c=99): #c is default, a & b are required – positional arguments
print(“A,B and C are: “,a,b,c)
sum=a+b+c
#print(“Sum is”,sum)
return sum

out = mysum3(9,18,27)
print(“Out =”,out)

out = mysum3(9,18)
print(“Out =”,out)

# 0, 1,1,2,3,5… fibonacci numbers

def checkvalue(a,b):
global h
print(“H = “,h)
h = 99
print(“2 H = “,h)
if a>b:
return (“is”,a,“a”)
elif b>a:
return (“is”,b,“b”)
else:
return (“not”,)
h=100
result =checkvalue(10,20)

if result==“not”:
print(“Both values are equal”)
else:
print(f”Variable {result} with value {result} is greater”)

# Session on MODULES

#Create a python file with name  p2.py and paste below programs there

#Functions
# positional and required
# keyword
# default values
# variable length arguments
def mysum1(a,b):
return a+b

def mymultiple(a,b):
print(“a * b = “,a*b)

def my_sample_func(a,b,c):
print(“A,B,C = “,a,b,c)

def myfunc1(*nums,**details):
“””This is a sample function to demonstrate working of a variable length parameters
Input:
nums: will take all the values as tuple. it can be empty as well
details: store all keyword arguments like a dictionary
Return:
doesnt return anything”””
print(type(nums), type(details)) #tuple, dictionary
for i in nums:
print(i,end=“, “)
print()
for k,v in details.items():
print(k,v)

if __name__ == “__main__”:
myfunc1(23,21,14,12,15,26,name=“Sachin”,age=49,place=“Mumbai”)

myfunc1(name=“Sachin”,age=49,place=“Mumbai”)

#DocString – this is

print(print.__doc__)
print(“===”)
print(input.__doc__)
print(“===”)
print(myfunc1.__doc__)

#Run below programs from different file

#import p2 as Amazing
from p2 import mymultiple, my_sample_func

#decorators

def my_main():
”’ Example of a function inside a function”’
print(“First line in function”)
def my_subfunc():
print(“First line inside sub func”)
print(“Second line in main function”)
my_subfunc()
print(“Third line in main function”)
my_subfunc()
print(“4th line in main function”)
my_main()

def my_fun2():
print(“First line from my_fun2”)

def my_fun3():
print(“First line from my_fun3”)

def my_fun1(var):
print(“First line from my_fun1”)
var()

if __name__ ==“__main__”:
mymultiple(10,20)
my_sample_func(10,50,80)

#calling my_fun2 from my_fun1
my_fun1(my_fun2) #passing function name as parameter
#calling my_fun3 from my_fun1
my_fun1(my_fun3) # passing function name as parameter
#Recursive functions – they call themselves
import time
def myfacto(n):
if n ==1:
return 1
return n * myfacto(n-1)

start1 = time.time()
out = myfacto(9)
end1 = time.time()
print(“Factorial of 10 is: “,out)
print(“Total time taken by recursion is:”,(end1-start1))

def myfacto2(n):
prod = 1
for i in range(1,n+1):
prod*=i
return prod
start2 = time.time()
out = myfacto2(9)
end2 = time.time()
print(“Factorial of 10 using Loops is: “,out)
print(“Total time taken by loop is:”,(end2-start2))

import random
var1 = random.randint(1,100)
print(“random number = “,var1)
print(“random number- between 0 and 1: “,random.random())
list1 = [1,2,3,4,5,6]
list2 = [“Apple”,“Banana”,“Cherry”,“Grapes”,“Guava”,“Mango”]
print(“Rolling the dice: “,random.choice(list2))

from datetime import date,datetime,time,timedelta,timezone, tzinfo
from pytz import timezone
#import datetime
print(“Current time = “,datetime.now())
print(“Yesterdat time = “,datetime.now()-timedelta(days=1))
print(“Today’s date: “,datetime.now().strftime(‘%Y-%m-%d’))
print(“This Month: “,datetime.now().month)
date_utc = datetime.now().replace(tzinfo=timezone(‘UTC’))
print(date_utc)
date_utc = datetime.now().replace(tzinfo=timezone(‘Asia/Kolkata’))
print(date_utc)
date_utc = datetime.now().replace(tzinfo=timezone(‘US/Eastern’))
print(date_utc)
# properties we mean – methods (functions) and variables
# class and object levels

class Books:
num_of_books = 0 #class variable

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

def display_book(self):
print(“Title of the book is”,self.title)
print(“Author of the book is”,self.author)
print(“Total books created is”,Books.num_of_books)

@classmethod
def display_classdetails(cls):
print(“Total number of books =”,cls.num_of_books)

b1=Books(“Python Programming”,“Swapnil Saurav”)
#b1.create_book()
b1.display_book()
b2=Books(“Machine Learning”,“Saurav”)
b3=Books(“Retail Management”,“Swapnil”)
b4=Books(“Data Visualization”,“Swapnil”)
#b2.create_book()
b2.display_book()
b1.display_book()
b3.display_classdetails()
b4.display_classdetails()
b1.display_classdetails()
Books.display_classdetails()
b3.display_book()

class MyMasthsOps:
def __init__(self,a,b):
self.num1 = a
self.num2 = b
return self.num1 + self.num2
def subtraction(self):
return self.num1 – self.num2

op1 = MyMasthsOps(10,5)
print(“Subtraction: “,op1.subtraction())
#Class and Objects
class Cart:
items_in_store=[{“item_code”:“100”,“Item_Description”:“Blue color Shirt”,“Cost”:40},
{“item_code”:“101”,“Item_Description”:“Chips Packet”,“Cost”:2},
{“item_code”:“102”,“Item_Description”:“Chocolate Royal”,“Cost”:5},
{“item_code”:“104”,“Item_Description”:“Shoes 9C”,“Cost”:30},
{“item_code”:“105”,“Item_Description”:“Carry Bag 9in”,“Cost”:70},
{“item_code”:“106”,“Item_Description”:“Pen Blue Rey”,“Cost”:10}]
def __init__(self):
self.list_of_items=[]

available =“N”
temp_dict = {“item_code”:“”,“item_desc”:“”,“price”:0,“quantity”:0}
icode= input(“Enter the item code: “)
for item in Cart.items_in_store:
if icode ==item[‘item_code’]:
available = “Y”
temp_dict[‘item_code’] = item[‘item_code’]
temp_dict[‘item_desc’] = item[‘Item_Description’]
temp_dict[‘price’] = item[‘Cost’]

if available==“Y”:
quan = int(input(“Enter the quantity:”))
temp_dict[‘quantity’] = quan
self.list_of_items.append(temp_dict)
else:
print(“This item is not available right now!”)

def display_items(self):
for item in self.list_of_items:
print(item)
print(“1. Add Item to the Cart”)
print(“2. Remove Item from the Cart”)
print(“3. Display the content of the cart”)
print(“4. Exit”)
return choice

if __name__ == ‘__main__’:
cart1 = Cart()
while True:
if ch==“1”:
elif ch==“2”:
pass
elif ch==“3”:
cart1.display_items()
elif ch==“4”:
break
else:
print(“Invalid Option, try again!”)
# CRUD – Create new data, Read existing data, Update (edit the existing data) & Deleting existing data
# RDBMS – relational database management system
# database structure – logical (how we use the database) and physical (actual files that are saved)
# DBA, Database Developers & Database Architect
# DBA – installing and making sure that the databases are up and running

# OLTP (Online Transaction Processing) v OLAP (Online Analytical Processing)
## CRUD – C, U,D=80%, 20% R v 99% – reading

# Table: Students
# ROLLNO NAME GRADE EMAILID PHONE
# 1 Sachin 5 sa@sa.com 123
# 2 Laxman 7 lax@lax.com 231

# Table: Competitions
# COMPID NAME DOC ORG CONTACTNO

#Table: STUDENTCOMPETITIONS
# ID ROLLNO COMPID RANK
class Library:
book_count = 0 #class level variable

# __init__() is automatically called when you create the object
def __init__(self,title,author,price): #object level method
self.title = title #object level variable
self.author = author #object level variable
self.price = price #object level variable
self.copies = –1
Library.book_count +=1 #Library.book_count = Library.book_count + 1

def print_info(self):
print(” Printing Book Info”)
print(“———————-“)
print(“Title = “,self.title)
print(“Author = “,self.author)
print(“Price = “,self.price)

def set_copies(self,copies=10):
self.copies = copies

def get_copies(self):
print(f”Total copies available for the book {self.title} is {self.copies})
return self.copies

b1 = Library(“Strangeness”,“George”, 13.50)
b2 = Library(“Python”,“Swapnil”, 19.50)

print(b1.book_count)
print(b2.book_count)
print(b3.book_count)
print(Library.book_count)
print(b1.title)
print(b2.title)
print(b3.title)
b3.print_info()
b2.set_copies(7)
b2.get_copies()
if b1.get_copies() <0:
b1.set_copies(5)
b1.get_copies()
Class Calculation
1. use init to assign two variables
2. def add(self) , def sub(self), def mul(self), def div(self)

##Main Program
input a and b
c1 = Calculation(a,b)
# Exceptions
# example 1: ValueError – when u convert non number to integer

”’
1. Syntax error:
print(“Hello) #SyntaxError: unterminated string literal (detected at line 7)

2. Logical Error: Sum of two numbers
a,b = 4,5
print(a*b)

3. Exceptions: Runtime error
1. int(‘n’) # ValueError: invalid literal for int() with base 10: ‘num’
ZeroDivisionError: division by zero

”’
#WAP to input two numbers and perform their division
try: #try block is used to check the exception
num = int(input(“Enter the numerator: “))
except ValueError: #if there is ValueError, code comes here
print(“You have given an invalid number, resetting it to zero”)
num = 0

except Exception: # if previous exception not valid then it comes here
print(“Sum error has occurred. Exiting the program”)
exit(0)
else: # if there is no error, then comes to else (not mandatory)
print(“You are doing good. No error so far!”)
finally: # error or no error, this is called. again its not mandatory
print(“You are doing good.”)

try:
dem = int(input(“Enter the denominator: “))
except ValueError: #if there is ValueError, code comes here
print(“You have given an invalid number, resetting it to one”)
dem = 1
try:
div = num/dem
except ZeroDivisionError:
print(“Denominator cant be zero!!! We are terminating the program”)
else:
print(“Division of given values is”,div)
# WAP to input and divide two numbers
try:
num = int(input(“Enter the numerator: “))
dem = int(input(“Enter the denominator: “))
divide = num/dem
except ValueError:
print(“Sorry, we cant move ahead because of the invalid number”)

except ZeroDivisionError:
print(“Sorry, we cant move ahead because we cant handle zero as denominator”)
else:
finally:
print(“thank you for using our calculator. See you soon…”)
# WAP to input and divide two numbers

try:
num = int(input(“Enter the numerator: “))
dem = int(input(“Enter the denominator: “))
divide = num / dem

except ValueError:
print(“Invalid number”)
except Exception:
print(“Some error has occurred. We need to stop”)
else:
finally:
print(“thank you for using our calculator. See you soon…”)

## Another approach
# WAP to input and divide two numbers
while True:
try:
num = int(input(“Enter the numerator: “))
except ValueError:
print(“Invalid number”)
else:
break

while True:
try:
dem = int(input(“Enter the denominator: “))
except ValueError:
print(“Invalid number”)
else:
if dem ==0:
print(“Denominator cant be zero, enter again!”)
else:
break

divide = num/dem

## Another approach using our own class
# WAP to input and divide two numbers

#creating by own exception
class ZeroValueError(Exception):
def __init__(self,value):
self.val = value

while True:
try:
num = int(input(“Enter the numerator: “))
except ValueError:
print(“Invalid number”)
else:
break

while True:
try:
dem = int(input(“Enter the denominator: “))
if dem ==0:
raise ZeroValueError(dem)
except ValueError:
print(“Invalid number”)
except ZeroValueError as zde:
print(f”Denominator cant be {zde.val}, enter again!”)
else:
break

divide = num/dem

#Another approach using Assert method
# WAP to input and divide two numbers

while True:
try:
num = int(input(“Enter the numerator: “))
except ValueError:
print(“Invalid number”)
else:
break

while True:
try:
dem = int(input(“Enter the denominator: “))
if dem ==0:
assert (dem!=0),“Denominator cant be zero, lets stop!”
except ValueError:
print(“Invalid number”)
except AssertionError:
print(“Dont give zero for denominator”)
else:
break

divide = num/dem
# Files – txt, csv
# w (write mode): only writing, file needn’t be there (it will be created), previous content gets deleted
# a (append mode): only writing, added on the previous content
# relative path: will not have drive name, can start with / or \\
filename = “MyPoem.txt”
filename2 = “c:/myfolder/Myfile.txt”
# if file isnt there for read mode:
# FileNotFoundError: [Errno 2] No such file or directory: ‘/MyPack1/MyPoem.txt’
fileobj = open(filename,“w”)

fileobj.close()
”’
Reading & Writing txt files. Modes in which you can open a txt files:
1. r – reading (you cant write to it)
2. w – writing (this will delete previous content and add the new content only)
3. a – append (old data will be ratained and new data is added below)
4. r+ – reading and writing
5. w+ – writing and reading
6. a+ – writing and reading

operations:
writing: write(), writelines()

1. Open the file using a handle to the object
2. whatever you want to do – read/write/
3. Close the file

Absolute path: complete path, with the drive letter: D:\\Files\\file.txt
Relative path: path is mentioned with respect to the python file which has the code: /data/abc.txt

”’

file=“MyLearn.txt”
try:
fileobj = open(file,“r”)
except FileNotFoundError:
fileobj1 = open(file, “w”)
fileobj1.close()
fileobj = open(file, “r”)

print(content)
#seek() – instruction to go to a perticular position
#fileobj.seek(1) #goes to the beginning of the content

fileobj.seek(0)
print(content2)
character = “B”
for sentence in content2:
if sentence==character:
print(sentence)

fileobj.close()

fileobj = open(file,“a”)
inp_content=”’
L: Lion
M: Monkey
N: Needle
O: Opal
P: Peach
”’
fileobj.write(inp_content)
inp_content2 = [‘Q: Queen\n,‘R: Rain\n,‘S: Ship\n,‘T: Teapot’]
fileobj.writelines(inp_content2)
fileobj.close()

### Writing usage
file=“MyLearn.txt”
fileobj = open(file,“a”)
inp_content=”’
L: Lion
M: Monkey
N: Needle
O: Opal
P: Peach
”’
fileobj.write(inp_content)
inp_content2 = [‘Q: Queen\n,‘R: Rain\n,‘S: Ship\n,‘T: Teapot’]
fileobj.writelines(inp_content2)
fileobj.close()
”’
2. Write to the diary

2.
11-JUNE-2023: Today we had singing practice at school

1.
Which date: 11-JUNE-2023
Output: Today we had singing practice at school

”’
import csv
file = “MyData.csv”
fileobj = open(file, mode=“a”, newline=“”)
csvwriter = csv.writer(fileobj, delimiter=“,”,quotechar=‘”‘,quoting=csv.QUOTE_MINIMAL)
while True:
content = []
content.append(name)
content.append(city)
content.append(score)
csvwriter.writerow(content)
ch=input(“Enter any value to continue adding:”)
if len(ch)==0:
break
fileobj.close()

”’ Reading the data from the CSV file”’
fileobj = open(file) # default mode is reading (r)
total = 0
total+=int(each_row)
print(“Total = “,total)
# name
# lastname, firstname
import csv
filename = “FruitProduction.csv”
fileobj = open(filename,“w”,newline=“”)
writerobj = csv.writer(fileobj, delimiter=“,”,quotechar=‘”‘,quoting=csv.QUOTE_MINIMAL)
first_row = [‘Year’,‘Apple’,‘Banana’,‘Mango’,‘Oranges’]
second_row = [‘2023’,65,34,29,56]
third_row = [‘2022’,45,29,23,45]
forth_row = [‘2021’,39,29,19,25]
writerobj.writerow(first_row)
writerobj.writerow(second_row)
writerobj.writerow(third_row)
writerobj.writerow(forth_row)
fileobj.close()

fileobj = open(filename) #default read mode
print(row)
fileobj.close()
fileobj = open(filename)
#1. Show to Apple production for last 3 years
print(“Apple production were:”)
print(row,“:”,row)

fileobj.close()

#Highest production of Mango
fileobj = open(filename)
#2. Highest Mango production
mango_high,year_high = –1,-1

linecount=0
if linecount==0:
linecount+=1
else:
if int(row) > mango_high:
mango_high=int(row)
year_high = row
print(“Highest Mango production was”,mango_high,“in the year”,year_high)
fileobj.close()  ## PostgreSQL Tutorial

# pymysql library connects to MYSQL
# Books
# Publishers

import sqlite3
connection = sqlite3.Connection(‘BOOKSDB.SQLITE’)
cursorobj = connection.cursor()

# SQL – Structured Query Language
# Dropping an already existing table:
#cursorobj.execute(“DROP TABLE Publishers”)

#create a new table:
table1 = ”’
Create Table Publishers(
PUBID INTEGER PRIMARY KEY,
PUBNAME VARCHAR,
PUBCITY VARCHAR
)
”’
#cursorobj.execute(table1) #creates the table
#create a new table:
table2 = ”’
Create Table BOOKS(
BID INTEGER PRIMARY KEY,
TITLE VARCHAR,
AUTHOR VARCHAR,
PUBID INTEGER,
CONSTRAINT fk_pidid_cons Foreign Key (PUBID) References Publishers(PUBID)
)
”’
#cursorobj.execute(table2) #creates the table

# INSERT Commands are used to add data to the tables
insert_data = [‘Insert into Publishers (PubID, PubName, PubCity) values (101, “ABC International”,”New York”)’,
‘Insert into Publishers values (102,”Indigo Publishers”,”New Delhi”)’,
‘Insert into Publishers (PubID, PubCity, PubName) values (105,”Hyderabad”,”Glocal Publishers”)’]

insert_data = [‘Insert into Books values (101,”Python Programming”,”Sachin”,102)’,
‘Insert into Books values (102,”Data Science Learning”,”Rohit”,102)’,
‘Insert into Books values (103,”SQL Programming”,”Virat”,105)’]
for statement in insert_data:
cursorobj.execute(statement)
connection.commit()
# pymysql library connects to MYSQL
# Books
# Publishers

import sqlite3
connection = sqlite3.Connection(‘BOOKSDB.SQLITE’)
cursorobj = connection.cursor()

# SQL – Structured Query Language
# Dropping an already existing table:
#cursorobj.execute(“DROP TABLE Publishers”)

#create a new table:
table1 = ”’
Create Table Publishers(
PUBID INTEGER PRIMARY KEY,
PUBNAME VARCHAR,
PUBCITY VARCHAR
)
”’
#cursorobj.execute(table1) #creates the table
#create a new table:
table2 = ”’
Create Table BOOKS(
BID INTEGER PRIMARY KEY,
TITLE VARCHAR,
AUTHOR VARCHAR,
PUBID INTEGER,
CONSTRAINT fk_pidid_cons Foreign Key (PUBID) References Publishers(PUBID)
)
”’
#cursorobj.execute(table2) #creates the table

# INSERT Commands are used to add data to the tables
insert_data = [‘Insert into Publishers (PubID, PubName, PubCity) values (101, “ABC International”,”New York”)’,
‘Insert into Publishers values (102,”Indigo Publishers”,”New Delhi”)’,
‘Insert into Publishers (PubID, PubCity, PubName) values (105,”Hyderabad”,”Glocal Publishers”)’]

insert_data = [‘Insert into Books values (101,”Python Programming”,”Sachin”,102)’,
‘Insert into Books values (102,”Data Science Learning”,”Rohit”,102)’,
‘Insert into Books values (103,”SQL Programming”,”Virat”,105)’]

”’
for statement in insert_data:
cursorobj.execute(statement)
connection.commit()
”’
# Read data from the database
q1 = “Select * from Publishers”
cursorobj.execute(q1)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
print(row)

q1 = “Select * from Books”
cursorobj.execute(q1)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
print(row)

#UPDATE
q3 =“Update Books Set Author =’Dhoni’ where BID=102 “
cursorobj.execute(q3)
connection.commit()

#DELETE
q3 =“Delete from Publishers where PUBID=101 “
cursorobj.execute(q3)
connection.commit()

q2 = “Select TITLE, PUBNAME, Author from Books t1, Publishers t2 where t1.PUBID=t2.PUBID”
cursorobj.execute(q2)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
#print(row)
”’
Install MYSQL from

Installation steps:
https://dev.mysql.com/doc/mysql-installation-excerpt/5.7/en/
or check this:
https://www.sqlshack.com/how-to-install-mysql-database-server-8-0-19-on-windows-10/

Components that we need:
3. Database
4. Workbench – UI tool to connect to the Server
”’

import pymysql
cursorobj = connection.cursor()

# SQL – Structured Query Language
# Dropping an already existing table:
#cursorobj.execute(“DROP TABLE Publishers”)

#create a new table:
table1 = ”’
PUBID INT PRIMARY KEY,
PUBNAME VARCHAR(15),
PUBCITY VARCHAR(15)
);
”’
#cursorobj.execute(table1) #creates the table
#create a new table:
table2 = ”’
BID INT PRIMARY KEY,
TITLE VARCHAR(15),
AUTHOR VARCHAR(15),
PUBID INT,
CONSTRAINT fk_pidid_cons Foreign Key (PUBID) References Publishers(PUBID)
)
”’
#cursorobj.execute(table2) #creates the table
# Alter is used to change the datatype
# Modify to change the current structure
alter_q =“ALTER TABLE publishers Modify Column PUBNAME varchar(40)”
#cursorobj.execute(alter_q)

alter_q =“ALTER TABLE Books Modify Column TITLE varchar(40)”
cursorobj.execute(alter_q)
# INSERT Commands are used to add data to the tables
insert_data = [‘Insert into Publishers (PubID, PubName, PubCity) values (101, “ABC International”,”New York”)’,
‘Insert into Publishers values (102,”Indigo Publishers”,”New Delhi”)’,
‘Insert into Publishers (PubID, PubCity, PubName) values (105,”Hyderabad”,”Glocal Publishers”)’]
”’
for statement in insert_data:
cursorobj.execute(statement)
connection.commit()
”’
insert_data = [‘Insert into Books values (101,”Python Programming”,”Sachin”,102)’,
‘Insert into Books values (102,”Data Science Learning”,”Rohit”,102)’,
‘Insert into Books values (103,”SQL Programming”,”Virat”,105)’]

for statement in insert_data:
cursorobj.execute(statement)
connection.commit()

# Read data from the database
q1 = “Select * from Publishers”
cursorobj.execute(q1)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
print(row)

q1 = “Select * from Books”
cursorobj.execute(q1)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
print(row)

#UPDATE
q3 =“Update Books Set Author =’Dhoni’ where BID=102 “
cursorobj.execute(q3)
connection.commit()

#DELETE
q3 =“Delete from Publishers where PUBID=101 “
cursorobj.execute(q3)
connection.commit()

q2 = “Select TITLE, PUBNAME, Author from Books t1, Publishers t2 where t1.PUBID=t2.PUBID”
cursorobj.execute(q2)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
#print(row)

##### Learn Python – Evening Jan 2022 – II
`############################str1 = 'HELLO'str2 = "I am fine"str3 = '''Where are you going?How long will you be here?What are you going to do?'''str4 = """I am hereI will be here for next 7 daysI am going to just relax and chill"""print(type(str1),type(str2),type(str3),type(str4))print(str1)print(str2)print(str3)print(str4)# What's you name?str5 = "What's your name?"print(str5)#He asked,"Where are you?"str6 = 'He asked,"Where are you?"'print(str6)#He asked,"What's your name?"#escape sequence  \print('''He asked,"What's your name?"''')print("He asked,\"What's your name?\"")print('nnnnn\nnn\tnn')print("\FOlder\\newfolder")# \n is used to print newline in pythonprint("\\n is used to print newline in python")# \\n will not print newline in pythonprint("\\\\n will not print newline in python")str1 = "Hello You"str2 = "There"print(str1 + str2)print(str1 *5)for i in str1:    print("Hello")#indexingprint(str1)print("last element: ",str1)print("last element: ",str1[-1])print("second element: ",str1[-8])print("ell: ",str1[1:4])print("ell: ",str1[-8:-5])print("First 3: ",str1[:3])print("First 3: ",str1[:-6])print("Last 3: ",str1[6:])print("Last 3: ",str1[-3:])#Methods - exactly same as your functions - only difference is they are linked to a classimport timestr1 = "HELLO"print(str1.replace("L","X",1))sub_str = "LL"str2 = "HELLO HOW WELL ARE YOU LL"cnt = str2.find(sub_str)print("Count = ",cnt)if cnt<0:    print("Sorry, no matching value hence removing")else:    print("Value found, now replacing")    for i in range(5):        print(". ",end="")        time.sleep(0.5)    print("\n")    print(str2.replace(sub_str,"OOOO"))out_res = str2.split("LL")print("Output Result = ",out_res)out_str = "LL".join(out_res)print(out_str)print(str2.title())print(str2.lower())print(str2.upper())str3 = 'hello how well are you ll'print(str3.islower())print(str3.isupper())num1 = input("Enter a number: ")if num1.isdigit():    num1 = int(num1)else:    print("Invaid input")ename = input("Enter your first name: ")if ename.isalpha():    print("Your name is being saved...")else:    print("Invaid name")#WAP to count of vowels in a sentencepara1 = "Work, family, and endless to-do lists can make it tough to find the time to catch up. But you'll never regret taking a break to chat with your friend, Frost reminds us. Everything else will still be there later."sum=0for l in para1:    if l=='a' or l=='A' or l=='e' or l=='E' or l=='i' or l=='I' or l=='o' or l=='O' or l=='u' or l=='3':        sum+=1print("Total vowesl = ",sum)sum=0for l in para1.lower():    if l=='a' or l=='e'  or l=='i' or l=='o' or l=='u':        sum+=1print("Total vowesl = ",sum)sum=0for l in para1.lower():    if l in 'aeiou':        sum+=1print("Total vowesl = ",sum)##########  LIST#LIST#collection of linear ordered itemslist1 = [1,2,3,4,5]print(type(list1))print("Size = ",len(list1))print(list1)print(list1[-1])print(list1)print(list1[:3])print(list1[-3:])print(list1[1:4])for i in list1:    print(i)print([2,3,4]+[6,4,9])print([2,3,4]*3)str2 = "A B C D A  B C A B A "print(str2.count("D"))print(list1.count(3))l1 = [2,4,6,8]print(l1.append(12))print(l1)l1=10print(l1)l1.insert(2,15)print(l1)# Queue: FIFO# Stack: LIFOif 16 in l1:    l1.remove(16) #takes in value to removel1.remove(15)print(l1)l1.pop(1) #indexprint(l1)#################while False:    print("Queue is: ",l1)    print("1. Add\n2. Remove\n3. Exit")    ch=input("Enter your choice: ")    if ch=="1":        val = input("Enter the value: ")        l1.append(val)    elif ch=="2":        l1.pop(0)    elif ch=="3":        break    else:        print("Try again!")while False:    print("Stack is: ",l1)    print("1. Add\n2. Remove\n3. Exit")    ch=input("Enter your choice: ")    if ch=="1":        val = input("Enter the value: ")        l1.append(val)    elif ch=="2":        l1.pop(-1)    elif ch=="3":        break    else:        print("Try again!")l2 = l1  #they become samel3 = l1.copy()print("1. List1 = ",l1)print("1. List2 = ",l2)print("1. List3 = ",l3)l1.append(33)l2.append(44)l3.append(55)print("2. List1 = ",l1)print("2. List2 = ",l2)print("2. List3 = ",l3)l1.extend(l3)print(l1)print(l1.count(6))sum=0marks=[]for i in range(3):    m = int(input("Enter marks in subject "+str(i+1)+": "))    marks.append(m)    sum+=mprint("Sum is ",sum, "and average is ",sum/3)print("Marks obtained is ",marks)#THREE STUDENTS AND THREE SUBJECTS:allmarks=[]for j in range(3):    sum=0    marks=[]    for i in range(3):        m = int(input("Enter marks in subject "+str(i+1)+": "))        marks.append(m)        sum+=m    print("Sum is ",sum, "and average is ",sum/3)    print("Marks obtained is ",marks)    allmarks.append(marks)print("All the marks are: ",allmarks)# All the marks are:  [[88, 66, 77], [99, 44, 66], [44, 99, 88]]# find the highest marks of each subject#Tuple - linear order immutable collection#strings are also immutabletuple1 = (1,3,1,4,1,5,1,6)print(type(tuple1))print(len(tuple1))print(tuple1.count(1))print(tuple1.index(4))print(tuple1)for i in tuple1:    print(i)t1 = list(tuple1)t1.append(55)t1=tuple(t1)t2 = (2,4,6,8)   #packing#unpackinga,b,c,d,e = t2print(a,b,c,d)#packing`
import numpy as np
x = range(16)
x = np.reshape(x,(8,2))
print(x)
x2 = np.ones((3,3))
print(x2)
x3 = np.full((4,4),11)
print(x3)
x4 = [[1,2,1],[1,1,1],[2,2,2],[3,1,1]]
x4 = np.array(x4)
print(type(x4))
print(x4)

#indexing
print(x4[1:3,1:])
x5 = np.array([[1,2,1],[1,1,1],[2,2,2],[3,1,1]])
print(x4+x5)
print(x4-x5)
print(np.subtract(x4,x5))
print(x4 * x5)
print(np.multiply(x4,x5))
print(x4 / x5)
print(np.divide(x4,x5))
print(x4 // x5)
print(np.sqrt(x4))
print(np.mean(x4))
print(“Shape of the matrix = “,np.shape(x4))
x6 = [,,]
print(x4 @ x6) #matrix multiplication
print(np.matmul(x4,x6))

# x=5, y=4
# 3x-2y = 7
# 3x+5y = 35
# A * B = C => B = A inverse * C
A = np.array([[3,-2],[3,5]])
C = np.array([,])
#find determinant and if its non zero only then perform inverse
det_A = np.linalg.det(A)
if det_A != 0:
Inv_A = np.linalg.inv(A)
Sol = Inv_A @ C
print(“Solution is: “,Sol)
else:
print(“Solution is not possible”)

# SCIPY
import scipy
#

## Numpy Video

#Indigo computers how many laptops and desktops to make
# memory chip: 1L+ 2D <=15000
# processing chip: 1L + 1D <=10000
# machine time: 4L + 3D <=25000
# maximize Profit: 750L + 1000D = ?
import numpy as np
from scipy.optimize import minimize, LinearConstraint, linprog
l,d = 1,1
obj = 750*l + 1000*d
#since we are going to minimize, the obj becomes
obj = –750*l –1000*d
obj_list = [-750, –1000]

lhs_constraint_ineq = [[1,2],
[1,1],
[4,3]]
rhs_value=[15000,
10000,
25000]
val_bounds = [(0, float(“inf”)),(0, float(“inf”))]
opt_sol = linprog(c=obj_list, A_ub=lhs_constraint_ineq, b_ub=rhs_value,method=“revised simplex”)
print(opt_sol)

import pandas as pd
data1 = pd.DataFrame([10,20,30,40,50])
print(data1)

data1 = pd.DataFrame([[10, “Sachin”],[20,“Laxman”],[30,“Dhoni”],[40,“Kohli”],[50,“Rohit”]], columns=
[“Roll No”,“Name”],
index=[“Player 1”,“Player 2”,“Player 3”,“Player 4”,“Player 4”])
print(data1)

print(dataset1)

## VIDEO FOR ABOVE DISCUSSION

import pandas as pd
data = [[“Sachin”,“Cricket”,“Mumbai”,19000],[“Virat”,“Cricket”,“Delhi”,10000],
[“Dhoni”,“Cricket”,“Ranchi”,11000],[“Sunil”,“Cricket”,“Mumbai”,8000],
[“Ravi”,“Cricket”,“Mumbai”, 3000]]
data_df = pd.DataFrame(data, columns=[“Name”,“Sports”,“City”,“Runs”],
index=[“A”,“B”,“C”,“D”,“E”])
print(data_df)
print(pd.__version__) #2.0.0
print(data_df.loc[“B”]) # loc & iloc
print(data_df.loc[[“A”,“C”]])

print(data_df.iloc)
print(data_df.iloc[0,2]) #(row,col)
print(data_df.iloc[[0,2],2])
print(data_df.iloc[0:3,1:3])
print(data_df.iloc[3:,:2])

print(“Average of Runs scored: “, data_df[“Runs”].mean())
print(“Total Runs scored: “, data_df[“Runs”].sum())
# Axis = 0 is for Rows, Axis = 1 is for Columns
data_df = data_df.drop([“A”], axis=0)
data_df = data_df.drop([“City”], axis=1)
#
data_df = data_df.drop(data_df.index)
data_df = data_df[data_df.Name !=“Virat”]
print(“After Drop”)
print(data_df)

## VIDEO - PANDAS INTRODUCTION

import pandas as pd
device_df = pd.read_csv(“D:/datasets/gitdataset/user_device.csv”) # 272 rows x 6 columns
usage_df = pd.read_csv(“D:/datasets/gitdataset/user_usage.csv”) # 240 rows x 4 columns

# merge
usage_device_df = pd.merge(usage_df, device_df,on=“use_id”) # inner
print(“INNER \n,usage_device_df)
usage_device_df = pd.merge(usage_df, device_df,on=“use_id”, how=“left”) # inner
print(“LEFT \n,usage_device_df)
usage_device_df = pd.merge(usage_df, device_df,on=“use_id”, how=“right”) # inner
print(“RIGHT \n,usage_device_df)

usage_device_df = pd.merge(usage_df, device_df,on=“use_id”, how=“outer”) # inner
print(“FULL \n,usage_device_df)

# 272 & 240 – 159 (159 + 113 + 81 = 353)
print(“Number of Rows in Combind tables: “,usage_device_df.shape)
print(“Number of Columns in Combind tables: “,usage_device_df.shape)

print(hotels_df.shape)
print(hotels_df.dtypes)

”’
Data Analytics steps:
1. Collecting data
2. Data cleaning: missing data, outliers
”’
# heatmap to check missing values
import matplotlib.pyplot as plt
import seaborn as sns

cols_30 = hotels_df.columns[:30]
print(cols_30)
sns.heatmap(hotels_df[cols_30].isnull(), cmap=sns.color_palette([“#00FF00”, “#FF0000”]))
plt.show()

## DATA VISUALIZATION PRESENTATION AND PROJECTS

data = [[“January”,1500,1900],[“February”,1900,1800],[“March”,1500,1800],[“April”,1000,1500],[“May”, 2300,2500]]
import pandas as pd
data_df = pd.DataFrame(data, columns=[“Month”,“Runs Scored”,“Runs Given Away”])
print(data_df)
print(data_df[“Runs Scored”].mean())
print(data_df[“Runs Given Away”].sum())
print(data_df[data_df[‘Month’]==“March”])
print(data_df[data_df[‘Month’].isin([“January”,“April”,“May”])])
print(data_df.iloc)
print(data_df.loc[[0,2,4],[“Month”,“Runs Given Away”]])

print(device_df.shape)
print(usage_df.shape)
new_df = pd.merge(device_df, usage_df,on=“use_id”) #how=inner
print(new_df)

new_df = pd.merge(device_df, usage_df,on=“use_id”, how=“left”) #how=inner
print(new_df)
new_df = pd.merge(device_df, usage_df,on=“use_id”, how=“right”) #how=inner
print(new_df)
new_df = pd.merge(device_df, usage_df,on=“use_id”, how=“outer”) #how=inner
print(new_df)
# 159+81+113 = 353

import pandas as pd
print(data_df)

### VIDEO RECORDING OF THE SESSION

# Natural language processing
import pandas as pd

”’
1. convert entire text to lower case
2. decomposition on the text (readable text)
3. convert accent (language specific words) into ASCII value (ignore the error)
4. Tokenization: breaking into words
5. Stop words removal (non helpful)
”’
#review_comment_message
import nltk
import unicodedata
reviews_df = reviews_df[reviews_df[‘review_comment_message’].notnull()].copy()

# Function to translate into English
”’
translator = Translator()
reviews_df[‘review_comment_english’] = reviews_df[‘review_comment_message’].apply(lambda x: translator.translate(x,src=”pt”, dest=’en’).text)

print(reviews_df[‘review_comment_english’])
”’
# function to normalize portuguese text
def normalize_text(text):
return unicodedata.normalize(‘NFKD’,text).encode(‘ascii’,errors=‘ignore’).decode(‘utf-8’)
def basic_nlp(text):
text = text.lower() # step 1 – lowercase
# steps 2 and 3
text = normalize_text(text)
# step 4: tokenize
words = set(normalize_text(word) for word in nltk.tokenize.word_tokenize(text))
# step 5: remove stop words (non meaningful words)
STOP_WORDS = nltk.corpus.stopwords.words(‘portuguese’)
words = tuple(w for w in words if w not in STOP_WORDS and w.isalpha())
return words

reviews_df[‘review_comment_words’] = reviews_df[‘review_comment_message’].apply(basic_nlp)
print(“===================”)

# Unigram, bigram, trigram

## Probability Distribution Notes

##### Learning with P
`print('hello')print(5 +3  )print('5+3=',   5+3)var1 = 53print(type(var1))  #<class 'int'>  integervar1 = '53'  # str - stringprint(type(var1))var1 = 53.0  #floatprint(type(var1))var1 = 53j   #complexprint(type(var1))var1 = False  #print(type(var1))count_of_pens = 23  #variable names can only have alphabets, numbers, _#variable shouldnt begin with a numbercost_each_pen = 21.23total_cost = cost_each_pen \             * count_of_pensprint('Cost of each pen is',cost_each_pen,"so for",count_of_pens,"pens, "       "total cost would be",total_cost)#f-string format stringprint(f"Cost of each pen is {cost_each_pen} so for {count_of_pens} pens, total cost would be {total_cost:.1f}")`

## VIDEO 1

`###################player= "Rohit"country = "India"position = "Captain"print(f"The Player {player:<15} plays for the country {country:^15} and is {position:>15} of the team")player= "Mbangawapo"country = "Zimbabwe"position = "Wicketkeeper"print(f"The Player {player:<15} plays for the country {country:^15} and is {position:>15} of the team")num1 = 5num2 = 3#Arithematic Operationsprint(num1 + num2)print(num1 - num2)print(num1 * num2)print(num1 / num2)  #float outputprint(num1 // num2) #integer division (double division)- integer (int)print(num1 % num2)  #remainder - moduloprint(num1 ** num2)  #num1 to the power num2#post office stamp problem for assignmentlength = input("Enter length of the rectangle: ")length = int(length)print(type(length))breadth = int(input("Enter breadth of the rectangle: "))area = length * breadthperimeter = 2*(length + breadth)print(f"The rectangle with length {length} and bread {breadth} has an area of {area} and perimeter of {perimeter}")#Comparison operators:  <   >    <=   >=  ==   !=#input here is variables, output is always bool valueval1=34val2=34print("Is val1 less than val2? ", val1 < val2)print("Is val1 greater than val2? ", val1 > val2)print("Is val1 less than or equal to val2? ", val1 <= val2)print("Is val1 greater than or equal to val2? ", val1 >= val2)print("Is val1 equal to val2? ", val1 == val2)print("Is val1 not equal to val2? ", val1 != val2)#Logical operators: and or not: Input is bool and output is also boolprint(val1 < val2 and val1 > val2 or val1 <= val2 and val1 >= val2 and val1 == val2 or val1 != val2)#in AND - even if you have one false - o/p is False otherwise True# in OR - even if you have one True - o/p is True otherwise Falseprint(not val1==val2)#membership operator: in, not inprint( 5 in [5,10,15,20])print("a" not in "ABCDE")marks1 = int(input("Enter the marks in subject 1: "))marks2 = int(input("Enter the marks in subject 2: "))marks3 = int(input("Enter the marks in subject 3: "))total = marks1 + marks2 + marks3avg = total / 3print(f"Total marks obtained is {total} and the average is {avg:.2f}")` `#Conditionalnum1 = -90if num1 >0:    print("Number is positive")    print("This is second line of if")if num1 >0:    print("Number is positive")else:    print("Number is not positive")if num1 >0:    print("Number is positive")elif num1 <0:    print("Number is negative")else:    print("Its Zero")avg = 80'''avg >= 90: Grade A, 80-90: B, 70-80: C, 60-70: D, 50-60:E, 40-50: F and Grade Failed <40'''if avg>=90:    print("Grade: A")elif avg>=80:    print("Grade: B")elif avg>=70:    print("Grade: C")elif avg>=60:    print("Grade: D")elif avg>=50:    print("Grade: E")elif avg>=40:    print("Grade: F")else:    print("Grade: FAILED")if avg>=40:    print("You have passed")#print - You have passed for all those who got over 40%avg=99.1if avg>=40:    print("You have passed")    if avg >= 90:        print("Grade: A")        if avg >=95:            print("You win President's medal")            if avg>=99:                print("WOW")    elif avg >= 80:        print("Grade: B")    elif avg >= 70:        print("Grade: C")    elif avg >= 60:        print("Grade: D")    elif avg >= 50:        print("Grade: E")    else:        print("Grade: F")else:    print("Grade: FAILED")#to evaluate an algorithm - we look at Space complexity and Time complexity# President medal for >95%num1 = 78if num1%2==0:    print("Even")else:    print("Odd")age=21nationality = "USA"if age>21 and nationality=="USA":    print("Vote")####### LOOPS -  repeatition# for loop: exactly how manytimes to run the loop# while loop: condition under which to repeat the loop# range(a,b,c): a= initial value (including), b=end value (excluding), c= increment#range(3,12,3): 3,6,9#range(3,13,3): 3,6,9,12for i in range(3,16,3):    print("HELLO")    print("i = ",i)`

## Video 3 Here

`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()'''    *    * *    * * *   * * * *  * * * * * '''for j in range(5):    for i in range(5-j-1):        print(" ",end='')    for k in range(j+1):        print("*",end=' ')    print()n=5m=1for j in range(1,11):    for i in range(1,11):        print(f"{i:>2} * {j:>2} = {j*i:>3}",end="  ")    print()#### WHILE Loops: no fixed times - based on some conditioni=1while i<=10:    print(i)    i+=1#print hello untill user wantsch='y'while ch=='y':    print("HELLO")    ch=input("Press y to continue, anyother key to stop: ")`

## DAY 4 Video

`import randomnum = random.randint(1,100)print("==> ",num)l1="="total_attempts,max,min=0,0,9999n=250000pc = n//100for i in range(n):    attempt = 0    while True:        guess = int(input("Guess the number: "))        #guess = random.randint(1,100)        attempt +=1  # attempt = attempt + 1        if guess ==num:            print(f"Congratulations! You have guessed it correctly in {attempt} attempts.")            total_attempts +=attempt            if min > attempt:                min = attempt            if max < attempt:                max = attempt            if i%pc==0:                print(i//pc,"% Completed")            break        elif guess > num:            print("Sorry, Actual number is smaller")        else:  #guess < num:            #pass            print("Sorry, Actual number is greater")print("Average number of attempts it took: ",total_attempts/n)print("Maximum attempt:",max," and minimum attempt:",min)##################################  Attempt  2  ##import random#print("==> ",num)l1="="total_attempts,max,min=0,0,9999n=250000pc = n//100num = random.randint(1, 100)for i in range(n):    attempt = 0    start, end = 1, 100    while True:        #guess = int(input("Guess the number: "))        guess = random.randint(start,end)        if guess>100 or guess <1:            continue  #takes you to the beginning of the loop        attempt +=1  # attempt = attempt + 1        if guess ==num:            #print(f"Congratulations! You have guessed it correctly in {attempt} attempts.")            total_attempts +=attempt            if min > attempt:                min = attempt            if max < attempt:                max = attempt            if i%pc==0:                print(i//pc,"% Completed")            break        elif guess > num:            #print("Sorry, Actual number is smaller")            end=guess-1        else:  #guess < num:            #pass            #print("Sorry, Actual number is greater")            start =guess+1print("Average number of attempts it took: ",total_attempts/n)print("Maximum attempt:",max," and minimum attempt:",min)`

## DAY 5 VIDEO (While Example)

`#Stringsstr1 = 'Hello'str2 = "How are you?"str3 = """I am fineI am greatI am amazing"""str4 = '''I am here'''print(str3)print("What's your name?")print('What\'s your name?')print(str1 + " "+str2)print(str1 *5)for i in str1:    print("Hello")#subset of the stringstr6 = "What's your name?"print(str6)print(str6)print(len(str6))print(str6[len(str6) - 1])  #last charprint(str6[len(str6) - 2])  #2nd last charprint(str6[- 1])  #last charprint(str6[- 2])  #2nd last charprint(str6[-len(str6)])print(str6[:3])print(str6[-3:])### Methodsprint(str6.index("W"))`

## Video Day 6

`str1 = 'How are YOU I AM fine'#they are immutable - you cant edit them#str1 = 'h'  #TypeError: 'str' object does not support item assignmentstr1 = 'h'+str1[1:]print(str1)#functions are independent - print(), len(), input(), int(), str()#methods - they are functions written within a classprint(str1.isdigit())val1 = str(5)#input("Enter a number: ")if val1.isdigit():    val1  = int(val1)else:    print("Invalid number! setting val1 to zero")    val1 = 0print(val1)str2="Hello123"print(str2.isalnum())print(str1.upper())  #isupper()print(str1.lower())print(str1.title())print(str1)print(str1.split("o"))  #default split is done on blank spacel1 = str1.split()str2 = "|| ||".join(l1)print(str2)str3 = "Ioooamooofineooohowoooareoooyouooo?"str4 = " ".join(str3.split("ooo"))print(str4)occ = str3.find("ooo")print("Occurences = ",occ)occ = str3.count("ooo")print("Occurences = ",occ)start,end=0,len(str3)for i in range(occ):    po = str3.index('ooo',start,end)    print(po,end=" , ")    start = po+1print()# LISTl1 = []print(type(l1))print(len(l1))l1 = [4,"Hello",8.0,True,[2,4,5],"Fine"]print(type(l1))print(len(l1))print(len(l1))print(l1)#list is mutable (unlike str)l1= 444print(l1)print(l1+l1)print(l1 *3)for i in l1:    print(i)#list methods` ### Video for Class 7 here `#Tuple - immutable version listt1 = (2,2,4,6,8,10)  #packinga,b,c,d,e,f = t1#print(a,b,c,d,e,f)print(type(t1))print(len(t1))for i in t1:    print(i," - ",t1)print(t1[-2:])#t1 = 88print(t1.index(8))print(t1.count(2))t1= list(t1)t1.append(18)t1=tuple(t1)a=(5,88,1,77,99)b=(5,88,1,77,99)if a>b:    print(a)elif b>a:    print(b)else:    print("both are same")# List - linear ordered collectionl1=[4,6,8,10,12,8,10,12,8,0,8]l1.append(55)  #add element at the endprint(l1)l1.insert(3,90)l1.insert(3,70)print("2. ",l1)#element = 12if element in l1:    l1.remove(12)else:    print("Element doesnt exist")if l1.count(element)<1:    print("Element doesnt exist")print()print("3. ",l1)l1.pop(3)print("4. ",l1)print(l1.index(8))s,e=0,len(l1)for i in range(l1.count(8)):    inx = l1.index(8,s,e)    print(inx,end=", ")    s=inx+1print()print("5. ",l1)#copyl2 = l1  #deep copy - (giving another name)l3 = l1.copy()  #shallow copy (photocopy)print("After copy")print("L1 = ",l1)print("L2 = ",l2)print("L3 = ",l3)l1.append(101)l2.append(102)l3.append(103)print("After editing")print("L1 = ",l1)print("L2 = ",l2)print("L3 = ",l3)l1.reverse()print("Reverse: ",l1)l1.sort()print("Sort: ",l1)l1.sort(reverse=True)print("Sort R: ",l1)#stack - LIFO: add using append, remove: pop(-1)#queue - FIFO: append, pop(0)# 1,5,8,9,7#add 5 numbers from the usersum=0nums=[]for i in range(5):    num = int(input("Enter the number: "))    sum+=num    nums.append(num)print("Sum is ",sum)print("Printing values: ",nums)`

## VIDEO CLASS 8

`#  [[a,b,c],[x,y,z],[p,q,r]]master_list = []for i in range(3):    temp=[]    for j in range(3):        m=int(input("Enter the marks: "))        temp.append(m)    master_list.append(temp)print("Master list: \n",master_list)'''Assignment: Exten the above program to find highest marks for each subject and foreach students. Eg if the marks are: [[66, 77, 88], [98, 87, 76], [45, 65, 76]]Highest for subject 1 = 98                    2 = 87                    3 = 88Highest for Student 1 = 88                    2 = 98                    3 = 76'''# Dictionary - key:valuedict1 = {:,:, :,:}printtype(dict1[])print"Hello""Hola"(dict1)#deep copy#shallow copy(dict1.keys())print(dict1.items())i dict1.keys():    (i, dict1[i])a,b dict1.items():    (a,b)k dict1.items():    (k)stats = {:[,,,],:[,,,],:[,,,]}for in if "Virat"printdict3.pop()print`

## VIDEO CLASS 9

`#Sets#data structures - collections: String, List, Tuple, Dictionary#SETS - A B M O C - there is no order# doesnt allow duplicateset1 = {2,4,6,8}print(set1)#union intersection minusset2 = {6,8,10,12}#unionprint(set1.union(set2))print(set1 | set2)#intersectionprint(set1.intersection(set2))print(set1 & set2)#differenceprint(set1.difference(set2))print(set1 - set2)print(set2.difference(set1))print(set2 - set1)#symmetric difference#union of 2 differencesprint(set1.symmetric_difference(set2))print(set1 ^ set2)print(set1, set2)#update doesnt give new set, it changes the main setset1.update(set2)#union -> update# {intersection_update, difference_update, symm_diff_update}print(set1, set2)set3 = {2,4,10,12}# sets to list and to tupleset1 = tuple(set1)list(set1)set()` ## PYTHON SETS VIDEO

##### Learning Python with Sahasra – 2023
`print("HELLO")# 1. INSTALLATION - getting your computer ready# a. you can practice online at Google Colab (colab.reaserch.google.com)# b. install all software on your machine -## i. install Python : python.org and download the version of your choice## ii. you can program on Python but its very easy to do## iii. Another software to make it user friendly - IDE## integrated development environment - you can practice##  eg Pycharm (jetbrains.com), VS Code , Notebooks like Jupyter, etcprint("Hello how are you?")print('uyuyuiiugiub7y7 7t6t6vt87tovtotff87yvpyv')print(5+11)print('5+11=',5+11)num1 = 5  #num1 are called variablesnum2 = 11 #variable names are case sensitive, name should not start with a digit    #alphabets, numbers and underscore(_) - only these are allowedprint(num1 + num2)`

var1 = 5 #let’s take a variable called var1 and make it equal to 5
# number without decimal point – integer
#var1 is a variable of type integer
print(“var1”)
print(var1)
print(type(var1))

var1 = 5.0 #float – -inf to +inf with decimal point
print(type(var1))

var1 = 5j #complex (imaginary) – i
# square root of -25 = sq rt(25* -1) = 5j
print(type(var1))
print(5j * 5j)

# string – text (str)
var1 = “hello”
print(type(var1))

#5th basic data types – bool (boolean – 2 values: True / False)
var1 = True
print(type(var1))

#Functions for explicit conversion – convert data from given type to this:
# int(), float(), complex(), str(), bool()
var1 = int(“5”)
print(type(var1))

quantity =49
cost_pc = 51.89
total_cost = quantity * cost_pc
print(“Total quantity bought is”,quantity,”each one at a cost of”,cost_pc,”so the total cost is”,total_cost)
print(f”Total quantity bought is {quantity} each one at a cost of {cost_pc:.1f} so the total cost is {total_cost}”)

pl=”Rohit”
cn=”India”
pos=”captain”
print(f”Player {pl:<12} plays for {cn:^12} and is {pos:>20} of the team!”)

pl=”Mabwange”
cn=”Zimbabwe”
pos=”Wicket-keeper”
print(f”Player {pl:<12} plays for {cn:^12} and is {pos:>20} of the team!”)

num1 = int(input(“Enter first number to be added: “)) #default input will read as str
print(type(num1))
num2 = int(input(“Enter second number to be added: “))
print(type(num2))
print(num1+num2)

`var1 = 5var2 = 5.0var3 = "Hello"var4 = Truevar5 = 5j#arithmetic operationsvar1 = 15var2 = 4print(var1 + var2) #8print(var1 - var2) #print(var1 * var2)print(var1 / var2)print(var1 // var2)  #integer divison, the integer part of the divisonprint(var1 % var2) #modulo - remainderprint(var1 ** var2)# a,b = 30,6      30 % 20#Comparison operators: is ?? and answer will be boolvar1 = 15var2 = 4var3 = 15print(var1 > var2)print(var1 >= var3) #is it greater than or equal toprint(var1 < var2)print(var2 <= var3)print(var1 == var2)print(var1 != var2)#logical operators: input and output both are bool#and, or, notprint(var1 == var2  and var1 != var2)print(False and False)  #Falseprint(False and True)  #Falseprint(True and False)  #Falseprint(True and True)  # Trueprint(False or False)  #Falseprint(False or True)  #Trueprint(True or False)  #Trueprint(True or True)  # Truevar1 = 15var2 = 4var3 = 15print(var1 > var2 and var1 >= var3 or var1 < var2 or var2 <= var3 and var1 == var2 and var1 != var2)#T or Fprint("Hello \nHow are you \nI am fine thank you")# \n is for newlineprint("\\n is for newline")print("\\\\n is for newline")print("Hello",end=" ")print("How are you",end=" ")print("I am fine thank you",end="\n")#Conditional statementsnum1=0if num1 > 0:    print("Positive")    print("This is a positive number")    print("my 3rd line for positive number")elif num1 < 0:    print("Negative")    print("This is a negative number")    print("my 3rd line for negative number")else:    print("Its neither positive or nagtive")print("Thank you for using IF")num1 = int(input("Enter a number to be tested: "))if num1 %3==0:    print("Its divisible by 3")else:    print("Its not divisible by 3")`   `avg = 89if avg>=50:    print("Result: Pass")    #85: Grade A, 75> Grade B, >60: C, > 50-D    if avg>=85:        print("Grade: A")        if avg>=90:            print("Please collect your merit certificate!")            if avg>=95:                print("You win President's medal")    elif avg>=75:        print("Grade: B")    elif avg>=60:        print("Grade: C")    else:        print("Grade: D")else:    print("Result: Fail")# a & b=> which is greatera=45b=95if a>b:    print("A is greater than B")elif b>a:    print("B is greater than A")else:    print("They are equal")`

#Assignment:  take three numbers a,b,c and arrange them in increasing order without using any inbuilt function.

[Hint: Build on the last example shared]

`#INPUT: a,b,c=20,60,30#OUPUT: 20,30,60  (increasing order)a,b,c=80,60,30# a>b, b>c => clear# a>b, c>b => wrote additional code to find#b>a,`
`a, b, c=50,30,30  #increasing orderif a<b:    #print (f"{b} {a}")    if c<b: #b is greatest        if a<c:            print(f"{a}, {c}, {b}")        else:            print(f"{c}, {a}, {b}")    else: #c is greatest        print (f"{a}, {b}, {c}")else: #b<a    if c<b: #b is greatest        print(f"{c}, {b}, {a}")    else: #b is lowest        if a<c:            print (f"{b}, {a}, {c}")        else:            print(f"{b}, {c}, {a}")# 30<50=50# LOOPS - repeation#FOR loop - when we know exactly how many times to execute###  Range(a,b,c): generates values from a (inclusive) to b (exclusive) at steps of c# range(2,12,3): 2,5,8,11# range(3,12,3): 3,6,9# range(6,10): a&b. c is default 1:#range(5): b & a,c are deafult 0 and 1 respectively => 0,1,2,3,4for i in range(5):    print("Hello",i)for i in range(3,12,3):    print("Hi there", i)for i in range(2,12,3):    print("Hello there", i)print()for i in range(5):    print("*",end=" ")print()'''* * * * * * * * * * * * * * * * * * * * * * * * * '''for j in range(5):    for i in range(5):        print("*",end=" ")    print()#While Loop = based on condition- executes till its True#print("Hello")`
`# loops - for & while## For loop is used when you know exactly how many times to run the loopfor i in range(2,10,2):    print("* ",i)print("-------------")'''* * * * * * * * * * * * * * * * * * * * * * * * * '''for j in range(5):    for i in range(5):        print("*",end=" ")    print()print("-------------")for i in range(5):    print("* "*5)print("-------------")'''*  * * * * * * * * * * * * * * '''for j in range(5):    for i in range(j+1):        print("*",end=" ")    print()print("-------------")'''* * * * * * * * * * * * * * * '''for j in range(5):    for i in range(5-j):        print("*",end=" ")    print()print("-------------")'''* * * * *  * * * *   * * *    * *     * '''for j in range(5):    for x in range(j):        print(" ",end="")    for i in range(5-j):        print("*",end=" ")    print()print("--- Assignment ----------")'''    *     * *   * * *  * * * * * * * * * '''`
`#WHILEi=0while i<5:    print("hello")    i+=1print("Thank you")cont='y'while cont=='y' or cont=='Y':    print("Ok, printing some values...")    cont = input("Do you want to continue? (y for yes)")cont='y'while cont=='y' or cont=='Y':    sum=0    for i in range(3):        marks = int(input("Enter the marks: "))        sum+=marks    print("Total marks is",sum,"and average is",sum/3)    cont = input("Do you want to continue? (y for yes)")`
`import turtle#screen = turtle.getscreen()plot = turtle.Turtle()  #creates screenscreen = turtle.Screen()turtle.Screen().bgcolor("yellow")plot.forward(100)turtle.color("red")plot.right(90)plot.forward(100)plot.right(90)plot.forward(100)plot.right(90)plot.forward(100)##plot.right(45)plot.forward(100)plot.right(45)plot.forward(100)plot.right(135)plot.forward(100)plot.right(45)plot.forward(100)plot.backward(100)plot.left(45)plot.backward(100)plot.left(45)plot.forward(100)plot.right(45)plot.forward(100)## circleplot.circle(50)width = screen.window_width()height = screen.window_height()plot.penup()plot.goto(width/2,height/2)plot.pendown()plot.dot(30,"red")turtle.mainloop()  #keep displaying the screen# Forward, Backward, Left, Right` `#When the value is = to 16 and you want to add 5, you add 5 units to 16num1 = 18num2 = 5num3 = num1 + num2num4 = num1 * num2num5 = num1 / num2num6 = num1 - num2# 3 square + 4 square + 5 square + 6 square + 7 squarenum1 = 3num2 = 4num3 = 5num4 = 6num5 = 7result = num1 * num1 + num2*num2 + num3*num3 + num4*num4 + num5*num5print ("Final result = ",result)#read 2 values from the user and display val1 square + val2 squareval1 = input("Enter val1: ")val1 = int(val1)val2 = int(input("Enter val2: "))#when you read using input by default values are of type stringprint("Type = ", type(val1))print("Result=", val1*val1+val2*val2)#solve:  2x.x + 9x - 5 = 0# 1. Calculate Descriminant: b.b - 4.a.c = 81+40=121# 2. Root of D = 121 ** 0.5 = +/- 11# 3. x = (-b +/-D) / 2.a = (a) (-9+11)/4 = 0.5  (b) (-9-11)/4 = -5print("Solving a quadratic equation for x:")a=4b=2c=-6D = b**2 - 4*a*cprint("Finding Discriminant = ",D)if D==0:    print("This equation has only 1 solution and x = ",(-b/(2*a)))elif D<0:    print("This equation has imaginary solution")else:    sol1 = (-b+D**0.5)/(2*a)    sol2 = (-b - D ** 0.5) / (2 * a)    print(f"Solutions are: {sol1} and {sol2}")## x.x + 4.5x - 2.5 = 0 / (x+p)(x+q): p.q = -2.5 and p+q = 4.5#If the number given divides into 2 whole numbers, then it is even. If it is divided by two and it is a decimal or fraction, then it is odd.#If the number is divided by 5 and the value is a whole number, than it is a multiple of 5`
`# if <> - elif <> - elsenum = -35if num>0:    print("Its positive")    print("Its inside num > 0 condition")else:    print("Its not positive")    print("What else")print("This is another statement")# In a block (only IF, IF-ELSE or IF-ELIF-ELSE)num2 = -10if num2==0:    print("Its zero")elif num2<0:    print("Its negative")else:    print("Its positive")# WAP to check if a number is odd or even (I will do now)#Modify the above program to give a message is number is less than 0# Msg - "Invalid numbernum3 = -11if num3 %2==0:    print("Its even number")else:    print("Its odd number")`
num = 112
if num >0:
if num%2==0:
print(“Its positive and even”)
if num%4==0:
print(“Number is divisible by 4 also”)
else:
print(“Its negative and odd”)
elif num<0:
print(“Its negative”)
else:
print(“Neither positive nor negative”)

#loops
# for loop
#range(start, stop, increment)
#range(5,25,5) = 5,10,15,20
#counter = 51
#print(counter in range(5,25,5))
for counter in range(5,25,5):
print(counter)
##range(5,10) = (start=5,end=10, default increment=1) 5,6,7,8,9
#range(5) = (default start=0, end=5, default increment=1) = 0,1,2,3,4
num=10
for j in range(num):
for i in range(num):
print(“*”,end=” “)
print()

for j in range(num):
for i in range(j+1):
print(“*”,end=” “)
print()

for j in range(num):
for i in range(10-j):
print(“*”,end=” “)
print()

num=5
for j in range(1,11):
for i in range(1,11):
print(f”{i:<2} * {j:<2} = {j*i:<2},end=” “)
print()

# while
#WAP to input 5 numbers and find sum

sum=0
for i in range(5):
num = int(input(“Enter the number: “))
sum=sum+num
print(“Sum is “,sum)

#WAP to input numbers from the user till they want and find sum
sum=0
ch=‘y’
while ch==‘y’:
num = int(input(“Enter the number: “))
sum = sum + num
ch=input(“Enter y to accept more values, anyother key to stop:”)

print(“Sum is”,sum)

#Another implementation:
#WAP to input numbers from the user till they want and find sum
sum=0
while True:
num = int(input(“Enter the number: “))
sum = sum + num
ch=input(“Enter y to accept more values, anyother key to stop:”)
if ch!=‘y’:
break #command that will throw you out of the loop

print(“Sum is”,sum)