Swapnil Saurav

Python Class with Advait
#variables are used to store some values
var1 = 50
var2 = 100
print(var1 + var2)

var1 = 500
var2 = 100
print(var1 + var2)
#Basic

#datatypes: str, int, float, bool, complex
var1 = "HELLO" # str - you have the value in quoation
print(type(var1))
var1 = 100 #without any decimal part - integer(int)
print(type(var1))
var1 = 100.0 #float value
print(type(var1))
var1 = True #bool - False
print(type(var1))
var1 = 5j #complex (python)=imaginary (maths)
var2 = var1 * var1 #implicit conversion into complex since var1 is also complex
print(var2)
print(type(var1))
#
var1 = 100
var2 = 3.5
var3 = var1 + var2 #implicit conversion into float since var2 is a float
print()

str1 = "55"
str1 = int(str1) #explicit conversion
#int(), str(), float(), bool(), complex()
var1 = 0;var1 = bool(var1);print(var1); #False - bool

var1 = "";
var1 = bool(var1);
print(var1) ; #False - bool


len = float(input("Enter length of the rectangle: "))
breadth = float(input("Enter breadth of the rectangle: "))
area = len * breadth
print("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 = 50
var2 = 20
print(var1 + var2)
print(var1 - var2)
print(var1 * var2)
print(var1 / var2)
# ** power, 5 ** 4 => 5 * 5 * 5 * 5
print(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 division
print(10 / 3)
print("Integer Division = ",10 // 3)

# % Modulo - remainder
#20 / 3 = 6 + 2/3
print(20 % 3)
print(50 % 30) # 20 is remainder

# Comparison operators: compare the values (bigger/smaller)
# input as numeric and output is BOOL
var1 = 15
var2 = 25
print(var1 > var2) #false
#Arithematic operations: + - * / , **, // and % (modulo)
## input as numbers and output was numbers
#Comparison operators: input are the numbers / output - bool
# > >= < <= == !=
val1 = 30
val2 = 40
val3 = 30
print(val1 > val2) #is leftside val greater than rightside value?
print(val1 > val3) #False
print(val1 >= val3) #is val1 greater than or equal to? - True
print(val1 < val2) #
print(val1 <= val3) #
print(val1 == val3) # == is for asking question, are they equal?
print(val1 == val2) #False
print(val1 != val3) #False
print(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 - opposite

val1 = 30
val2 = 40
val3 = 30
print("==>: ",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 - in
print(5 in [2,4,5,6,8])

#bitwise operator - works by converting the numbers to boolean
# binary equivalent of 33 ?
print(bin(33)) #0b100001
print(int(0b101111011111))

# and (&) or (|) >> (right shift) << (left shift)
print(22 & 33) #0
print(33 & 22) #0
print(bin(33), bin(22))
## 33 = 100001
## 22 = 010110
## (&) 000000
## (|) 110111
print(int(0b110111)) #55
print(33 | 22) # 55

##
print(55 >>2)
# 55 = 110111 >> 1 = 11011 >> 1 = 1101
print(int(0b1101)) #13
print(55 << 2) # 110111 << 1 = 1101110 << 1 = 11011100

###
# if - checking conditions
val1 = 30
if val1 > 0:
print("Value is positive")
print("Positive Positive Positive")

print("Thank you for using my program")

# 300 pts
## ? 300
print("You win")
print("You lose")
print("Tied")

#TUPLE - immutable version of List
str1 = "hello"
str2 = 'Good evening' \
'How are you?'
str3 = '''Hello there
hope you are doing good
we shall meet soon'''
str4 = """I am fine
how 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 random
num = 55
attempt = 0
low,high = 1,100
while 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+1


str1 = "Hello"
print(str1[-1] , str1[len(str1)-1])
print(str1[1])
print("Length = ",len(str1))
# range(a,b,c) - a=initial value, b = ending value, c=increment
# range(2,14,3) - 2,5,8,11
print(str1[0:4], str1[:4])
print(str1[-5:-1], str1[:-1])
# llo
print(str1[2:5], str1[2:])
print(str1[-3:])

vowel_count = 0
str1 = "This is a Sample STATEMENT to test"
for i in str1:
#print("Hello: ",i)
if i in 'aeiouAEOIU':
vowel_count+=1
print(f"Total vowels in '{str1}' is {vowel_count}")

# strings are immutable
str1 = "Hello"
str1=str1[0]+'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 b
tot = str4.count('ab')
print("Total bs = ",tot)
srt = 0
for i in range(3):
print(str4.index('ab',srt))
srt=str4.index('ab',srt)+1

### LIST: linear ordered mutable collection
l1 = []
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 collection
l1 = [5,"Hello",False,[4,8,12]]
print(type(l1)) #<class 'list'>

#accessing (similar to strings)
print(l1[1][0])
print(type(l1[1]))
print(l1[-1][1])

l2 = [5.6,"Good Evening"]
print(l1+l2)
print(l2 * 3)
l3=[-1]*10
print(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 list
val1 = 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, value
l5.insert(1,400)
print("After addition: ",l5)
l5.pop(2) #input as position(index)
l5.remove(200) #takes values as input
print(l5)

### Stack & Queue ##
## Stack - LIFO data structure

stack=[]
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)) #element
print(l6.index(100, 2)) # element with start position
print(l6.index(100, 5,8)) # element with start and end pos
print("count = ",l6.count(200))

#Deep and Shallow copy
l7 = l6 #Deep copy - 2 names for same set of values
l8 = 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 collection
l6[0] = 110 #edit the value unlike string
print(l6)
l7 = [2,4,6,8,10]
print(l6+l7) #l6 and l7 retains original values
l6.extend(l7) #l6 will get l7 values
print(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 immutable

l6.append(66)
print(l6) #existing list got changed as it is mutable
#Sequential search
list1 = [12,14,8,6,10,20,4,10,16,18,2]
num = 10
count_num=0
count_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 Search
list1 = [12,14,8,6,10,20,4,10,16,18,2]
list1.sort()


num = 22
first = 0
last = len(list1)-1
isFound = False
while 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:
break

if 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 random
q_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 2023
months= ["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 = 3
print(months[3-1])
date = 21
print(str(date)+date_ending[date-1])
#Tuple - linear ordered immutable collection
t1 = ()
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) #packcing
print("type 1 = ",type(t1), len(t1))
print("4th member - ", t1[3])
print("2s = ",t1.count(2))
print("Position of 3 = ",t1.index(3))
t2 = (2,4,6,8)
a,b,c,d = t2 #unpacking
print(c,d,b,a)

# you can convert tuple to list and list to tuple
t2 = 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 pair
d1 = {}
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 keys
print(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 LA
for 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}
A.add(5)
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 duplicate
set1 = {'Apple','Grapes','Banana','Orange'}
print(type(set1))
set1.add('Cherry')
set2 = {"Pineapple","Mango","Apple","Orange"}
# two ways to remove
set1.remove("Banana")
set1.discard("Apple")
#set1.remove("Rose") - if value isnt there throws error
set1.discard("Rose") #doesnt throw error
print("1. Set1: ",set1)
set1.pop()
set1.update(set2) #union
print("2. Set1: ",set1)
set1.clear()
print("3. Set1: ",set1)
### SET FUNCTIONS ####
set1 = {'Apple','Grapes','Banana','Orange'}
set2 = {"Pineapple","Mango","Apple","Orange"}
#UNION
print("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-convertible
list1 = [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(“Whats your name?”)
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[0]==“not”:
print(“Both values are equal”)
else:
print(f”Variable {result[2]} with value {result[1]} 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()

# add and subtract

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

op1 = MyMasthsOps(10,5)
print(“Addition: “,op1.addition())
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”:“103”,“Item_Description”:“Bread Big packet”,“Cost”:7},
{“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=[]

def add_item(self):
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)
print(“Item has been added to your shopping cart!”)
else:
print(“This item is not available right now!”)

def display_items(self):
for item in self.list_of_items:
print(item)
def mainmenu(self):
print(“Main Menu:”)
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”)
choice=input(“Enter your choice: “)
return choice

if __name__ == ‘__main__’:
cart1 = Cart()
while True:
ch = cart1.mainmenu()
if ch==“1”:
cart1.add_item()
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)
b3 = Library(“Machine Learning”,“Advait”, 33.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)
create: def menu()
# 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:
print(“Answer is”,divide)
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:
print(“Answer is”,divide)
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
print(“Answer is”,divide)

## 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
print(“Answer is”,divide)

#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
print(“Answer is”,divide)
# Files – txt, csv
# r (read mode): only reading, file must be there
# 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 \\
# absolute path: will start with drive name
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:
reading: read(), readline(), readlines()
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”)

content = fileobj.read(10)
print(content)
#seek() – instruction to go to a perticular position
#fileobj.seek(1) #goes to the beginning of the content
content1 = fileobj.readline()
print(“Content after readline:\n,content1)

# read whats for H?
fileobj.seek(0)
content2 = fileobj.readlines()
print(content2)
character = “B”
for sentence in content2:
if sentence[0]==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()
”’
1. Read from the diary
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 = []
name=input(“Enter your name:”)
content.append(name)
city=input(“Enter your city: “)
content.append(city)
score=input(“Enter your score:”)
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)
csvreader = csv.reader(fileobj,delimiter=“,”)
total = 0
for each_row in csvreader:
total+=int(each_row[2])
print(“Total = “,total)
#CSV files reader / writer
# 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
readerobj = csv.reader(fileobj,delimiter=‘,’)
for row in readerobj:
print(row)
fileobj.close()
fileobj = open(filename)
#1. Show to Apple production for last 3 years
readerobj = csv.reader(fileobj,delimiter=‘,’)
print(“Apple production were:”)
for row in readerobj:
print(row[0],“:”,row[1])

fileobj.close()

#Highest production of Mango
fileobj = open(filename)
#2. Highest Mango production
readerobj = csv.reader(fileobj,delimiter=‘,’)
mango_high,year_high = –1,-1

linecount=0
for row in readerobj:
if linecount==0:
linecount+=1
else:
if int(row[3]) > mango_high:
mango_high=int(row[3])
year_high = row[0]
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)
print(f”{row[0]} which is written by {row[2]} is published by {row[1]})
”’
Install MYSQL from
https://dev.mysql.com/downloads/mysql/

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:
1. Server – dont forget the admin (root) password
2. Client – server host, database, database username and password
3. Database
4. Workbench – UI tool to connect to the Server
”’


import pymysql
connection = pymysql.Connection(host=“localhost”,database=“advaitdb”,user=“root”,password=“learnSQL”)
cursorobj = connection.cursor()

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

#create a new table:
table1 = ”’
Create Table advaitdb.Publishers(
PUBID INT PRIMARY KEY,
PUBNAME VARCHAR(15),
PUBCITY VARCHAR(15)
);
”’
#cursorobj.execute(table1) #creates the table
#create a new table:
table2 = ”’
Create Table advaitdb.BOOKS(
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)
print(f”{row[0]} which is written by {row[2]} is published by {row[1]})

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 here
I will be here for next 7 days
I 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 python
print("\\n is used to print newline in python")

# \\n will not print newline in python
print("\\\\n will not print newline in python")

str1 = "Hello You"
str2 = "There"
print(str1 + str2)
print(str1 *5)
for i in str1:
print("Hello")

#indexing
print(str1[2])
print("last element: ",str1[4])
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 class
import time
str1 = "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 sentence
para1 = "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=0
for 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+=1
print("Total vowesl = ",sum)
sum=0
for l in para1.lower():
if l=='a' or l=='e' or l=='i' or l=='o' or l=='u':
sum+=1
print("Total vowesl = ",sum)

sum=0
for l in para1.lower():
if l in 'aeiou':
sum+=1
print("Total vowesl = ",sum)

########## LIST
#LIST
#collection of linear ordered items
list1 = [1,2,3,4,5]
print(type(list1))
print("Size = ",len(list1))

print(list1[0])
print(list1[-1])
print(list1[3])
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[0]=10
print(l1)

l1.insert(2,15)
print(l1)

# Queue: FIFO
# Stack: LIFO

if 16 in l1:
l1.remove(16) #takes in value to remove
l1.remove(15)
print(l1)
l1.pop(1) #index
print(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 same
l3 = 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=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)

#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 immutable

tuple1 = (1,3,1,4,1,5,1,6)
print(type(tuple1))
print(len(tuple1))
print(tuple1.count(1))
print(tuple1.index(4))
print(tuple1[2])
for i in tuple1:
print(i)
t1 = list(tuple1)
t1.append(55)
t1=tuple(t1)
t2 = (2,4,6,8) #packing
#unpacking
a,b,c,d,e = t2
print(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(np.add(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 = [[5],[6],[4]]
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([[7],[35]])
#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
#
#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)

dataset1 = pd.read_csv(“D:/datasets/ongc.csv”)
print(dataset1)
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[0])
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[1])
data_df = data_df[data_df.Name !=“Virat”]
print(“After Drop”)
print(data_df)
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
print(usage_df.head(6))

# 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[0])
print(“Number of Columns in Combind tables: “,usage_device_df.shape[1])

hotels_df = pd.read_csv(“D:/datasets/gitdataset/hotel_bookings.csv”)
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 = [[“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[0])
print(data_df.loc[[0,2,4],[“Month”,“Runs Given Away”]])

#pd.read_csv(“https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/user_device.csv”)
device_df = pd.read_csv(“D:/datasets/gitdataset/user_device.csv”) #(272, 6)
print(device_df.shape)
usage_df = pd.read_csv(“D:/datasets/gitdataset/user_usage.csv”) #(240, 4)
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


link = “https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/baseball_game_logs.csv”

import pandas as pd
data_df = pd.read_csv(link)
print(data_df)
# Natural language processing
import pandas as pd
link = “https://raw.githubusercontent.com/swapnilsaurav/OnlineRetail/master/order_reviews.csv”
reviews_df = pd.read_csv(link)


”’
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()
print(reviews_df[‘review_comment_message’].head())

# Function to translate into English
#pip install googletrans==4.0.0-rc1
”’
from googletrans import Translator
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(“===================”)
print(reviews_df[‘review_comment_words’].head())

# Unigram, bigram, trigram

Learning with P
print('hello')

print(5 +3 )
print('5+3=', 5+3)

var1 = 53
print(type(var1)) #<class 'int'> integer
var1 = '53' # str - string
print(type(var1))

var1 = 53.0 #float
print(type(var1))

var1 = 53j #complex
print(type(var1))

var1 = False #
print(type(var1))

count_of_pens = 23 #variable names can only have alphabets, numbers, _
#variable shouldnt begin with a number
cost_each_pen = 21.23
total_cost = cost_each_pen \
* count_of_pens
print('Cost of each pen is',cost_each_pen,"so for",count_of_pens,"pens, "
"total cost would be",total_cost)

#f-string format string
print(f"Cost of each pen is {cost_each_pen} so for {count_of_pens} pens, total cost would be {total_cost:.1f}")

###################
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 = 5
num2 = 3
#Arithematic Operations
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2) #float output
print(num1 // num2) #integer division (double division)- integer (int)
print(num1 % num2) #remainder - modulo
print(num1 ** num2) #num1 to the power num2

#post office stamp problem for assignment
length = input("Enter length of the rectangle: ")
length = int(length)
print(type(length))
breadth = int(input("Enter breadth of the rectangle: "))
area = length * breadth
perimeter = 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 value
val1=34
val2=34
print("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 bool
print(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 False
print(not val1==val2)

#membership operator: in, not in
print( 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 + marks3
avg = total / 3

print(f"Total marks obtained is {total} and the average is {avg:.2f}")

#Conditional
num1 = -90
if 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.1
if 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 = 78
if num1%2==0:
print("Even")
else:
print("Odd")

age=21
nationality = "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,12

for i in range(3,16,3):
print("HELLO")
print("i = ",i)
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=5
m=1
for 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 condition
i=1
while i<=10:
print(i)
i+=1

#print hello untill user wants
ch='y'
while ch=='y':
print("HELLO")
ch=input("Press y to continue, anyother key to stop: ")
import random
num = random.randint(1,100)
print("==> ",num)
l1="="
total_attempts,max,min=0,0,9999
n=250000
pc = n//100
for 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,9999
n=250000
pc = n//100
num = 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+1

print("Average number of attempts it took: ",total_attempts/n)
print("Maximum attempt:",max," and minimum attempt:",min)
#Strings
str1 = 'Hello'
str2 = "How are you?"
str3 = """I am fine
I am great
I 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 string
str6 = "What's your name?"
print(str6[0])
print(str6[2])
print(len(str6))
print(str6[len(str6) - 1]) #last char
print(str6[len(str6) - 2]) #2nd last char
print(str6[- 1]) #last char
print(str6[- 2]) #2nd last char
print(str6[-len(str6)])

print(str6[:3])
print(str6[-3:])

### Methods
print(str6.index("W"))


str1 = 'How are YOU I AM fine'
#they are immutable - you cant edit them
#str1[0] = 'h' #TypeError: 'str' object does not support item assignment
str1 = 'h'+str1[1:]
print(str1)

#functions are independent - print(), len(), input(), int(), str()
#methods - they are functions written within a class
print(str1.isdigit())

val1 = str(5)#input("Enter a number: ")
if val1.isdigit():
val1 = int(val1)
else:
print("Invalid number! setting val1 to zero")
val1 = 0
print(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 space
l1 = 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+1
print()

# LIST
l1 = []
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[4]))
print(l1[4][1])
#list is mutable (unlike str)
l1[0]= 444
print(l1)

print(l1+l1)
print(l1 *3)
for i in l1[4]:
print(i)

#list methods
#Tuple - immutable version list

t1 = (2,2,4,6,8,10) #packing
a,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[2] = 88
print(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 collection
l1=[4,6,8,10,12,8,10,12,8,0,8]
l1.append(55) #add element at the end
print(l1)
l1.insert(3,90)
l1.insert(3,70)
print("2. ",l1)

#
element = 12
if 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+1
print()
print("5. ",l1)

#copy
l2 = 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 user
sum=0
nums=[]
for i in range(5):
num = int(input("Enter the number: "))
sum+=num
nums.append(num)
print("Sum is ",sum)
print("Printing values: ",nums)

#  [[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 for
each students. Eg if the marks are: [[66, 77, 88], [98, 87, 76], [45, 65, 76]]
Highest for subject 1 = 98
2 = 87
3 = 88
Highest for Student 1 = 88
2 = 98
3 = 76
'''

# Dictionary - key:value
dict1 = {:,:, :,:}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"
print
dict3.pop()
print
#Sets
#data structures - collections: String, List, Tuple, Dictionary
#SETS - A B M O C - there is no order
# doesnt allow duplicate

set1 = {2,4,6,8}
print(set1)
#union intersection minus
set2 = {6,8,10,12}
#union
print(set1.union(set2))
print(set1 | set2)
#intersection
print(set1.intersection(set2))
print(set1 & set2)

#difference
print(set1.difference(set2))
print(set1 - set2)
print(set2.difference(set1))
print(set2 - set1)

#symmetric difference
#union of 2 differences
print(set1.symmetric_difference(set2))
print(set1 ^ set2)
print(set1, set2)

#update doesnt give new set, it changes the main set
set1.update(set2)

#union -> update
# {intersection_update, difference_update, symm_diff_update}
print(set1, set2)

set3 = {2,4,10,12}

# sets to list and to tuple
set1 = tuple(set1)
list(set1)
set()
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, etc

print("Hello how are you?")
print('uyuyuiiugiub7y7 7t6t6vt87tovtotff87yvpyv')
print(5+11)
print('5+11=',5+11)
num1 = 5 #num1 are called variables
num2 = 11 #variable names are case sensitive, name should not start with a digit
#alphabets, numbers and underscore(_) - only these are allowed
print(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 = 5
var2 = 5.0
var3 = "Hello"
var4 = True
var5 = 5j
#arithmetic operations
var1 = 15
var2 = 4
print(var1 + var2) #8
print(var1 - var2) #
print(var1 * var2)
print(var1 / var2)
print(var1 // var2) #integer divison, the integer part of the divison
print(var1 % var2) #modulo - remainder
print(var1 ** var2)

# a,b = 30,6 30 % 20

#Comparison operators: is ?? and answer will be bool
var1 = 15
var2 = 4
var3 = 15
print(var1 > var2)
print(var1 >= var3) #is it greater than or equal to
print(var1 < var2)
print(var2 <= var3)
print(var1 == var2)
print(var1 != var2)

#logical operators: input and output both are bool
#and, or, not
print(var1 == var2 and var1 != var2)
print(False and False) #False
print(False and True) #False
print(True and False) #False
print(True and True) # True

print(False or False) #False
print(False or True) #True
print(True or False) #True
print(True or True) # True
var1 = 15
var2 = 4
var3 = 15
print(var1 > var2 and var1 >= var3 or var1 < var2 or var2 <= var3 and var1 == var2 and var1 != var2)
#T or F
print("Hello \nHow are you \nI am fine thank you")
# \n is for newline
print("\\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 statements
num1=0
if 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 = 89
if 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 greater
a=45
b=95
if 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 order
if 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,4
for 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 loop
for 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 ----------")
'''
*
* *
* * *
* * * *
* * * * *
'''

#WHILE
i=0
while i<5:
print("hello")
i+=1

print("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 screen
screen = 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)

## circle
plot.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 16
num1 = 18
num2 = 5
num3 = num1 + num2
num4 = num1 * num2
num5 = num1 / num2
num6 = num1 - num2

# 3 square + 4 square + 5 square + 6 square + 7 square
num1 = 3
num2 = 4
num3 = 5
num4 = 6
num5 = 7
result = num1 * num1 + num2*num2 + num3*num3 + num4*num4 + num5*num5
print ("Final result = ",result)

#read 2 values from the user and display val1 square + val2 square
val1 = input("Enter val1: ")
val1 = int(val1)
val2 = int(input("Enter val2: "))
#when you read using input by default values are of type string
print("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 = -5
print("Solving a quadratic equation for x:")
a=4
b=2
c=-6
D = b**2 - 4*a*c
print("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 <> - else
num = -35
if 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 = -10
if 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 number
num3 = -11
if 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)
Machine Learning with Python – 01M0
print('5+3=',5+3)  #comment 1
#practice day 1
var1 = 45
print(type(var1)) #<class 'int'> integer
# we have 5 basic types of data (datatypes)

var1=55.0
print(type(var1)) #<class 'float'>

var1 = 3j
print(type(var1)) #<class 'complex'>
print(3j * 3j) #(-9+0j)

var1="Hello"
print(type(var1)) #<class 'str'> string

var1=True #False
print(type(var1))

quantity = 53
price = 119.77
total_cost = quantity * price
#The total cost of 50 pens costing 119 is total_cost
print("The total cost of",quantity,"pens costing",price,"is",total_cost)
#format string - f string
print(f"The total cost of {quantity} pens costing {price} is {total_cost:.2f}")

name1 ="Rohit";country="India"
position="Captain"
print(f"Player named {name1:.<12} plays for {country:X^15} and he is {position:>15} of the team")

name1 ="Mangwabate"
country="Zimbabwe"
position="Wicket-keeper"
print(f"Player named {name1:<12} plays for {country:^15} and he is {position:>15} of the team")

var1,var2 = 50, 60
print("I am here");print("Hello \\\n Ok \tfine",end=". ")
print("How are you?" );

#str, float, int, bool, complex
# \ is called escape character
num1 = 55
name1 = "Sachin"
#whenever you read as input, the data type will always be string
name2 = input("Enter your name: ")
print(name2)
num2 = input("Enter radius: ")
num2 = int(num2)
print(num2)
area = 3.14*num2*num2
print("Area = ",area)

# + / - *
# // (integer division - this will give you only integer part of the division)
# ** power
# %(modulo -remainder)
num1 = 13
num2 = 5
#Arithematic/math operations
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2) #output wll always be float
print(num1 // num2) #output will always be int
print(num1 ** num2) # 10 to the power 5
print(num1 % num2) #modulo -
#logical operators: Input is bool values and output is also bool: and or not
#and - even if one value is false it will give you false
#or - even if one value is True it will give you true
#not - opposite: not True = False
print(True and False)
print(False or False)
print(not False)
num1 = 9
num2 = 13
print("Logical operator")
print(num1 > num2 or num1 < num1 and num2 == num1 or num1 != num2 or num1!=num2)
#(T)


#comaprison operators: < > <= >= == != : True/False
num1 = 9
num2 = 13
print("is num1 equal to num2? ",num1==num2)
print("is num1 not equal to num2? ",num1!=num2)
print("is num1 greater than num2? ",num1>num2)
print("is num1 greater than or equal to num2? ",num1>=num2)
print("is num1 less than num2? ",num1<num2)
print("is num1 less than or equal to num2? ",num1<=num2)

r=5
pi=3.14
print("Radius = ",pi*r**2)
# is 71 divisible by 9 ?
print(71%9)

####################
#is x divisible by y or not?
#conditions - they are used to check if its condition 1 or 2
# if to check conditions followed by Conditional or logical- they only
# give you True or False as output
x = 72
y = 9
if x%y==0:
print(f"{x} is perfectly divisible by {y}")
print("PERFECT DIVISIBLE")
else:
print(f"{x} is NOT divisible by {y}")
num1 = 0
if num1 >0:
print("Its positive")
else:
print("Its not positive")

num1 = 0
if num1 >0:
print("Its positive")
elif num1<0:
print("Its negative")
else:
print("Its not positive")

sum=448
avg=sum/5
print("AVG = ",sum/5)
#if avg>90 - grade A
# 80-90 - grade B # 70-80 - grade C # 60-70 - grade D
# 50-60 - grade E #40-50" grade F #<40 - Fail
if avg>=90:
print("PASS")
print("Grade = A")
elif avg>=80:
print("PASS")
print("Grade = B")
elif avg >=70:
print("PASS")
print("Grade = C")
elif avg >= 60:
print("PASS")
print("Grade = D")
elif avg >=50:
print("PASS")
print("Grade = E")
elif avg>=40:
print("PASS")
print("Grade = F")
else:
print("Grade = Failed")

#Nested conditions
if avg>=40:
print("PASS")
if avg >= 90:
print("Grade = A")
if avg>=95:
print("You win President's medal!")
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")

num1,num2,num3=10,15,20
if num1>=num2:
print(f"{num1} >= {num2}")
else:
print(f"{num2} >= {num1}")
#Repeating - loops in programming language
# range(a,b,c): a-start number (including), b-end number (excluding), c-increment
range(3,15,4) # 3, 7, 11,
range(3,7) # c is default 1: 3,4,5,6
range(4) #a is default 0, c is default 1: 0,1,2,3

# there are 2 ways loops are implemented in Python: FOR / WHILE
#for - when you know exactly how many times to run
for counter in range(1,11):
print(counter)
#odd numbers between 1 and 10
for i in range(1,11,2):
print(i)
# even numbers between 1 and 10
for i in range(2, 11, 2):
print(i)

for i in range(5):
print("*")

for i in range(5):
print("*",end=' ')
print("\n\n")
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
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()

'''
* * * * *
* * * *
* * *
* *
*
'''
'''
1* 1=1 2* 1=2 ... 10*1=10
...
1*10=10 2* 10=20 ... 10*10
'''
for n in range(1,11):
for m in range(1,11):
print(f"{m:>2} * {n:>2} = {n*m:>3}",end=" ")
print()

#while - when you until what condition
num = 51
isPrime = True
for i in range(2, num):
if num % i == 0:
isPrime = False
break
if isPrime:
print("Its a prime number ")
else:
print("Its not a prime number ")

# print prime numbers between 1000 and 5000
start, end = 1000, 5000
for k in range(start, end + 1):
isPrime = True
for i in range(2, k):
if k % i == 0:
isPrime = False
break
if isPrime:
print(k, end=" , ")

### WHILE LOOP
#print numbers from 1 to 10
i = 1
while i <=10:
print(i)
i+=1

choice = True
while choice:
print("Hello")
ch = input("Press n to stop")
if ch=='n':
choice = False


while True:
print("Hello")
ch = input("Press n to stop")
if ch == 'n':
break
#Strings
str1 = 'Hello'
str2 = "Hi there"
str3 = '''Hi there
how are you
Where are you?'''
str4 = """I am fine
I am here
How are you"""
print(str4)
print(str1 + str2)
print(str1 *3)

for i in str1:
print(i)

print(str1[2])
#str1[1] = "B"
print(str1[4], str1[-1])
print(str1[0],str1[-5])
print(str1[:3])
print(str1[-3:])

str1= "Hello How ARE YOU"
print(str1.isalnum())
num1 = input("Enter a number: ")
if num1.isdigit():
int(num1)
print(num1)
else:
print("Invalid number")

str2= ' '
print(str2.isspace())
print(str2.islower())
print(str2.isupper())

str3 = "Hello HI There"
print(str3.lower())
print(str3.upper())
print(str3.title())
str4 = str3.replace("h","ABC",1)
print(str4)
str4 = str3.split('e')
print(str4)
str5 = "e".join(str4)
print(str5)
print("HI" in str3)
print(str3.find("HI"))
print(str3.count('e'))
#Sets
#data structures - collections: String, List, Tuple, Dictionary
#SETS - A B M O C - there is no order
# doesnt allow duplicate

set1 = {2,4,6,8}
print(set1)
#union intersection minus
set2 = {6,8,10,12}
#union
print(set1.union(set2))
print(set1 | set2)
#intersection
print(set1.intersection(set2))
print(set1 & set2)

#difference
print(set1.difference(set2))
print(set1 - set2)
print(set2.difference(set1))
print(set2 - set1)

#symmetric difference
#union of 2 differences
print(set1.symmetric_difference(set2))
print(set1 ^ set2)
print(set1, set2)

#update doesnt give new set, it changes the main set
set1.update(set2)

#union -> update
# {intersection_update, difference_update, symm_diff_update}
print(set1, set2)

set3 = {2,4,10,12}

# sets to list and to tuple
set1 = tuple(set1)
list(set1)
set()
#List - linear ordered mutable
list1 = []
print(list1)
print(type(list1))
list1 = [2,4,6.5,"Hello",True,[2,8,12]]
print("Number of elements = ",len(list1))
print(list1[1])
print(type(list1[-2]))
print(type(list1[-1]))

#sum and avg of 5 marks
list_of_marks=[]
sum = 0
for i in range(0):
m=int(input("Enter marks: "))
list_of_marks.append(m)
sum+=m
print("Sum = ",sum)
print("List of marks = ",list_of_marks)

## 2 ways to add values to an existing list: append, insert
list_of_marks.insert(1,100)#index, value
print("List of marks = ",list_of_marks)
list_of_marks.insert(1,80)
print("List of marks = ",list_of_marks)
list_of_marks.insert(1,90)
print("List of marks = ",list_of_marks)
list_of_marks.insert(1,30)
print("List of marks = ",list_of_marks)
list_of_marks.insert(1,40)
print("List of marks = ",list_of_marks)

list_of_marks.sort(reverse=True)
print("(Sort)List of marks = ",list_of_marks)
list_of_marks.reverse()
print("(Reverse)List of marks = ",list_of_marks)

num_to_delete = 80
if num_to_delete in list_of_marks:
list_of_marks.remove(num_to_delete)
print("(remove)List of marks = ",list_of_marks)
list_of_marks.pop(3)
print("(pop)List of marks = ",list_of_marks)
num_to_delete = 80
if list_of_marks.count(num_to_delete) >0:
list_of_marks.remove(num_to_delete)
print("(remove)List of marks = ", list_of_marks)
list1 = [10,3,4,5,3,4,6,3,7,8,3,6]
print(list1.count(3))
print(list1.index(3)) #index(element,start,end)

#index of all the values in the list:
element_search = 3
inx_found=0
for i in range(list1.count(element_search)):
print(list1.index(element_search, inx_found), end=" ,")
inx_found = list1.index(element_search, inx_found) + 1
print()
list1 = [1,3,5,7]
list2 = list1 #they are same , just have 2 names
list3 = list1.copy() #copy - creates a different copy
print("1. List 1 = ",list1)
print("1. List 2 = ",list2)
print("1. List 3 = ",list3)
list1.append(15)
list2.remove(5)
list3.append(19)

print("2. List 1 = ",list1)
print("2. List 2 = ",list2)
print("2. List 3 = ",list3)

# TUPLE - immutable form of List
t1 = ()
print(type(t1))

t1 = (1,)
print(type(t1))

t1=list(t1)
t1.append(40)
t1 = tuple(t1)
#list, tuple and sets are all 3 inter convertible
#advantage of tuple -its fast to access
t2 = (1,2,3) #packing
a,b,c = t2 #unpacking
print(a,b,c)

#Dictionary - uses its own key to track values
#list, tuple, sets - linear

list1 = [2,3,4,5,2,3,4,2,3,2]
list1=list(set(list1))
print(list1)

#Dictionary: key:value pairs
d1 = {}
print(type(d1))
d1 = {4,5}
print(type(d1))

d1 = {4:"Sachin","Matches":5}
print(type(d1))
print(d1)
print("Keys: ",d1.keys())
print("Values: ",d1.values())
print("(Key, Value): ",d1.items())

print(d1['Matches'])
d2={'City':'Mumbai'}
d1.update(d2)
print(d1)

d2={'City':'Hyderabad'}
d1.update(d2)
print(d1)

#deep v shallow copy
d3 = d1 # deep - creates another name for d1
d4 = d1.copy()
print("D1 = ",d1)
print("D3 = ",d3)
print("D4 = ",d4)
d1.update({'Sports':'Cricket'})
print("D1 = ",d1)
print("D3 = ",d3)
print("D4 = ",d4)
#remove a member: pop(), popitem()
d1.pop(4) #pop takes key as input
print("D1 after pop: ", d1)
d1.popitem() #last added value is removed - remeber last added is not same as last updated
print("D1 after popitem: ", d1)

print(" iterating through keys: ")
for i in d1.keys():
print(i)
print(" iterating through values: ")
for i in d1.values():
print(i)

print(" iterating through items")
for i in d1.items():
print(i)
for i,j in d1.items():
print(f"Keys = {i} and value = {j}")

women = {101:"Renuka", 103:"Smriti",105:"Harmanpreet",107:"Deepti"}
men = {102:"Sachin",104:"Virat",106:"Rohit"}
all ={211:'Steve',222:'Warner'}
all.update(women)
all.update(men)
print(all)
for key,val in all.items():
if key in women.keys():
print(f"{val} plays in women's team")
elif key in men.keys():
print(f"{val} plays in men's team")
else:
print(f"{val} neither part of mens or womens team")
# SET - sets - linear unordered mutable collection - doesnt allow duplicate
set1 = {'Apple','Grapes','Banana','Orange'}
print(type(set1))
set1.add('Cherry')
set2 = {"Pineapple","Mango","Apple","Orange"}
# two ways to remove
set1.remove("Banana")
set1.discard("Apple")
#set1.remove("Rose") - if value isnt there throws error
set1.discard("Rose") #doesnt throw error
print("1. Set1: ",set1)
set1.pop()
set1.update(set2) #union
print("2. Set1: ",set1)
set1.clear()
print("3. Set1: ",set1)
### SET FUNCTIONS ####
set1 = {'Apple','Grapes','Banana','Orange'}
set2 = {"Pineapple","Mango","Apple","Orange"}
#UNION
print("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-convertible
list1 = [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")
 
# Basic data types (stores only 1 value) - int, float, str,bool and complex
# Collections (stores multiple values - 1D) - list, tuple,dictionary, set
# functions - own functions - user defined functions
# print(), input(), type(), int(), str(), len() : in-built functions (developers of python have already written for us)
# we will learn to write our own functions

#first part of writting function is to Define the meaning- function
def mytext(val1, val2,val3):#required positional argument
print("Hello How are you today?")
print("Where are you going?")
print("I am fine.",val1)

def mytext2(val1=0, val2=0,val3=9):#default positional argument
print("Hello How are you today?")
print("Where are you going?")
print("I am fine.",val1)
print("Values are: ",val1,val2,val3)
#demo keyword (non-positional) arguments
def mytext3(val1, val2,val3):#default positional argument
print("Hello How are you today?")
print("Where are you going?")
print("I am fine.",val1)
print("Values are: ",val1,val2,val3)


#default argument (non-required) & keyword argument (non-positional)
mytext(5,10,0)
print("Done with one time calling now calling second time")
mytext2(20,4,10)
mytext2(20,4)
mytext2(10,5,1)
mytext3(val3=10,val1=9,val2=8)
mytext3(100, val3=9,val2=8)
#print()
# numpy, pandas (Multi-D)

def isPositive(val1):
#result = "Positive" # "+ve" / 1
if val1 >0:
return 1
else:
return 0 #print("Its not Positive")

res = isPositive(100)
if res==1:
print("Its positive, now lets go ahead building our logic")
else:
print("STOP! STOP! STOP!")

isPositive(-100)
isPositive(90)
def myfun1(val1):  #Required positional argument
print(val1)

myfun1(10)

def myfun2(val1,val2,val3): #Required positional argument
print(val1, val2,val3)

myfun2(10,30,20)

# Default argument
def myfun3(val1,val2=100,val3="New York"): #Required positional argument
print(val1, val2,val3)
return val1+val2

myfun3(10,30)

## keywords - (non-positional)
result = myfun3(val2=99,val3=77,val1=44)
print("Result = ",result)

## single function to perform perimeter of triangle, square, pentagon, hexagon

def calcPerimeter(s1=0,s2=0,s3=0,s4=0,s5=0,s6=0):
if s1==0:
return "You have not provided any value!"
elif s2==0:
return "Perimeter of a line is the same value which is "+str(s1)
elif s3==0:
print("We cant have a closed shape with 2 only sides!")
elif s4==0:
print("Its a Triangle! Perimeter is",s1+s2+s3)
elif s5==0:
if s1==s2 and s2==s3 and s3==s4:
print("its a square with perimeter",s1*4)
elif s1==s2 and s4==s3:
print("Its a rectangle with Perimeter",2*(s1+s3))
else:
print("Its an irregular 4 sides shape with perimeter",s1+s2+s3+s4)
elif s6==0:
print("Its a pentagon with perimeter",s1+s2+s3+s4+s5)
else:
print("Its a hexagon with perimeter",s1+s2+s3+s4+s5+s6)

result = calcPerimeter()
print(result)
result = calcPerimeter(5)
print(result)
calcPerimeter(6,8)
calcPerimeter(8,7,5,4,3,3)

def checkNum(val1):
if val1 <0:
return -1 #for negative
elif val1==0:
return 0 #zero value
else:
return 1 #positive

res = checkNum(100)
if res==-1:
print("Negative")
elif res==0:
print("Zero")
else:
print("Positive")

res = checkNum(-100)
if res==-1:
print("Negative")
elif res==0:
print("Zero")
else:
print("Positive")
list1 = []

class Book:

num_books = 0 #class level variable

# object level method
def say_hi(self,n):
self.name=n #self. indicates name is specific to object
print(“Hi…”)
Book.num_books+=1

# class level variable
# class level method
# object level variable

b1 = Book()
b2 = Book()
b1.say_hi(“Python”)
b2.say_hi(“Django”)
print(b1.num_books)
print(b2.num_books)
print(Book.num_books)
print(“b1.name = “,b1.name)
print(“b2.name = “,b2.name)
#Book.name
class Library:
def __init__(self, library):
self.library = library
def _method2(self): #declared as protected
return “I am in Library!!!”
def __method3(self): #private declaration – cant be accessed outside of this class
return “I am in Library by method 3!!!”
def get_libname(self):
return self.library
class Books(Library): #Books is a derived class of Library class (base class)
title_count = 0
#__init__ – this is automatically called when object is created
def __init__(self, title, author,libname=“XYZ Library”):
Library.__init__(self,libname)
self.title = title
self.author = author

Books.title_count+=1

#get author – object
def get_author(self):
return self.author
def get_title(self):
return self.title

#count of the book
@classmethod
def get_bookcount(cls):
return cls.title_count
class Sample:
def sample_method(self):
Library._method2(self) #protected will not show up but still callable
#protected concept exists but not strictly implemented

def sample_method3(self):
Library.__method3(self) #private members are not accessible

b1 = Books(“Python Programming”,“Swapnil”)
b2 = Books(“Data Science Programming”,“Snehil”,“PQR Library”)
b3 = Books(“Blockchain”,“Ojass”)
print(“Number of books in the library = “,b1.get_bookcount())
print(“Number of books in the library = “,b3.get_bookcount())
print(“Title of the book = “,b1.get_title())
print(“Title of the book = “,b2.get_title())
l1 = Library(“ABC Local Library”)
print(“Library name = “,l1.get_libname())
print(“B1 Library is: “,b1.get_libname())
print(“LIBNAME = “,b1.get_libname())
print(“Method2 by Books: “,b1._method2())
s1 = Sample()
print(“Call by Sample: “,s1.sample_method())
#print(“Call by Sample: “,s1.sample_method3()) – throws error
# as private members cant be accessed

#print(“Method2 by Books: “,b1.__method3())- throws error
# as private members cant be accessed

MASTERLIST = [{“ItemCode”: 101,“Item”:“Shirt”,“Price”:28.2},
{“ItemCode”: 102,“Item”:“Bag”,“Price”:18.2},
{“ItemCode”: 103,“Item”:“Book1”,“Price”:38.2},
{“ItemCode”: 104,“Item”:“Watch”,“Price”:58.2},
{“ItemCode”: 105,“Item”:“Shoes”,“Price”:128.2},
{“ItemCode”: 106,“Item”:“Laptop”,“Price”:1028.2}]
class ShoppingCart:
def __init__(self):
self.myshoppingcart = []

#add product to the cart
def add_prod(self):
each_item = {}
item_name = input(“Enter the product Name: “)
not_in_list = True
for items in MASTERLIST:
if item_name==items[“Item”]:
not_in_list = False
if not_in_list:
print(“Sorry, That Item is Out of Stock!”)
else:
item_size = input(“Enter the product Size: “)
item_color = input(“Enter the product Color: “)
item_quantity = int(input(“Enter the product Quantity: “))
each_item ={“Item”:item_name,“Size”:item_size,“Color”:item_color,“Quantity”:item_quantity}
self.myshoppingcart.append(each_item)
#print(self.myshoppingcart)
def display_prod(self):
print(“Item Size Color Quantity”)
for i in self.myshoppingcart:
for k,j in i.items():
print(f”{j:<10}, end=” “)
print()

def remove_prod(self):
item_name = input(“Enter the product name to remove: “)
not_in_list = True
for items in self.myshoppingcart:
if item_name == items[“Item”]:
self.myshoppingcart.remove(items)
not_in_list = False

if not_in_list:
print(“Sorry, That Item is not in your shopping cart!”)
else:
print(“Item is now removed from your shopping cart!”)

def generate_receipt(self):
print(“Item Size Color Quantity Price”)
print(“=======================================================”)
item_cost = 0
price = 0
grand_total = 0
for i in self.myshoppingcart:
for k,j in i.items():
for master_list in MASTERLIST:
if j==master_list[“Item”]:
price=master_list[“Price”]

print(f”{j:<10}, end=” “)
if k==“Quantity”:
item_cost = j*price
grand_total+=item_cost
print(f”{round(item_cost):<10}, end=” “)
print()
print(“——————————————————-“)

print(” TOTAL: $”+str(round(grand_total)))
print(“=======================================================”)

if __name__==“__main__”:
sc1 = ShoppingCart()
sc2 = ShoppingCart()
while True:
print(“1. View my cart \n2. Add to my cart\n3. Remove from my cart\n4. Generate My Receipt\n5. Exit”)
ch=input(“Enter your option: “)
if ch==“1”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
sc1.display_prod()
elif ch==“2”:
sc1.add_prod()
elif ch==“3”:
sc1.remove_prod()
elif ch==“4”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
sc1.generate_receipt()
elif ch==“5”:
break
else:
print(“Invalid option”)

DATABASE TUTORIAL

DESCRIPTIVE STATISTICS

Descriptive Statistics – Types of Data

 

Quantitative Data
Numeric Data
Continuous
(Weight, Temperature,
etc)
Ratio
Interval
Data
Discrete
Qualitative Data
Categorical
Nominal
(There is no order in the values): {M, F} {N,S,E,W}
Ordinal
(There is an order): {1,2,3,4,5} {Good, Average, Bad}
Text
Data
Audio

 

Video

 

UNIVARIATE – One Variable

 

•WEIGHT: FREQUENCY TABLE & HISTOGRAM
•MARKS: FREQUENCY TABLE & HISTOGRAM
•GENDER: BAR GRAPH / PIE CHART
•REGIONS: BAR GRAPH / PIE CHART
•COURSE RATING: BAR GRAPH / PIE CHART/LINE GRAPH (IN A PARTICULAR ORDER)
•TEMPERATURE: FREQUENCY TABLE & HISTOGRAM
•SALES: LINE GRAPH
 

 

Lecture Notes – I
text1 = 'Hello' \
'World'
text2 = "hi there"

text3 = '''How are you
where are you
what do you want?'''
text4 = """I am fine"""
#I am just trying to run few programs

print(text1,end=' ') #printing first text print("Hello")
print(text2)
print(text3)
print(text4)
'''this is a
multi line text
please ignore'''

print(type(True))

cost = 60
quantity = 212
total_cost = cost * quantity
print("Cost of each pen is $",cost,"so for ",quantity,"pens, its going to be $",total_cost)
print(f"Cost of each pen is $ {cost} so for {quantity} pens, its going to be $ {total_cost}")
print("Hellon\nhow are you?\nI am fine")
txt1 = "Hello"
a1 = 5
b1 = False
#user input- will provide the value
inp1 = input("Enter your name:")
print(inp1)
inp2 = int(input("Enter your age:"))
print(type(inp2))
print(inp2)

num1 = 10
num2 = 20
#ArithmeticOperations
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2)
print(num1 // num2) #integer division - ignores the decimal part
print(num1 ** num2) #power - exponent
print(num1 % num2) #mod (modulus) - remainder

#Comparison operators: < > <= >= == !=
# :input is anything but output is always bool value

#Logical operations: and or not
# :both input and output are bool value
#comparison operators - output is always Bool
## > < >= <= == !=
num1 = 56
num2 = 56
num3 = 57
print(num1 <= num2) # less than or equal - T
print(num1 <= num3) # T
print(num1 < num2) # F
print(num1 >= num2) #T
print(num1 > num2) #F
print(num1 > num3) #F
print(num1 == num2) #T
print(num1 != num2) #F

#Logical operators
# Today we will do operators and conditions
# I do only operators
#
# Today we will do operators or conditions
# I do only operators

# and or not
num1 = 56
num2 = 56
num3 = 57
print(num1 <= num2 and num1 <= num3 or num1 < num2 and num1 >= num2 or num1 > num2 and num1 > num3 or num1 == num2 and num1 != num2)
#T
#

print()
num1 = int(input("Enter a number: "))
print(type(num1))
#
# 1. Calculate area and perimeter of a rectangle with given sides
# 2. Calculate area and circumference of a circle with radius as input from the user

#conditional statements
num1 = -56
#ask you is it a positive number ?
if num1>0:
print("hello")
print("Yes its positive")
elif num1 <0:
print("Its negative")
else:
print("Its neither positive nor negative")

avg = 76

'''
avg>85 : Grade A
avg>70: Grade B
:avg >60: Grade C
avg >40: Grade D
<40: Grade E
'''
if avg >=85:
print("Grade A")
if avg >= 90:
print("You win special certificate")
if avg>95:
print("You get President's meddal")
elif avg>70:
print("Grade B")
elif avg>60:
print("Grade C")
elif avg>40:
print("Grade D")
else:
print("Grade E")

#get input of 3 numbers and find the largest and the smallest number
#loops - Keep repeating
# FOR - when you know how many times
# WHILE - untill the condition is true
#range(a,b,c): start = a, go upto b (excluding), c = increment
#range(3,19,4) = 3, 7, 11,15,
##range(3,9) (increment by default 1) - 3, 4,5,6,7,8
## range(4) (by default start=0, increment = 1)- 0,1,2,3
for i in range(5):
print("*",end=" ")

print("\n -------------- \n\n")
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for j in range(5):
for i in range(5):
print("*",end=" ")
print()

print("\n -------------- \n\n")
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for j in range(5):
for i in range(5):
print("*",end=" ")
print()

print("\n -------------- \n\n")
'''
*
* *
* * *
* * * *
* * * * *
'''
for j in range(5):
for i in range(j+1):
print("*",end=" ")
print()

print("\n -------------- \n\n")
'''
* * * * *
* * * *
* * *
* *
*
'''
for j in range(5):
for i in range(5-j):
print("*",end=" ")
print()

print("\n -------------- \n\n")
'''
* * * * *
* * * *
* * *
* *
*
'''
for j in range(5):
for i in range(j):
print("",end=" ")
for i in range(5-j):
print("*",end=" ")
print()
'''
*
* *
* ** *
* *
'''

sum=0
while True:
num1 = int(input("Enter a number (-999 to stop):"))
if num1==-999:
break #throw us out of the current loop
sum+=num1


print("Sum of the given numbers are: ",sum)


## check if prime number

while True:
num1 = int(input("Enter a number (0 to stop/negative numbers not allowed): "))
if num1 == 0:
break
if num1<0:
print("Invalid number")
continue
isPrime = True
for i in range(2,num1//2+1):
if num1 % i==0:
isPrime=False
break

if isPrime:
print(f"{num1} is a Prime number")
else:
print(f"{num1} is not a Prime number")

## generate if prime number
num1=0
while True:
#num1 = int(input("Enter a number (0 to stop/negative numbers not allowed): "))
num1+=1
if num1 == 0:
break
if num1<0:
print("Invalid number")
continue
isPrime = True
for i in range(2,num1//2+1):
if num1 % i==0:
isPrime=False
break

if isPrime:
print(f"{num1}")
ch=bool(input())
if ch!=False:
break

#read the marks of 5 subjects and print total and average

total = 0

while True:
for i in range(5):
marks = int(input("Enter the marks in subject "+str(i+1)+": "))
total+=marks

print(f"Total marks is {total} and average is {total/5:.2f}")
ch=bool(input())
if ch:
break
### Enter marks for 5 subjects for as long as user wants to repeat
while True:
sum = 0
for i in range(5):
marks = int(input("Enter your marks in subject "+str(i+1)+": "))
sum+=marks
print("Total marks obtained = ",sum)

ch=bool(input("Enter any key to stop:"))
#converting empty string to bool will result in
# False, anything will result in True
if ch:
break


########################
####
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 here
I will be here for next 7 days
I 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 python
print("\\n is used to print newline in python")

# \\n will not print newline in python
print("\\\\n will not print newline in python")

str1 = "Hello You"
str2 = "There"
print(str1 + str2)
print(str1 *5)
for i in str1:
print("Hello")

#indexing
print(str1[2])
print("last element: ",str1[4])
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 class
import time
str1 = "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 sentence
para1 = "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=0
for 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+=1
print("Total vowesl = ",sum)
sum=0
for l in para1.lower():
if l=='a' or l=='e' or l=='i' or l=='o' or l=='u':
sum+=1
print("Total vowesl = ",sum)

sum=0
for l in para1.lower():
if l in 'aeiou':
sum+=1
print("Total vowesl = ",sum)

########## LIST
#LIST
#collection of linear ordered items
list1 = [1,2,3,4,5]
print(type(list1))
print("Size = ",len(list1))

print(list1[0])
print(list1[-1])
print(list1[3])
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[0]=10
print(l1)

l1.insert(2,15)
print(l1)

# Queue: FIFO
# Stack: LIFO

if 16 in l1:
l1.remove(16) #takes in value to remove
l1.remove(15)
print(l1)
l1.pop(1) #index
print(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 same
l3 = 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=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)

#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


#
num = 51
isPrime = True
for i in range(2,num):
if num%i==0:
isPrime = False
break
if isPrime:
print("Its a Prime number")
else:
print("Its not a prime number")

###
start1,end1= 500,5000
for j in range(start1,end1+1):
isPrime = True
for i in range(2, j):
if j % i == 0:
isPrime = False
break
if isPrime:
print(j,end=", ")

# while loop
#While loop
i=1
while i<=10:
print(i)
i+=1

ch=True
while ch:
num=int(input("Enter a number: "))
if num%2==0:
print("Its an even number!")
else:
print("Its an odd number")
choice=input("Do you want to continue (press n to stop):")
if choice=='n':
ch=False


while True:
num=int(input("Enter a number: "))
if num%2==0:
print("Its an even number!")
else:
print("Its an odd number")
choice=input("Do you want to continue (press n to stop):")
if choice=='n':
break


import random

n=1
total_attempts = 0
max=0
min=99999999
for i in range(n):
comp_num = random.randint(1,100)
print("Random: ",comp_num)
attempt = 0
while True:
guess = int(input("Guess the number: "))
#guess = random.randint(1, 100)
attempt+=1
if guess == comp_num:
print("Congratulations! You have guessed it correctly. Attempts = ",attempt)
total_attempts+=attempt
if attempt>max:
max=attempt
if attempt <min:
min=attempt
break
elif comp_num > guess:
print("Sorry! You have guessed low!")
else:
print("Sorry! You have guessed high")

print("Avg attempts = ",total_attempts/n)
print("Max attempts =",max,"and Minimum attempts = ",min)



'''
Avg attempts = 99.384
Max attempts = 529 and Minimum attempts = 1
'''

#######
import random

n=500
total_attempts = 0
max=0
min=99999999
for i in range(n):
comp_num = random.randint(1,100)
print("Random: ",comp_num)
attempt = 0
low,high=1,100
while True:
#guess = int(input("Guess the number: "))
guess = random.randint(low, high)
attempt+=1
if guess == comp_num:
print("Congratulations! You have guessed it correctly. Attempts = ",attempt)
total_attempts+=attempt
if attempt>max:
max=attempt
if attempt <min:
min=attempt
break
elif comp_num > guess:
print("Sorry! You have guessed low!")
low= guess+1
else:
print("Sorry! You have guessed high")
high=guess-1

print("Avg attempts = ",total_attempts/n)
print("Max attempts =",max,"and Minimum attempts = ",min)

'''
Avg attempts = 7.522
Max attempts = 15 and Minimum attempts = 1
'''
txt1 = "HELLO"
txt2 = 'How are yOU?'
# what's your name?
print("what's your name?")
print('He asked,"Where are you?"')

#He asked,"What's your name?"
print('''He asked,"What's your name?"''')
print("He asked,\"What's your name?\"")

txt3 = '''How are you?
Where are you?
what do you want?'''
txt4 = """I am fine
I am here
I want nothing"""
print(txt4)

for ch in txt1:
print(ch)
print(txt1+" "+txt2)
print(txt1*10)

#indexing
print(txt1[0])
print(txt1[4])
length = len(txt1)
print("Total characters = ", length)
print(txt1[length-1])
print(txt1[-1])
print(txt1[length-2])
print(txt1[length-3])
print(txt1[-3])
print(txt1[0]+txt1[1]+txt1[2])
print(txt1[0:3])
print(txt1[0:4])
print(txt1[1:4])
print(txt1[2:5])
print(txt1[-3:])
print(txt1[:])

#METHODS ARE INBULT FUNCTIONS OF A CLASS
print(txt1.lower())
print(txt2.upper())
#String - class
# functions specific to classes are called methods

str1 = "O I see I am fine see you are NICE"
str2 = "hello hi"
print(str1.islower())
print(str2.islower())
str3 = str2.upper()
print(str3)
print(str3.isupper())

num1 = input("Enter a number: ")
if num1.isdigit():
num1=int(num1)
else:
print("Invalid number as input, setting it it zero")
num1 = 0
print("Num1 = ",num1)

#create username with only alphabets and numbers
username = input("Enter your username: ")
if username.isalnum():
print("Username accepted")
else:
print("Invalid Username!")

print(str1.upper())
print(str1.lower())
print(str1.title())

str1 = "O I see I am fine I see I you are NICE"
print("i" in str1)
print(str1.find('I'))
print(str1.count('I'))
print(str1.find('I',3))
print(str1.find('I',9))

char = "ee"
num_pos = str1.count(char)
print("Total times char is present = ",num_pos)
print("Their positions are: ",end=" ")
start_pos = 0
for i in range(num_pos):
nxt_val = str1.find(char,start_pos)
print(nxt_val,end= " , ")
start_pos = nxt_val+1

print(str1.replace("ee","EE"))

words = str1.split("I")
print(words)
str6 = "I".join(words)
print(str6)
#LIST
l1 = [5,4,"Hello",99,False,100,[20,10, 5]]
print(type(l1))
print(len(l1))
l2 =l1[-1]
print(l2[1])
print(l1[-1][2])
print(l1[1:4]) #4, "hello" 99
print("Only Integer values fom List")
for i in l1:
if str(i).isdigit():
print(i)

print(l1+l2)
print(l2*5)
list1 = [2,4,6,8,10]
list1.insert(2,33)
list1.remove(10) # remove asks
print(list1)
# let's simulate Queue behavior: FIFO
list2 = []
while True:
print("1. Add Value to the Stack")
print("2. Remove Value from the Stack")
print("3. Exit from the Stack")
ch=input("Enter the operation you want to perform: ")
if ch=="1":
value = input("Enter the member to be added: ")
list2.append(value)
print("Printing the stack:",list2)
elif ch=="2":
list2.pop(0) # position is entered
print("Printing the stack:", list2)
elif ch=="3":
print("Removing all the values from the queue and terminating it!")
list2.clear()
break
else:
print("Invalid options")

#STACK - FILO
list2 = []
while True:
print("1. Add Value to the Queue")
print("2. Remove Value from the Queue")
print("3. Exit from the queue")
ch=input("Enter the operation you want to perform: ")
if ch=="1":
value = input("Enter the member to be added: ")
list2.append(value)
print("Printing the queue:",list2)
elif ch=="2":
list2.pop(0)
print("Printing the queue:", list2)
elif ch=="3":
print("Removing all the values from the queue and terminating it!")
list2.clear()
break
else:
print("Invalid options")

#WAP to input marks in 3 subjects for 3 students
# [[1,2,3], [10, 20,30], [5,0,15]]
num_students = 3
num_subjects = 3

all_data=[]
for i in range(num_students):
t_list = []
for j in range(num_subjects):
val = input("Enter the marks in subject "+str(j+1)+" and student "+str(i+1)+": ")
t_list.append(val)
all_data.append(t_list)
print("Display all data: ",all_data)

l1 = [1,3,6,5,7,7,7]
#List is mutable
l1[2]=50
print(l1)
count = l1.count(7)
print("Count = ", count)
print("Index = ", l1.index(7))

#deep copy v shallow copy
print("1. Before")
print(l1)
l2 = l1 # deep copy
l3 = l1.copy()#shallow copy
print("1. AFTER")
print("Values in Chapter 1 and Room 1:", l1)
print("Values in Chapter 1 and Room 1:", l2)
print("Values in Chapter 1 and Room 1:", l3)
l1.append(50)
l3.insert(100,200)
l2. insert(45,20)
print("2. AFTER")
print("Values in Chapter 1 and Room 1:", l1)
print("Values in Chapter 1 and Room 1:", l2)
print("Values in Chapter 1 and Room 1:", l3)

l1 = [10,40,60,20,40,80]
l1.sort()
print("Sort: ",l1)
l1.reverse()
print("Reverse: ",l1)
l3=[3]
l3.extend(l1) # l3 = l3 + l1
print(l3)

#l3 = l1 +l2

#Assignment: Read marks in 3 subjects for 3 students and find the highest marks in each subject

START PLANNING ON BELOW PROJECT WORK

Ignore the libraries to be used instructions above, instead, use Connecting to Database and save and retrive data from the database. You can use SQLITE3 or MYSQL or any database of your choice. You need to implement all the features mentioned.

#TUPLE - immutabe form of List
t1 = (2,4,6,8,10,12,14,16,18,20) #packing
print(type(t1))
print(t1[4])

t2=()
print(type(t2))

t3=(3,)
print(type(t3))

for i in t1:
print(i, end=" , ")
print()
t1 = list(t1)
print(type(t1))
t1.append(99)
t1=tuple(t1)
t2 = (3,6,9,12)
a,b,c,s = t2
print(a)

t4=(5,99)
t5=(5,99)
if t4>t5:
print(t4, "greater")
elif t5>t4:
print(t5, "greater")
else:
print("Both are same")

##Dictionary: there is no defaut order
# each member has its own key
dict1 ={"Name": "Rohit","Sport":"Cricket",1:"Captain",1:100}
print(type(dict1))
print(dict1['Name'])
print(dict1[1])

#Immutable: String, Tuple
#Mutable: List, Dictuinary, Sets
t_dict = {'City':'Mumbai'}
dict1.update(t_dict)
print(dict1)

dict2 = dict1
dict3 = dict1.copy()

print("1. Dictionaries")
print(dict1)
print(dict2)
print(dict3)

dict1.pop(1)
dict3.popitem()
print("2. Dictionaries")
print(dict1)
print(dict2)
print(dict3)

print("Items (Key,value): ",dict1.items())
print("Values: ",dict1.values())
print("Keys: ",dict1.keys())
dict1.clear()
print(dict1)

marks_dict={}
for i in range(2):
name1 = input("Enter the students name: ")
t_list = []
for j in range(3):
m=int(input("Enter marks: "))
t_list.append(m)
marks_dict.update({name1:t_list})

print("Marks details: ")
for i,j in marks_dict.items():
print(f"{i} obtained marks: {j}")


list_temp= ['Maths','Science','Social Studies']
all_marks = {}
student1 = {}.fromkeys(list_temp,-9)
all_marks.update(student1)

print("All marks: \n",all_marks)
for i in all_marks.keys():
marks = int(input("Enter the marks for "+i+" : "))
all_marks[i]=marks

print("All marks are: ",all_marks)
#Basic data types
val1 = 5 #int
print(type(val1))

val1 = '5' #str
print(type(val1))

val1 = 5.0 #float
print(type(val1))

val1 = True #bool - True / False
print(type(val1))

val1 = 5j #complex - j (square root of -1)
print(type(val1))

val1 = 4

## comparison operators - takes num as input but gives bool as output
## logical operators: take bool value as input and gives bool as output
# AND: All the values have to be True to be True else its False
# True and True = True
# T and T and T and T and T and T and F = False

# OR: All the values have to be False to be False otherwise its True
## True or False = True

## control structure with logical operators, you mean multiple conditions
val1 = 185

if val1>0 and val1 <100:
print("Value is between 0 and 100")

## Basic graphics, sets, functions,
list1 = [5, 5,5,8.3, False,"Hello",[1,6,9]]
tup1 = (5, 8.3, False,"Hello",[1,6,9]) #list and tuple have auto index: 0...
dict1 = {5:"Hello","Name":"Sachin"}

# SET -
set1 = {"Apple","Banana"}
print(type(set1))
print(set1)
# sets - union, intersection, difference, symmetric difference
set1 = {2,4,6,8}
set2 = {1,3,5,7,6,8}
# union - it puts all the values together
set3 = set1.union(set2)
print("Set 3 = ", set3)
#SETS
set1 = {1,2,3,10,20}
set2 = {1,2,3, 50,60}
print("UNION: ")#union
set3 = set1.union(set2)
print(set3)
print(set1 | set2)

print("INTERSECTION: ")#
set3 = set1.intersection(set2)
print(set3)
print(set1 & set2)

print("DIFFERENCE: Set1 - Set2")#
set3 = set1.difference(set2)
print(set3)
print(set1 - set2)

print("DIFFERENCE: Set2 - Set1")#
set3 = set2.difference(set1)
print(set3)
print(set2 - set1)

print("SYMMETRIC DIFFERENCE")#
set3 = set2.symmetric_difference(set1)
print(set3)
print(set2 ^ set1)


#### update, difference_update, intersection_update, symmetric_difference_update)
#without update, the operations result in new sets but with update, existing set is updated

### Functions - giving a name to a block of code
def mystatements(): # user defined functions
print("Whats your name?")
print("Where are you going?")
print("How are things?")

mystatements()
mystatements()
mystatements()

#below is an example of udf which doesnt take any argument nor does it return any value
def add_2_num():
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
sum = num1 + num2
print("total value is",sum)

#add_2_num()
#this is an example of function returning a value (still no arguments)
def add_2_num_ret():
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
sum = num1 + num2
#print("total value is",sum)
return sum
#result = add_2_num_ret()
#print("After return value is", result)


#example of function that takes argument
#TYPE 1 Required positional arguments
def add_2_num_arg(num1, num2):
sum = num1 + num2
#print("total value is",sum)
return sum

#TYPE 2: Default (opp of Required) positional arguments
def add_2_num_arg1(num1, num2="19"): #num2 is default
sum = num1 + num2
#print("total value is",sum)
return sum

#values are mapped from left to right
output = add_2_num_arg1("15","89")
print("Result from add_2_num_arg1: ",output)

output = add_2_num_arg1("15")
print("Result from add_2_num_arg1: ",output)

# TYPE 3: Keyword arguments (non-Positional)
output = add_2_num_arg1(num2 = "15",num1 = "89")
print("Result from add_2_num_arg1: ",output)


# TYPE 4: Variable length arguments
def myfun1(*var1, **var2):
print("Var 1 = ",var1) #Tuple
print("Var 2 = ", var2) #Dictionary

myfun1(2,4,99,"hello",False,[2,3,4],num2 = "15",num1 = "89")
#WAP to count positive numbers entered by a user
def checkPositive(*num): #variable length arguments
total=0
for i in num:
if i >0:
total+=1
return total

def checkPositive2(num): #variable length arguments
if num >0:
print("Positive")
else:
print("Not Positive")

def checkPositive3(num): # variable length arguments
if num > 0:
return 1
else:
return 0

val1 = [13,35,90,-9,0,8]
tot = checkPositive(13,35,90,-9,0,8,-8,-6,6)
print("Number of positive values = ",tot)

val2 = -9
result = checkPositive3(val2)
if result==1:
print("Number is positive")
else:
print("Number is not positive")


total = 0
val1 = [13,35,90,-9,0,8]
for i in val1:
total += checkPositive3(i)
print("Total positive values = ",total)

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

def myfactorial(n):
if n<=1:
return 1
else:
return n * myfactorial(n-1)

result = myfactorial(-5)
print("Factorial is ",result)
# return 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
# 2 = 2 * 1!
# 1 * 0!
val = 5
aList = [2,4,5,3,5,6,7,5]
count = 0
for item in aList:

if item==val:
count=count+1

print("Count = ",count)


'''
import random
a = random.random() # random value between 0 and 1
print(a)
b = random.randint(1,3)
print(b)

a <- 5 #assignment in APSC exam language, in Python: a =5
a = 5 # is a equal to 5? in Python a ==5

aList <- [2,4,6,8]
DISPLAY aList[1]

a <- aList[3]

aList[2] <- 10 # [2,10,6,8]
INSERT(aList, 2,10) # [2,10,4,6,8]
APPEND(aList,20) # [2,10,4,6,8,20]
REMOVE(aList,4) # [2,10,4,8,20]
LENGTH(aList) #len(aList) - python

# In Python we say:
for item in alist:
pass

#in APSC lang
FOR EACH item in aLists
{

}


def fun1(n1,n2):

return 1

PROCEDURE fun1(n1,n2)
{

RETURN (1)
}
'''
Learn Python

DAY 1

#interpreter - Python, R
#compiler - Java, C C++
print(5-3) #adding 5 and 3
print()
print("5+3=",5+3,"and 5*6=",5*6) #you can use " or '
print(5/0)
print("48578wefoiwefue89guaiuodgjadfgj")

# comments sdjfhasdufasodihs
# mistake
#syntax - grammar
#
#mistake
print('Hello '
'Good evening') #single line text
print("Hi")
print('''How
are
you?''')
print("""I am fine""") #multi line
num1 = 4
print("Data type of num1 is ",type(num1))
'''variable names has to begin with either an alphabet
or with _. It can contain, numbers, alphabets and _ '''

num2 = 3
print(4+3)
print("5+4=",5+4)
''' how
are
you
i am fine'''
# Five basic datatypes in Python
num1 = 4
print("Data type of num1 is ",type(num1))
num1 = 4.0
print("Data type of num1 is ",type(num1))
num1 = 4j
print("Data type of num1 is ",type(num1))
num1 = "4"
print("Data type of num1 is ",type(num1))
num1 = True
print("Data type of num1 is ",type(num1))

cost = 25.897896876;quant = 50;total = cost * quant;
print("Cost of each book is $",cost,"so for",quant,"copies, the total cost is $",total)
print(f"Cost of each book is ${cost:.3f} so for {quant} copies, the total cost is ${total:.1f}")
#format string

pl = "Virat"
count = "India"
position="captain"
print(f"{pl:<15} is {position:.^15} of {count:>15} and plays cricket")
pl = "Bywangengeger"
count = "Zimbabwe"
position="Wicket-keeper"
print(f"{pl:<15} is {position:.^15} of {count:>15} and plays cricket")

#WAP to input l and b of a rectangle and calculate area and perimeter
#WAP to input s of a square and calculate area and perimeter
#WAP to input r of a circle and calculate area and circumference
#\ is called excape sequence
#\n within the quotation will break into different line
#\t - tab space - give tab space
print("Cost of each book is $ 25.897896876 \nso for 50 copies, the total cost is $ 1294.8948438")

print("\\n is for newline")
#Arithemtic operations - mathematical operations: + - * / //  **  %
num1 = 10 #Assignment operator
num2 = 20
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2)
print(num1 // num2) #integer division
print(num1 ** num2) # exponent-power
print(num1 % num2) # modulus - remainder

#Comparison operators - can take any value but output is always bool
# == != < > <= >=
num1 = 10
num2 = 20
print(num1 == num2) #F
print(num1 != num2) #T
print(num1 > num2) #F
print(num1 < num2) #T
print(num1 >= num2) #F
print(num1 <= num2) #T

#logical operators: input is boolean and output is also bool
## and or not
##and will give False even if one value is False rest everything True
##or will give True even if one value is True rest everything False
print(True and False)
print(True or False)

print(num1 == num2 or num1 != num2 and num1 > num2 or num1 < num2 and num1 >= num2 or num1 <= num2)
#T
# 2 +8 +21+10 = 41

avg=4
if avg>=50:
print("Result: PASS")
print("i m still in if")
else:
print("Result: FAIL")

num1 = -99
if num1 >0:
print("Its a positive number")
elif num1<0:
print("Its a negative number")
else:
print("Its a zero")

print("Thank you")

avg = 65
'''
avg>=90: Grade A
avg>=80: Grade B
avg>=70: Grade C
avg>=60: Grade D
avg>=50: Grade E
avg<50: Grade F

'''
a,b,c = 10,12,8
if a>=b:
#either a is greater or equal
if a>=c:
print(f"{a} is greatest value")
else:
print(f"{c} is greatest value")
else:
#b is greater
if b>=c:
print(f"{b} is greatest value")
else:
print(f"{c} is greatest value")
#Assignmnt : Modify the above program to display 3 number is descending order

#loops - repeating
#FOR - how many times
#range(a,b,c) - generates value from a upto b and increasing by c
#range(5,19,4) - 5, 9,13,17
#range(4,19,5) - 6,11,17
#WHILE - repeating based on condition
#IF ELIF ELSE
avg = 78

'''
>90 - Grade A, 80-90: B, 70-80: C, 60-70: D 50-60: E 40-50: F
<40: Failed
'''
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: Fail")

#if you get more than 40: print - Pass
avg=55
if avg>=40:
print("Pass")
if avg >= 90:
print("Grade A")
if avg>=95:
print("You win President's medal!")
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: Fail")


# LOOPS - repeating same statements more than once
print("Hello")
# print(), type(), input(), int()- str(), bool(),float()

sum = 5+3
print(type(sum))
sum = str(sum)
print(type(sum))

#range(a,b,c) = a:start number (including) b:ending (excluding) c:increment
range(3,9,2) # 3,5,7
range(3,7) # c is default =1: 3,4,5,6
range(4) #a=0, c=1 (default): 0,1,2,3

#For: exactly how many times
for i in range(3,9,2):
print(i, 'hello')
for i in range(3, 6):
print(i, 'hello')
for i in range(3):
print(i, 'hello')
for i in range(1,6,2):
print(i)

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

#While: dont know how many times but you the condition
for counter2 in range(5):
for counter in range(5):
print("*",end=" ")
print()

'''
*
* *
* * *
* * * *
* * * * *
'''
for counter2 in range(5):
for counter in range(counter2+1):
print("*",end=" ")
print()

'''
* * * * *
* * * *
* * *
* *
*
'''
for counter2 in range(5):
for counter in range(5-counter2):
print("*",end=" ")
print()
'''
*
* *
* * *
* * * *
* * * * *
'''
for counter2 in range(5):
for counter in range(5-counter2):
print(" ",end="")
for counter3 in range(counter2+1):
print("*",end=" ")
print()

for j in range(1,11):
for i in range(1,11):
print(f"{i:<2} * {j:<2} ={j*i:>3}", end=" ")
print()
for j in range(1,11):
for i in range(1,11):
print(f"{i:>2} * {j:>2} = {j*i:>3}", end=" ")
print()

#While loop:
#print values from 1 to 10
i=1
while i<=10:
print(i)
i+=1 #i=i+1

i=1
ch="y"
while ch=="y":
print(i)
i+=1 #i=i+1
ch=input("Hit y to continue or anyother key to stop: ")

total = 0
for i in range(3):
marks = int(input("Enter marks: "))
total+=marks

print("Total marks = ",total,"and average is: ",total/3)

#

ch="y"
total=0
counter = 0
while ch=="y":
marks =int(input("Enter the marks: "))
counter+=1
total+=marks
ch=input("Enter y to continue")

print("Total marks = ",total,"and average is: ",total/counter)

#

total=0
counter = 0
while True: #infinite
marks =int(input("Enter the marks: "))
counter+=1
total+=marks
ch=input("Enter y to continue")
if ch!='y':
break

print("Total marks = ",total,"and average is: ",total/counter)

#

total=0
counter = 0
while True: #infinite
marks =int(input("Enter the marks: "))
if marks<0:
continue
counter+=1
total+=marks
ch=bool(input("Enter anykey to stop"))
if ch:
break

print("Total marks = ",total,"and average is: ",total/counter)

#Strings

str1 = "Hello"
str2 = 'hi there'
print(str1)
print(str2)
str3 = '''good evening
how are you?
hows going?
are you alright?'''
str4 = """take care"""

print(str3)
print(str4)

str2 = 'hi there'
print(str1 + str2)
print(str1*4)
#read a portion of the text
print(str2[3])
print(str2[0:4])
print(str2[:4])
print(str2[-1])
print(str2[-3])
print("Total: ", len(str2))
print(str2[-3:])

for i in str1:
print(i)

str1 = "I am DOing well"
print(str1.lower())
print(str1.upper())
print(str1.title())

#strings are immutable - you cant edit them, you can overwrite
#str1[1] = "K"

str1 = "hello"
print(str1.islower())
print(str1.isdigit())

num1 = input("Enter a number: ")
if num1.isdigit():
num1 = int(num1)
print(num1)
else:
print("Invalid number")
txt1 = "hello123"
print(txt1.isalnum())

#split, search, join
str1 = 'HELLO How ARE YOU'
str2 = "hello"
#Strings are immutable - they cant be edited
print(str1.lower())
print(str1.upper())
print(str1.title())
print(str2.isalnum())
num1 = input("Enter your age: ")
if num1.isdigit():
num1 = int(num1)
else:
print("Invalid number, try again!")

val2=" a "
print(val2.isspace())
print(val2.isalpha())

# islower(), isupper(), istitle()
print(val2[1])
#val2[1]="A" - not possible as strings are immutable
str3 = "how are you oops I mean you yOu"
print("check: ", 'w a' in str3)
print(str3.count('you'))
print(str3.index('you'))

#
res=str3.split("o")
print("split: ",res)
txt = "o".join(res)
print(txt)
# List - store multiple values -
# they need not be of same datatype

l1 = [5,10,15,"Hello", False, [4,5,6]] #list
print(type(l1))
print(l1[1]) #second member
print(l1[3][1])

print([1,2,3] + [4,5,6])
print([3,6,9] * 3)
print("Length of List = ",len(l1))
for i in l1:
print(i)

l2 = [12,34,23,54,89,76,49,29]
sum=0
for i in l2:
sum+=i
print("Sum of the values in the list = ",sum)
l2 = [12,34,23,54,55,76,55,29]
l2[1]=55
print(l2)

print(l2.count(55))

ind=0
print("Indices: ",end=" ")
for i in range(l2.count(55)):
index = l2.index(55,ind)
print(index,end=" , ")
ind = index+1
print()
l3 = l2 # copy by = DEEP COPY
l4 = l2.copy() #copy by copy method - SHALLOW COPY
print("1. Copying")
print("L2: ",l2)
print("L3: ",l3)
print("L4: ",l4)
l2.append(99) #append adds element at the end
l2.insert(0,9) #insert adds element at the given position (pos,element)

print("2. Copying")
print("L2: ",l2)
print("L3: ",l3)
print("L4: ",l4)

l2.pop(2)
l2.remove(54)
print("After remove: ",l2)
l2.reverse()
print(l2)
l2.sort()
print("Sorted: ",l2)
l2.sort(reverse=True)
print("Sorted: ",l2)

l2.clear()
print(l2)

## TUPLES - immutable version of list
t1 = (2,)
print(type(t1))
l1 = ['hello',25,45,False,[2,4,6], 45]
l9 = [False,[2,4,6], 45,'hello',25,45]
# TUPLE - linear ordered immutable collection
t1 = ('hello',45,False,[2,4,6])
print(type(t1))
t2 = tuple(l1)
l2 = list(t1)

print(t2)
print(type(t2))

print(t2.count(45))
print(t2.index(45))

t3 = ()
print("first t3: ",type(t3))

t3 = (3,)
print("second t3: ",type(t3))

t3 = (3,5)
print("third t3: ",type(t3))
print(t2[2])
#Dictionary - key:value mutable collection

d1 = {}
print("Type of d1 is ",type(d1))
d1={"First":10, 5:"Hello", "Completed":False}
print(d1[5])

t={"City":"Hyderabad"}
d1.update(t)
print(d1)
t1={5:"Learn Python"}
d1.update(t1)
print(d1)

####
emp_id = [1001,1002,1009,1015]
incentive = [30,32,35,39]

emp_incentive = {1001:30, 1002:32,1009:35,1015:39}

#How much incentive should be given to emp with id 1009
print(emp_incentive[1009])
print(incentive[emp_id.index(1009)])

pos = emp_id.index(1009)
print(incentive[pos])

#keys, values, items
print(d1.values())
print(d1.keys())
print(d1.items())
print("Printing values")
for i in d1.values():
print(i)
print("Printing keys")
for i in d1.keys():
print(i)
print("Printing items")
for i,j in d1.items():
print("Key:",i," and value: ",j)
# SET - sets - linear unordered mutable collection - doesnt allow duplicate
set1 = {'Apple','Grapes','Banana','Orange'}
print(type(set1))
set1.add('Cherry')
set2 = {"Pineapple","Mango","Apple","Orange"}
# two ways to remove
set1.remove("Banana")
set1.discard("Apple")
#set1.remove("Rose") - if value isnt there throws error
set1.discard("Rose") #doesnt throw error
print("1. Set1: ",set1)
set1.pop()
set1.update(set2) #union
print("2. Set1: ",set1)
set1.clear()
print("3. Set1: ",set1)
### SET FUNCTIONS ####
set1 = {'Apple','Grapes','Banana','Orange'}
set2 = {"Pineapple","Mango","Apple","Orange"}
#UNION
print("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-convertible
list1 = [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")
# Basic data types (stores only 1 value) - int, float, str,bool and complex
# Collections (stores multiple values - 1D) - list, tuple,dictionary, set
# functions - own functions - user defined functions
# print(), input(), type(), int(), str(), len() : in-built functions (developers of python have already written for us)
# we will learn to write our own functions

#first part of writting function is to Define the meaning- function
def mytext(val1, val2,val3):#required positional argument
print("Hello How are you today?")
print("Where are you going?")
print("I am fine.",val1)

def mytext2(val1=0, val2=0,val3=9):#default positional argument
print("Hello How are you today?")
print("Where are you going?")
print("I am fine.",val1)
print("Values are: ",val1,val2,val3)
#demo keyword (non-positional) arguments
def mytext3(val1, val2,val3):#default positional argument
print("Hello How are you today?")
print("Where are you going?")
print("I am fine.",val1)
print("Values are: ",val1,val2,val3)


#default argument (non-required) & keyword argument (non-positional)
mytext(5,10,0)
print("Done with one time calling now calling second time")
mytext2(20,4,10)
mytext2(20,4)
mytext2(10,5,1)
mytext3(val3=10,val1=9,val2=8)
mytext3(100, val3=9,val2=8)
#print()
# numpy, pandas (Multi-D)

def isPositive(val1):
#result = "Positive" # "+ve" / 1
if val1 >0:
return 1
else:
return 0 #print("Its not Positive")

res = isPositive(100)
if res==1:
print("Its positive, now lets go ahead building our logic")
else:
print("STOP! STOP! STOP!")

isPositive(-100)
isPositive(90)
#Functions with input arguments, return values
#Input arguments - required positional arguments, default, keywords arguments
def fun1(a,b):
pass

a=fun1(b=3,a=2)

#variable length arguments
def myfun2(*a, **c):
print("A has: ",a)
print("C has: ",c)

myfun2(5,6,100,8,11,"Hello",name="Sachin",city="Mumbai",Sports="Cricket")

#lambda, annoynomous or one-line - functions

a=lambda n1,n2,n3:n1*n2+n3
print(a(2,3,4))

#map, filter, reduce - special properties for LIST
list_ft = [20000,29000,30000,32000,30000,25000,33000,18000,11000,19000]
list_mt=[]
for i in list_ft:
list_mt.append(i/3.1)
print(f"Data in metres = {list_mt}")

list_mt_2 = list(map(lambda i:i/3.1,list_ft))
print(f"Data in metres = {list_mt_2}")

#Filter
list_filter = list(filter(lambda i:i%10000==0,list_ft))
print("Filtered values: ",list_filter)

#Filter 2
list_filter = list(filter(lambda i:i<20000,list_ft))
print("Filtered values: ",list_filter)

# reduce
import functools
list1 = [5,10,15,20,25,30,35] #140
val = functools.reduce(lambda a,b:a+b,list1)
print(“Result = “,val)

#functions – they are independent: print(), len(), input(), int()
#methods – they are part of a class: list (append,sort..), dictionary(copy…),string()
#in class, you have to first create an object
list1 = [] # create an object
#list1.append()

#function, you dont have to create any object – object of what??

# function
def onename():
print(“I am fine”)
print(“I am here”)
print(“I will stay here”)
def somename():
print(“Whats your name?”)
print(“What are you doing here?”)
print(“How are you?”)
return 100,200,300
x,y=2,3
def adding(x,y): # required positional arguments
print(“X = “,x,“y=”,y)
return x+y
def subtracting(a,b):
return a-b
result = adding(5,7)

result = subtracting(result,5)
#print(“Result is”,result)

b = somename()
print(“b = “,b)
a = print(“Hello”)
print(“a = “,a)
somename()

print()

def mycalc1(x,y,z): #required positional arguments
add = x+y+z
sub = z-x+y
print(“X, Y, Z are “,x,y,z)
return add,sub

r1,r2 = mycalc1(5,10,20)
print(“Result are”,r1,r2)

def mycalc2(x,y,z=15): # (x & y) are required, z is default (non-required): all of them are positional arguments
add = x+y+z
sub = z-x+y
print(“X, Y, Z are “,x,y,z)
return add,sub

r1,r2 = mycalc2(5,10,20)
print(“Result are”,r1,r2)

r1,r2 = mycalc2(5,10)
print(“Result are”,r1,r2)
#Function declaration for Required positional arguments
def myfun1(a,b,c):
print(f”A = {a}, B={b}, C={c} )
return a+b+c

def myfun2(a,b,c=25): #c is default, a and b are required, all are positional
print(f”A = {a}, B={b}, C={c} )
return a+b+c

myfun1(50,100,15) #calling required positional
myfun2(10,20) # c is default
#for non positional (keyword arguments) – depends upon the way we call
myfun1(c=50,a=100,b=15)

myfun2(b=23,a=54)

# function that will return true if a number is prime or else False
def isPrime(num):
prime = True
for i in range(2,num):
if num %i==0:
prime = False
break
return prime
result = isPrime(15)
if result:
print(“Number is Prime”)
else:
print(“Number is not a Prime”)

# generate range of prime numbers
start, end = 5000,6000
for j in range(start,end+1):
result = isPrime(j)
if result:
print(j,end=“, “)
print()

#variable length arguments
def mySum1(*var,**var2): # * to accept variable number of arguments
”’
This is a demo function to show the working of variable number of arguments
:param var: will read as tuple
:param var2: will read as dictionary
:return: sum of elements in the tuple
”’
print(var2) #read as dictionary
# *var would be a tuple
sum=0
for i in var: #(5,2,1,3,8,6,4)
sum+=i # sum = sum+i
return sum

output = mySum1()
print(“Output = “, output)
output = mySum1(2,3)
print(“Output = “, output)
output = mySum1(5,10,0,10,15,20,25,30,35,40,10,20,name=“Sachin”,game=“Cricket”,fame=“Batsman”)
print(“Output = “, output)

print(mySum1.__doc__) #doc string (documentation)
print(print.__doc__)
print(input.__doc__)

#
def try_recur(n):
print(“Hello”)
if n>2:
try_recur(n-1)

try_recur(50)

##function to find factorial of a number
def myFactorial(num):
prod = 1
for i in range(1,num+1):
prod *=i # prod = prod * i
return prod

fact = myFactorial(5)
print(“Factorial = “,fact)

def myRFacto(num):
if num==1:
return 1
else:
return num*myRFacto(num-1)

fact = myRFacto(5)
print(“Factorial = “,fact)

Filename: P5.py

#recursive functions
def facto(n):
if n==1:
return 1
return n * facto(n-1) # 10 * 9!

#decorators
def myfunc1():
print(“This is my func1”)

def myfunc2():
print(“This is my func2”)

def myfunc3(abc):
print(“This is my func3 line 1”)
abc()
print(“This is my func3 line 2”)

if __name__ ==“__main__”:
val = facto(5)
print(“Factorial is “,val)
myfunc3(myfunc1)

Filename: P6.py

# import option 1
import MyPack1.modul1
import p5

val = p5.facto(5)
print(val)
# import option 2: with alias
import p5 as MyTopChoices
MyTopChoices.myfunc3(MyTopChoices.myfunc1)

# import option 3
from p5 import myfunc3,myfunc2,myfunc1
myfunc2()

# importing package
import MyPack1.modul1 as p1m1
p1m1.myfunc3(10)

from MyPack1 import *
MyPack1.modul1.myfunc2(2,5,8)

## using random module
import random
print(“Random val = “,random.random())
print(“Random integer = “,random.randint(1,100))
#Object Oriented Programming
#class & objects
#apple – class, hold it, eat it -object

# create a class – define some properties
# to use a class – you have to create an object
# object will have properties of the class and few more

class Book:
num_of_books = 0 #class variable
publisher = “Eka Publishers”
def __init__(self,book_title, pages=100,book_author=“”): #object function
self.pages = pages #object variables
self.title = book_title
self.author = book_author
Book.num_of_books +=1

def display_details(self):
print(“Title: “,self.title)
print(“Author: “,self.author)
print(“Pages: “,self.pages)
print(“Total books = “,Book.num_of_books)

@classmethod
def total_count(cls):
print(“Total books = “,cls.num_of_books)

b1 = Book(“Python Programming”, 350,“Swapnil Saurav”) #object is created – __init__() is called automatically
b2 = Book(“Machine Learning”, 550,“Swapnil Saurav”)
b3 = Book(“Data Visualization”, 250,“Swapnil Saurav”)
#b1.create_book(“Python Programming”, 350,”Swapnil Saurav”) #object function is called
b2.display_details()
print(type(b1))
class MyMathOps:
def __init__(self,n1,n2):
self.n1 = n1
self.n2 = n2
self.add = –1
self.subtract = –1
self.multiply = –1
self.divide = –1

def myadd(self):
self.add= self.n1 + self.n2
return self.add
def mysubtract(self):
self.subtract = self.n1 – self.n2
def mymultiply(self):
self.multiply = self.n1 * self.n2
def mydivide(self):
self.divide = self.n1 / self.n2

class SpecialOps:
def __init__(self,num):
self.number = num
print(“Num = “,num)


def isPrime(self):
prime = True
for i in range(2,self.number//2 + 1):
if self.number % i ==0:
prime = False
break
return prime

if __name__ ==“__main__”:
op1 = MyMathOps(5,15)
#

op2 = MyMathOps(5,10)
print(op1.myadd()) #1. class Abstraction
print(op1.mymultiply())
op2.mydivide()
print(op1.divide)

l1 = [4,5,6,7]
l1.append(5)
sp1 = SpecialOps(11)
print(“Prime: “,sp1.isPrime())
import p3
from p3 import MyMathOps as mp

c1 =mp(10,20)
c1.myadd()
print(“Add = “,c1.add)

class ShoppingCart:
def __init__(self):
self.myshoppingcart = []

#add product to the cart
def add_prod(self,item):
self.myshoppingcart.append(item)

sc1 = ShoppingCart()
while True:
print(“1. View my cart \n2. Add to my cart\n3. Remove from my cart\n4. Exit”)
ch=input(“Enter your option: “)
if ch==“1”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
print(“Products in your cart are: “,sc1.myshoppingcart)
elif ch==“2”:
item = input(“Enter the product you want to add: “)
sc1.add_prod(item)
elif ch==“3”:
pass
elif ch==“4”:
break
else:
print(“Invalid option”)
class ShoppingCart:
def __init__(self):
self.myshoppingcart = []

#add product to the cart
def add_prod(self):
each_item = {}
item_name = input(“Enter the product Name: “)
item_size = input(“Enter the product Size: “)
item_color = input(“Enter the product Color: “)
each_item ={“Item”:item_name,“Size”:item_size,“Color”:item_color}
self.myshoppingcart.append(each_item)
#print(self.myshoppingcart)
def display_prod(self):
print(“Item Size Color”)
for i in self.myshoppingcart:
for k,j in i.items():
if k==“Item”:
print(f”{j:<10}, end=” “)
else:
print(j,end=” “)
print()


sc1 = ShoppingCart()
while True:
print(“1. View my cart \n2. Add to my cart\n3. Remove from my cart\n4. Exit”)
ch=input(“Enter your option: “)
if ch==“1”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
sc1.display_prod()
elif ch==“2”:
sc1.add_prod()
elif ch==“3”:
pass
elif ch==“4”:
break
else:
print(“Invalid option”)
MASTERLIST = [{“ItemCode”: 101,“Item”:“Shirt”,“Price”:28.2},
{“ItemCode”: 102,“Item”:“Bag”,“Price”:18.2},
{“ItemCode”: 103,“Item”:“Book1”,“Price”:38.2},
{“ItemCode”: 104,“Item”:“Watch”,“Price”:58.2},
{“ItemCode”: 105,“Item”:“Shoes”,“Price”:128.2},
{“ItemCode”: 106,“Item”:“Laptop”,“Price”:1028.2}]
class ShoppingCart:
def __init__(self):
self.myshoppingcart = []

#add product to the cart
def add_prod(self):
each_item = {}
item_name = input(“Enter the product Name: “)
not_in_list = True
for items in MASTERLIST:
if item_name==items[“Item”]:
not_in_list = False
if not_in_list:
print(“Sorry, That Item is Out of Stock!”)
else:
item_size = input(“Enter the product Size: “)
item_color = input(“Enter the product Color: “)
item_quantity = int(input(“Enter the product Quantity: “))
each_item ={“Item”:item_name,“Size”:item_size,“Color”:item_color,“Quantity”:item_quantity}
self.myshoppingcart.append(each_item)
#print(self.myshoppingcart)
def display_prod(self):
print(“Item Size Color Quantity”)
for i in self.myshoppingcart:
for k,j in i.items():
print(f”{j:<10}, end=” “)
print()

def remove_prod(self):
item_name = input(“Enter the product name to remove: “)
not_in_list = True
for items in self.myshoppingcart:
if item_name == items[“Item”]:
self.myshoppingcart.remove(items)
not_in_list = False

if not_in_list:
print(“Sorry, That Item is not in your shopping cart!”)
else:
print(“Item is now removed from your shopping cart!”)

def generate_receipt(self):
print(“Item Size Color Quantity Price”)
print(“=======================================================”)
item_cost = 0
price = 0
grand_total = 0
for i in self.myshoppingcart:
for k,j in i.items():
for master_list in MASTERLIST:
if j==master_list[“Item”]:
price=master_list[“Price”]

print(f”{j:<10}, end=” “)
if k==“Quantity”:
item_cost = j*price
grand_total+=item_cost
print(f”{round(item_cost):<10}, end=” “)
print()
print(“——————————————————-“)

print(” TOTAL: $”+str(round(grand_total)))
print(“=======================================================”)

if __name__==“__main__”:
sc1 = ShoppingCart()
sc2 = ShoppingCart()
while True:
print(“1. View my cart \n2. Add to my cart\n3. Remove from my cart\n4. Generate My Receipt\n5. Exit”)
ch=input(“Enter your option: “)
if ch==“1”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
sc1.display_prod()
elif ch==“2”:
sc1.add_prod()
elif ch==“3”:
sc1.remove_prod()
elif ch==“4”:
if len(sc1.myshoppingcart)==0:
print(“Your shopping cart is empty!”)
else:
sc1.generate_receipt()
elif ch==“5”:
break
else:
print(“Invalid option”)
”’
WAP to implement Stack properties:
add, delete: LIFO
”’
class MyStack:
def __init__(self):
self.mystack=[]
def add(self,val):
self.mystack.append(val)
def delete(self):
self.mystack.pop()
def display(self):
print(“Values in the stack are:\n,self.mystack)

# create the object
stack1 = MyStack()
stack1.add(40)
stack1.add(10)
stack1.add(20)
stack1.add(60)
stack1.add(50)
stack1.add(80)
stack1.display()
stack1.delete()
stack1.display()
stack1.delete()
stack1.delete()
stack1.display()


January 2023 Evening
#interpreter: Python R
print("Hello")
print(5+4)
print('5+4=',5+4,'so what even 4+5=',4+5)
a=5 # variable
print("type of a in line #5 is ",type(a))
print("a = ",a)
#type of data (datatype) is integer - numbers without decimal point -99999,999
a = 5.0 #data type is float - numbers with decimal point, -999.5, 0.0, 99.9
print("type of a in line #9 is ",type(a))
a = 5j # i in Maths - square root of -1
print("type of a in line #11 is ",type(a))
#square root of -4 = 2i
print("a*a = ",a*a) #
a=9
print("a = ",a)
#function - print(), type()
# ,
#variable - constant
# is comment - Python these are not for you. these for us
a="HELLO" #text - in python type - string str
print("type of a in line #21 is ",type(a))

 

 

a = True #boolean = True or False
#print(type(a))
print(“type of a in line #24 is “,type(a))
#compiler: C. C++ Java

#Android – STORY MANTRA – after you login
#on the home page you will see- CATEGORIES -> Technical
#Technical -> Python, R ,

print("Hello")  #fist line
print('irte834t8ejviodjgiodfg0e8ruq34tuidfjgiodafjgodafbj')

 

print(5+3)
print(‘5+3’)
print(‘5+3=’,5+3,“and 6+4=”,6+4)
#whatever is given to print() shall be displayed on the screen
#syntax – rules (grammar)
#COMMENTS

#print(), type()
#comments
#data types: int, float, str,bool, complex
#variables - will accept alphabets, numbers and _
price = int(51.9876);
quantity = 23;
total_cost = price * quantity;
print(total_cost);
print("Given price is", price,"and quantity bought is",quantity,"so total cost will be",total_cost)

# f string
print(f"Given price is {price:.2f} and quantity bought is {quantity} so total cost will be {total_cost:.2f}")

player = "Sachin"
country = "India"
position = "Opener"
print(f"{player:<15} is a/an {position:>15} and plays for {country:^15} in international matches.")
player = "Mbwangebwe"
country = "Zimbabwe"
position = "Wicket-keeper"
print(f"{player:<15} is a/an {position:>15} and plays for {country:^15} in international matches.")

#Sachin is a/an Opener and plays for India in international matches.
#Mbwangebwe is a/an Wicket-keeper and plays for Zimbabwe in international matches.

#escape sequence \
print("abcdefghijklm\nopqrs\tuv\wx\y\z")
# \n - newline

# \n is used for newline in Python
print("\\n is used for newline in Python")

# \\n is actually give you \n in Python
print("\\\\n is actually give you \\n in Python")


# Data types - 5 main types
var1 = 5
print(type(var1)) # int - integer -9999 0 5

var1 = 5.0
print(type(var1)) #float - numbers with decimal

var1 = 5j
print(type(var1)) #complex - square root of minus 1

var1 = True #False #bool
print(type(var1))

var1 = "hello" #str - string
print(type(var1))

#input() - is used to read a value from the user
num1 = float(input("Enter a number: "))
print(f"{num1} is the number")
print("Datatype of num1 is ",type(num1))

var2 = "50"

#implicit and explicit conversion

# arithmetic Operations that can be performed on
# numeric (int, float, complex): i/p and o/p both are numbers
num1 = 23
num2 = 32 #assign 32 to num2
print(num1 + num2) #addition
print(num1 - num2) #
print(num1 * num2) #
print(num1 / num2) #
print(num1 // num2) #integer division: it will give you only the integer part
print(num1 ** num2) # Power
print(num1 % num2) # mod modulus - remainder

## comparison operator : input as numbers and output will be bool
## > < == (is it equal?) != , >= <=
num1 = 23
num2 = 32
num3 = 23
print(num2 > num3) # T
print(num3 > num1) # F
print(num2 >= num3) #T - is num2 greater than or equal to num3 ?
print(num3 >= num1) # T
print(num2 < num3) # F
print(num3 < num1) # F
print(num2 <= num3) # F
print(num3 <= num1) # T
print(num2 == num3) # F
print(num3 != num1) # F

# Logical operator: and or not
# prediction 1: Sachin or Saurav will open the batting - T
# prediction 2: Sachin and Saurav will open the batting - F
# actual: Sachin and Sehwag opened the batting

#Truth table - on boolean values
# AND Truth Table:
### T and T => T
### T and F => F
### F and T => F
### F and F => F

# OR Truth Table:
### T or T => T
### T or F => T
### F or T => T
### F or F => F

# NOT
## not True = False
## not False = True

## Assignment 1: Get lenght and breadth from the user and calculate
## area (l*b) and perimeter (2(l+b))

## Assignment 2: Get radius of a circle from the user and calculate
## area (pi r square) and curcumference (2 pi radius)
#Logical operator: works on bool and returns bool only
# and: all values have to be True to get the final result as True
# or: anyone value is True, you get the final result as True
# 5 * 99 * 7 * 151 * 45 * 0 = 0
# 0 + 0 + 0 + 0+1 = 1

print(True and True and False or True or True and True or False or False and True and True or False)
num1 = 5
num2 = 8
print(num1 !=num2 and num1>num2 or num1<=num2 and num2>=num1 or num1==num2 and num1<num2)

num3 = bin(18) #0b10010
print(num3)
print("hex(18) = ",hex(18)) #0x12
print("oct(18): ", oct(18)) #0o22

print("hex(0b1101111) = ",hex(0b1101111))
print("int(0b1101111) = ",int(0b1101111))

#BITWISE Operators
# left shift (<<) / right shift (>>) operators work on only binary numbers
print("56 << 3 = ",56 << 3) #output #111000000
print(bin(56))
print(int(0b111000000)) #448

print("56 >> 4 = ",56>>7) #

# & and in bitwise
print("23 & 12 = ",23 & 12) #4
print("23 | 12 = ",23 | 12) #31
print(bin(23)) #10111
print(bin(12)) #01100
#& 00100
print(int(0b100))
# | 11111
print(int(0b11111))

# | or in bitwise

num1 = 10
#positive
#negative

# area of a circle = pi * r**2 (3.14 = pi)
# circunference = 2 * pi * r

# Conditions
avg = 30
if avg >=40:
print("Pass") #indentation
print("Congratulations!")
else: #incase of IF getting False condition
print("You have failed")
print("try again")

#avg > 90 - Grade A
#avg 80 to 90 - Grade B
# avg 70 to 80 - Grade C
#avg 60 to 70 - Grade D
#avg 50 to 60 - Grade E
#avg 40 to 50 - Grade F
#avg <40 - Grade G

avg=30
if avg>=40:
print("Pass") # indentation
print("Congratulations!")

if avg>=90:
print("Grade A")
if avg >=95:
print("You win President Medal")

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("You have failed")
print("try again")
print("Grade G")


avg = 90
if avg <40:
print("Grade G")
elif avg <50:
print("Grade F")
elif avg <60:
print("Grade E")
elif avg <70:
print("Grade D")
elif avg <80:
print("Grade C")
elif avg <90:
print("Grade B")
else:
print("Grade A")

print("Thank you so much")

num = 5
if num > 0:
print("Number is positive")
if num % 2 == 1:
print("Its Odd")
else:
print("Its even")
if num % 3 == 0:
print("It is divisible by both 2 and 3. It is also divisible by 6")

else:
print("Its divisible by 2 but not 3")

elif num == 0:
print("Neither Positive not negative")
else:
print("Its Negative")

#loops - repeating multiple lines of code
#Python - 2 types of loops- one when you know how many times to repeat - FOR
#repeat until some condition true WHILE
# range(a,b,c) #generates range of values - start from a, go upto b(exlusive), c=increment
#range(2,6,2) = 2,4
#range(5,9) = (2 val indicate a&b - c is default 1) => 5,6,7,8
#range(5) = (its b, a is deafult 0 and c is default 1) = ?

for i in range(3,9,2):
print("HELLO",i)

for i in range(10):
print(i*2+2,end=", ")
print("\n")
for i in range(5):
print("*",end=" ")
print("\n=================")
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for j in range(5):
for i in range(5):
print("*",end=" ")
print()

#for loop
for i in range(5):
print(i)
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()

num,sum = 5,0
while num <103:
sum+=num
print(num)
num+=5

print("Sum = ",sum)
i=0
while True:
i=i+1
print("Hello, i is ",i)
ch=input("Enter y to stop: ")
if ch=='y':
break
print("One more hello")
if i%5==0:
continue
print("Another hello but not to print when its multiple of five")
a,b,c = 10,12,8
if a>=b:
#either a is greater or equal
if a>=c:
print(f"{a} is greatest value")
else:
print(f"{c} is greatest value")
else:
#b is greater
if b>=c:
print(f"{b} is greatest value")
else:
print(f"{c} is greatest value")
#Assignmnt : Modify the above program to display 3 number is descending order

#loops - repeating
#FOR - how many times
#range(a,b,c) - generates value from a upto b and increasing by c
#range(5,19,4) - 5, 9,13,17
#range(4,19,5) - 6,11,17
#WHILE - repeating based on condition

############################
#Strings
str1 = 'Hello how are you'
str2 = "Im fine"
str3 = '''How are you today
are you fine
hope you feel better'''
str4 = """I am fine today
expecting to do well
I am feeling better now"""
print(str3)

print(str1 + " "+str2)
print(str2*10)
print("Lo" in str1)

#indexing: slicing dicing
print(str1[0])
print(str1[4])
print(str2[-1])
print(str1[6:9])
print("->",str1[-11:-8])
print("First 3 values: ",str1[:3])
print("last 3 values: ",str1[-3:])

#
print(str1.upper())
#string immutable - you cant edit the string
#str1[0]="K" TypeError: 'str' object does not support item assignment
str1 = "K"+str1[1:]
print(str1)
str1 = "hello how are you?"
print("last 3 characters: ",str1[-3:])
for i in str1:
print(i)

print(str1.islower())
print(str1.isupper())
print(str1.isalpha()) #
str1 = "509058585855"
print(str1.isdigit())
print(str1.isspace())
str1 = "hello how are you?"
print(str1.title())
print(str1.lower())
print(str1.upper())

str2 = "I am fine how are you doing today"
target = "aeiou"
count=0
for i in str2:
if i.lower() in target:
count+=1
print("Total vowels: ",count)

result = str1.split()
print(result)
result2 = str1.split('ow')
print(result2)
result3 = "OW".join(result2)
print(result3)

print(str1.find('o',0,5))
print(str1.replace("hello","HELLO"))
print(str1)

#strings are immutable
var1 = 5 # integer
print(type(var1))
var1 = 5.0 # float
print(type(var1))
var1 = "5" # string
print(type(var1))
var1 = 5j # complex
print(type(var1))
var1 = True # bool
print(type(var1))

#Arithematic operations
num1 = 5
num2 = 3
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2)
print(num1 // num2) #integer division
print(num1 % num2) #modulo - remainder
print(num1 ** num2) # power

##Once I had been to the post-office to buy stamps of five rupees,
# two rupees and one rupee. I paid the clerk Rs. 20,
# and since he did not have change, he gave me three more
# stamps of one rupee. If the number of stamps of each type
# that I had ordered initially was more than one,
# what was the total number of stamps that I bought.
total = 30
stamp_5_count = 2 #>=
stamp_2_count = 2 #>=
stamp_1_count = 2+3 #>=
total_by_now = stamp_5_count * 5 + stamp_2_count * 2 + stamp_1_count * 1
print(total_by_now, "is total by now")
accounted_for = total - total_by_now

stamp_5_count = stamp_5_count + accounted_for //5
accounted_for = accounted_for %5

stamp_2_count = stamp_2_count + accounted_for //2
accounted_for = accounted_for %2

stamp_1_count = stamp_1_count + accounted_for

print("You will end up getting:")
print("Number of 5 Rs stamp = ",stamp_5_count)
print("Number of 2 Rs stamp = ",stamp_2_count)
print("Number of 1 Rs stamp = ",stamp_1_count)
total_value = stamp_5_count*5 + stamp_2_count* 2+ stamp_1_count*1
print("Net difference between amount and stamp value: ",total-total_value)

#Comparison operators: < > <= >= == !=
num1 = 7
num2 = 7
print("is num1 equal to num2? ", num1==num2) #== ??
print("is num1 not equal to num2?", num1!=num2)
print("is num1 greater than num2? ", num1>num2)
print("is num1 greater than or equal to num2?", num1>=num2)
print("is num1 less than num2? ", num1<num2)
print("is num1 less than or equal to num2?", num1<=num2)

#Logical operators: and (*) or (+) not
# pred: sachin and sehwag will open the batting
# actual: sachin and sourav opened the batting - wrong

# pred: sachin or sehwag will open the batting
# actual: sachin and sourav opened the batting - right

print(True and True) #True
print(True and False) #rest is all False
print(False and True)
print(False and False)

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

print(not True) #

num1 = 7
num2 = 7
print("=>",num1==num2 and num1!=num2 or num1>num2 or num1>=num2 and num1<num2 and num1<=num2)
# F
# conditional check
num1 = 100
#perform check - IF condition
if num1>0:
print("Its positive")
#We use conditions when we need to control the flow of the program
avg = 88

#avg: 90 to 100: A , 80-90: B, 70-80: C , 60-70: D
#50 to 60: E, 40 to 50: F, <40: Failed
# if ... elif.. else

if avg >=90:
print("Pass")
print("Grade A")
elif avg>=80:
print("Pass")
print("Grade : B")
elif avg>=70:
print("Pass")
print("Grade : C")
elif avg>=60:
print("Pass")
print("Grade : D")
elif avg>=50:
print("Pass")
print("Grade : E")
elif avg >=40:
print("Pass")
print("Grade : F")
else:
print("Grade : Failed")

## Assignment - use Nested condition: Take 3 numbers and put them
## in increasing order:
## 14, 13 13 => 13,13,14
# 19, 39,29 => 19,29,39
avg = 94
if avg>=40:
print("Pass")
if avg >= 90:
print("Grade A")
if avg>=95:
print("You win President's medal!")
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")

num1= -0
if num1>0:
print("Number is positive")
elif num1<0:
print("Number is negative")
else:
print("0 - neither positive not negative")

# FOR Loop: when you know how many times to run the loop
# range(a,b,c) : start from a (including), go upto b (exclusive), increment by c
range(3,9,2) # 3,5,7 ... 8
print("For loop example 1:")
for i in range(3,9,2):
print(i)

print("For loop example 2:")
for i in range(3, 6): #range(a,b) => c=1 (default)
print(i)

print("For loop example 3:")
for i in range(3): # range(b) => a=0 (default) c=1 (default)
print(i)
# WHILE Loop: you dont know the count but you know when to stop
#LIST:  linear ordered mutable collection

l1 = [5,9,8.5,False,"Hello",[2,4,6,"Welcome"]]
print("Length: ",len(l1))
print(type(l1))
print(type(l1[1]))
print(l1[-3])
print(l1[-2][2])
print(l1[-1][-1][-1])

l2 = [10,20,30]
print(l1+l2)

print(l2 * 3)

files = ['abc.csv','xyz.csv','aaa.csv','bbb.csv','ccc.csv','ddd.csv']
for i in files:
print("I have completed",i)

#inbuilt methods for list
print("1. L2 = ",l2)
l2.append(40)
l2.append(60) #append will add members at the end
#insert()
l2.insert(3,50)
l2.insert(3,70)
print("2. L2 = ",l2)
l2.remove(50) #remove the given element
print("3. L2 = ",l2)
l2.pop(3)
#l2.clear()
print("4. L2 = ",l2)
l2 = [5,10,15,20,25,30,35,40]
print(l2.count(5))
l1 = [100,200,300]
l1.extend(l2) # l1 = l1 + l2
l1[0] = 999
print("L1 = ",l1)
l1.sort(reverse=True)
print("A. List1: ",l1)
l1.reverse()
print("B. List1: ",l1)

l2 = l1 #copy method 1 - deep copy: adds another name l2 to l1
l3 = l1.copy() #copy method 1
print("C1. List 1: ",l1)
print("C1. List 2: ",l2)
print("C1. List 3: ",l3)
l1.append(33)
l2.append(44)
l1.append(55)
print("C2. List 1: ",l1)
print("C2. List 2: ",l2)
print("C2. List 3: ",l3)
str1 = "hello"
str2 = str1.upper()
print(str2)
print(str1)
#l1

m1= int(input("marks 1:"))
m2= int(input("marks 1:"))
m3= int(input("marks 1:"))
m4= int(input("marks 1:"))
m5= int(input("marks 1:"))
total = m1+m2+m3+m4+m5
avg = total/5
print(m1,m2,m3,m4,m5)
print("Total marks = ",total," and Average = ",avg)

total = 0
for i in range(5):
m1 = int(input("marks:"))
total+=m1
avg = total/5
print("Total marks = ",total," and Average = ",avg)

marks=[]
total = 0
for i in range(5):
m1 = int(input("marks:"))
marks.append(m1)
total+=m1
avg = total/5
print(marks[0],marks[1],marks[2],marks[3],marks[4])
for i in marks:
print(i,end=" ")
print("\nTotal marks = ",total," and Average = ",avg)
########################
####
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 here
I will be here for next 7 days
I 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 python
print("\\n is used to print newline in python")

# \\n will not print newline in python
print("\\\\n will not print newline in python")

str1 = "Hello You"
str2 = "There"
print(str1 + str2)
print(str1 *5)
for i in str1:
print("Hello")

#indexing
print(str1[2])
print("last element: ",str1[4])
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 class
import time
str1 = "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 sentence
para1 = "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=0
for 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+=1
print("Total vowesl = ",sum)
sum=0
for l in para1.lower():
if l=='a' or l=='e' or l=='i' or l=='o' or l=='u':
sum+=1
print("Total vowesl = ",sum)

sum=0
for l in para1.lower():
if l in 'aeiou':
sum+=1
print("Total vowesl = ",sum)

########## LIST
#LIST
#collection of linear ordered items
list1 = [1,2,3,4,5]
print(type(list1))
print("Size = ",len(list1))

print(list1[0])
print(list1[-1])
print(list1[3])
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[0]=10
print(l1)

l1.insert(2,15)
print(l1)

# Queue: FIFO
# Stack: LIFO

if 16 in l1:
l1.remove(16) #takes in value to remove
l1.remove(15)
print(l1)
l1.pop(1) #index
print(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 same
l3 = 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=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)

#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 immutable

tuple1 = (1,3,1,4,1,5,1,6)
print(type(tuple1))
print(len(tuple1))
print(tuple1.count(1))
print(tuple1.index(4))
print(tuple1[2])
for i in tuple1:
print(i)
t1 = list(tuple1)
t1.append(55)
t1=tuple(t1)
t2 = (2,4,6,8) #packing
#unpacking
a,b,c,d,e = t2
print(a,b,c,d)
#packing
# Dictionary
dict1 = {1: "Sachin Tendulkar","Runs": 50000, 'City':'Mumbai','Teams':['Mumbai','Mumbai Indians','India']}
print(dict1['Teams'])
dict2 = {'100s':[50,20,1]}
dict1.update(dict2)
print(dict1)
print(dict1.values())
print(dict1.keys())
print(dict1.items())

#Dictionary are mutable
dict1.pop('City')
print(dict1)
dict1.popitem()
print(dict1)

dict3 = dict1.copy() #shallow copy
dict4 = dict1 #deep copy

all_details={}
while True:
roll = input("Enter Roll Number of the Student: ")
marks=[]
for i in range(3):
m = int(input("Enter the marks: "))
marks.append(m)
temp={roll:marks}
all_details.update(temp)
ch=bool(input("Enter null to continue: "))
if ch:
break

print("All details: ",all_details)
for i, j in all_details.items():
sum=0
for a in j:
sum+=a
print(f"Total marks obtained by {i} is {sum} and average is {sum/3:.1f}")


### SET
'''
A B C D E
D E F G H
How many total (union): 8
How many common(intersection): 2
Remove set2 values from set1: (set1 - set2): 3

'''
set1 = {2,4,6,8,10,12}  #neither have duplicate values nor there is any order
print(type(set1))
set2 = {3,6,9,12}
print(set1 | set2)
print(set1.union(set2))
#print(set1.update(set2)) #meaning union_update
#print(set1)
print(set1 & set2)
print(set1.intersection(set2))
#print(set1.intersection_update(set2))
#print(set1)
print(set1 - set2)
print(set1.difference(set2))
#print(set1.difference_update(set2))
#print(set1)
print(set1^set2)
print(set1.symmetric_difference(set2))
#print(set1.symmetric_difference_update(set2))
#print(set1)

#####
## Functions

#defining a function
def sometxt():
print("Hello")
print("how are you?")
print("I am fine thank you!")
return "Great"

print(sometxt())
a= sometxt()
print(a)

#functions that return values v doesnt return values
# function taking input arguments /  pass - parameters
def function1(x,y,z): #required positional arguments
print("Value of X: ",x)
print("Value of Y: ", y)
print("Value of Z: ", z)

def function2(x,y=15,z=30): #default positional arguments
print("Value of X: ",x)
print("Value of Y: ", y)
print("Value of Z: ", z)

def function3(x,*y,**z):
print("Value of X: ", x)
print("Value of Y: ", y)
print("Value of Z: ", z)

function3(20, 2,4,6,8,10,12,14,16,18,20, fruit="Apple",calorie=150)
a=5
b=6
c=9
function1(a,b,c) #parameters
function2(12)

function2(z=30,x=12) #keywords (non-positional)

VIDEO- Function Types Intro

#Functions

def func1(num1,num2):
print("Number 1 = ", num1)
print("Number 2 = ", num2)
add = num1 + num2
print("Addition = ",add)
return add



def func2(num1,num2=100):
print("Number 1 = ", num1)
print("Number 2 = ", num2)
add = num1 + num2
print("Addition = ",add)
return add


#variable length arguments

def alldata(num1, num2, *var1, **var2):
print("Number 1 = ",num1)
print("Number 2 = ", num2)
print("Variable 1 = ", var1)
print("Variable 2 = ", var2)

if __name__ =="__main__":
result = func1(5, 10) # required positional arguments
result = func2(5) # num1 is required / num2 is default & positional arguments
print("Result of addition is", result)

result = func2(num2=5, num1=25) # keyword arguments (non-positional)
print("Result of addition is", result)

alldata(5, 83, 12, 24, 36, 48, 60, name="Sachin", city="Pune")

# class - definition
# class str - defining some properties to it like split(), lower()
# object is the usable form of class
str1 = "hello"

#creating a class called Library
#in that I added a function called printinfo()
# self: indicates function works at object level
class Library:
#class level variable
myClassName = "Library"

#__init__ - it has predefined meaning (constructor), called automatically
#when you create an object
def __init__(self):
name = input("Init: What's your name?")
self.name = name # self.name is object level

# object level method
def askinfo(self):
name = input("What's your name?")
#self.name = name #self.name is object level

#object level method
def printinfo(self):
myClassName="Temp class"
print(f"{Library.myClassName}, How are you Mr. {self.name}?")

#create object
l1 = Library()
l2 = Library()
l3 = Library()
#l1.askinfo()
#l2.askinfo()
#l3.askinfo()

l2.printinfo()
l3.printinfo()
l1.printinfo()
Learn with Ray

DAY 1:

 

print("Hello")
print('how are you today?')
print(5+4)
print('5+4')
print('5+4=',5+4,'and 6+4=',6+4)
var_1 = 5 #datatype is implicit
print(var_1+10)
#variable naming rule: It shouldnt start with a number, only _ is a allowerd special character
var_1 = 15
print(var_1+10)
#comments are for human
#print() - functions are written to perform certain task

#interpreter (Python R) or compiler (C C++ Java...)

# 5 basic datatypes:
## int - integer - numeric values without decimal part: -999, -99, 0,1,2,99
## float - float - numeric values with decimal part: -5.5, 5.0, 0.0
## complex - complex - numeric values that represent square root of minus 1 (i)
## str - string - text data
## bool - boolean - just two values: True / False

var_1 = 5j
print(var_1 * var_1) #25*-1= -25
print(type(var_1))

#operators & operation
#Arithmetic operators: + - * / // (integer division) ** % (modulus - mod)
num1 = 7
num2 = 3
print(num1/num2)
print(50 // 6)
print(num1 ** num2)
print(50 % 6)

#Comparison operators: == > >= < <= != Will always result in bool values
num1 = 10
num2 = 10
num3 = 15
print(num1 == num2) #is num1 equal to num2 ? True
print(num1 != num3) #is num1 not equal to num2? True
print(num1 > num2) # False
print(num1 >= num2) #True
print(num1 < num2) # False
print(num1 <= num2) #True

#Logical operators = and / or = they work only on boolean value and given bool as result
#prediction1: Argentina and France will play in the Soccar world cup final - True
#prediction2: Argentina or Brazil will play in the Soccar world cup final- True
#actual: Argentina and France actually played in the finals

#and truth table:
# True and True = True
# False and False = False and True = True and False = False

#or truth table:
# False or False = False
# True or True= False or True = True or False = True

a,b,c=5, 10,10
print(a > b and b<c and c==a or c==b or a>c and c<a and b==b and c<a or c==b)

#Conditions
# I want to check if a number is positive or not
num1 = 0
if num1 >0:
print("Number is positive")
print("Line 2 for positive")
elif num1<0:
print("Number is negative")
print("Line 2 for negative")
else:
print("Number is neither positive nor negative")
print("Thank you")


#conditions
#if - elif - else
###
# When +ve: case 1 = 3 , case 2 =3
# When -ve: case 1 = 3 , case 2 =2
# When 0: case 1 = 3 , case 2 = 1
##
num = -50

#case 1
if num==0:
print("Its Zero")
if num <0:
print("Its negative")
if num >0:
print("Its positive")

#case 2
if num==0:
print("Its Zero")
elif num <0:
print("Its negative")
else:
print("Its positive")
#converting one datatype to another - str(), int(),float(),complex(),bool()
marks_in_subject1 = int(input("Enter marks in Subject 1:"))

print(type(marks_in_subject1))
marks_in_subject2 = 8.0
marks_in_subject3 = 88
marks_in_subject4 = 8
marks_in_subject5 = 8
total = marks_in_subject1 + marks_in_subject2 + marks_in_subject3+marks_in_subject4+marks_in_subject5
avg = total/5
print("Average = ",avg)
#avg > 85 - A
# avg>70 - B
# avg > 60 - C
#avg >50 - D
#avg >40 - E
#avg < 40 - F
#avg >=90 - special award
if avg >=85:
print("You got grade A")
if avg>=90:
print("You win Special award")
if avg>=95:
print("You get a Scholarship")
elif avg >=70:
print("You got grade B")
elif avg>=60:
print("You got grade C")
elif avg>=50:
print("You got grade D")
elif avg>=40:
print("You got grade E")
else:
print("You got grade F")


print("Thank You")

#nested

#LOOPS - Repeat
print("Hello")
# Loops - For loop and While loop
#For loop is used when you know how many times you need to repeat
#While loop is used when you dont know exactly how many times but you know the condition
#when to stop

#print hello 5 times
# range(a,b,c) : a=start (inclusive), b = end (exclusive), c=increment
# range(2,8,3) : 2,5
# range(a,b) : a=start, b=end, default increment = 1
# range(2,5) : 2,3,4
# range(b): default start = 0, end=b, default increment of 1
# range(5): 0,1,2,3,4
print("For loop 1:")
for var in range(5):
#print("Value of var is ",var)
print("Hello")

print("Using while: ")

counter = 1
while counter <=5:
counter = counter + 1
print("Hello")
print("Thank You")

DAY 3:

 

#Day 3: Loops
#For loop - along with range() , how many times the loop has to run

for i in range(1,101):
print(i,end="\t")
print()
print("Hello")
#by default print will give us a newline

n,m=5,6
for j in range(m):
for i in range(n):
print("*",end=" ")
print()
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''

n=5
for j in range(n):
for i in range(j+1):
print("*",end=" ")
print()
'''
*
* *
* * *
* * * *
* * * * *
'''

n=5
for j in range(n):
for i in range(n-j):
print("*",end=" ")
print()
'''
* * * * *
* * * *
* * *
* *
*
'''
print("-----")
for j in range(n):
for k in range(n-j-1):
print(" ",end="")
for i in range(j+1):
print("*",end=" ")
print()
'''
*
* *
* * *
* * * *
* * * * *
'''
# check if a number is prime or not
number = 51
# 51 - 1, 51
isPrime = True
for i in range(2,number//2):
if number%i==0:
isPrime=False
break
#break will throw you out of current loop

if isPrime:
print("Number is prime")
else:
print("Number is not Prime")


total = 0
for i in range(1,101):
total=total+i
print("\n total is ",total)

#1: total= 0 + 1 = 1
#2: total = 1 + 2 = 3
#3: total = 3 + 3 = 6

#While
while True:
print("Hello")
if True:
break

import random
random.seed(10)
num = random.random() #generates random number between 0 and 1
print("num = ",num)
num1 = random.randint(1,10) # integer values - between 1 and 10 (both inclusive)
print("num1 = ",num1)
attempts = 0
actual = 45 #random.randint(1,100)
while True:
guess = int(input("Enter your guess number:"))
attempts=attempts+1
if actual == guess:
print(f"Congratulations! You have guessed it correctly in {attempts} attempts")
break
elif actual < guess:
print("You missed it! Your Guess is higher")
else: #actual >guess
print("You missed it! Your Guess is lower")
#Strings
var1 = 'hello'
print(type(var1))
var2 = "good morning"
print(type(var2))
var3 = '''Hi there
where are you going
I am here till you come'''
print(type(var3))
var4 ="""Hows going
I was waiting to talk to you
see you soon"""
print(type(var4))
print(var3)
print(var4)

# What's your name?
var5 = "What's your name?"
print(var5)

# He asked,"How are you"?
print('He asked,"How are you"?')

# He asked,"What's your name"?
print('''He asked,"What's your name"?''')
print("He asked,\"What\'s your name\"?")
var1 = 'hello'
print('H' in var1)
for i in var1:
print(i)
# 'y' 'a' "yes" "no" "name"

# ' or " can only take one line of text
#''' or """ can take multi line text

# [] square brackets are used for indexing
print("=====> 1. ",var1[4])
print("=====> 1. ",var1[-1])
print("=====> 2. ",var1[0:4])
print("=====> 3. ",var1[:4])
print("=====> 3. ",var1[-5:-1])
print("=====> 3. ",var1[:-1])
print("=====> 4. ",var1[-3:])

#len()
print("Length = ",len(var1))

for i in range(len(var1)):
print(var1[i])

var1 = "hello"
var2 = "Good Morning"
print(var1,var2)
print(var1 + " and "+(var2+ " ")*3)
#Strings
str1 = "hellothere" #str1 is an object of class str
str2 = "49534095834"
print("str2.isdigit(): ",str2.isdigit())
print("str1.isdigit(): ",str1.isdigit())
print("str1.isalpha()",str1.isalpha())
print(" ".isspace())
str1.isalnum()
str1 = "hello there 123"
print("str1.islower(): ",str1.islower())
str1.isupper()
str1.istitle()

ch=input("Enter Y to continue: ")

#username - username can have only alphabet and/or number

#first name - ABC XYZ

#methods (function in a class) v functions -independent

num1 = input("Enter a number: ")
if num1.isdigit():
num1=int(num1)
else:
print("You have not entered a valid number hence setting num1 to zero")
num1 = 0
print("num1 = ",num1)

# Exception Handling - to handle runtime errors - preferred

str1 = "HELLO"
#strings are immutable
print(str1[0])
#str1[0] = "K" #TypeError: 'str' object does not support item assignment
#str1 = "KELLO"
str1 = "K"+str1[1:]
print(str1)

str2="How are YOU? your Where are you? you are welcome"
str3 = str2.lower().replace("you","they",2) #old,new,count
print("After Replace: ",str3)
print("you" in str2)
print(str2.lower().find("you",9)) #find: substring, start, end

var1 = str2.split("o")
print(var1)
str5 = "o".join(var1)
print(str5)

#abc => abcing
#abing = abingly
inp_txt = input("Enter the word: ")
output=""
if inp_txt[-3:].lower()=="ing":
output= inp_txt+"ly"
else:
output = inp_txt+"ing"
print("Output text is",output)


str1 = "How are you doing today and whats plan for tomorrow"
l_str = ""
curr_str = ""
inx = 0
for c in str1:
inx+=1
if inx==len(str1):
curr_str = curr_str + c
if c.isspace() or inx==len(str1):
if len(curr_str) > len(l_str):
l_str=curr_str
curr_str=""
else:
curr_str=curr_str+c

print("Largest text is",l_str)
Python Zero to Hero
### DAY 1
print("Welcome")

val1 = 5
#val1 is a variable in this case
print("val1")
print("Value of variable val1 =",val1)

#type() - it gives the datatype of variable
print(type(val1)) # <class 'int'> integer: nondecimal value- -5, -99,0,9999999

val1 = 5.8
print("Value of variable val1 =",val1)
print(type(val1)) # <class 'float'> float: number with decimal value- -5.0, -99.1,0.0,9999999.5

val1 = 5j #it is same as i of Maths, square root of -1
print("Value of variable val1 =",val1)
print(type(val1)) # <class 'complex'>
print(val1 * val1)

val1 = "Good evening"
print("Value of variable val1 =",val1)
print(type(val1)) #<class 'str'> string - all kinds of text
val1 = "55"
val2 = 55
val3 = 44;val4 = "44";print(val1 + val4);
print(val2 + val3)

val1 = True #/ False
print("Value of variable val1 =",val1)
print(type(val1)) #<class 'bool'> - boolean just 2 values: True and False

# input() - used to read value from the user

name = input("Enter your name: ")
print(name)

## DAY 2: 11 DEC 2022
name = input("Enter your name: ") #automatically its gets converted into str - implicit conversion
marks1 = input("Enter marks in Subject 1: ")
marks1 = int(marks1) #explicit conversion
marks2 = int(input("Enter marks in Subject 2: "))
marks3 = int(input("Enter marks in Subject 3: "))
print(type(name))
print(type(marks1))

sum = marks1 + marks2 + marks3
avg = sum / 3
print(name, "scored a total of",sum,"marks at an average of",avg)

# f string - format string
print(f"{name} scored a total of {sum} marks at an average of {avg:.2f}%")

# <class 'str'> str()
# <class 'int'> int()
# <class 'float'> float()
# <class 'complex'> complex()
# <class 'bool'> bool()

length = int(input("Enter the length of the rectangle: "))
breadth = int(input("Enter the breadth of the rectangle: "))
area = length * breadth
perimeter = 2* (length + breadth)
print(f"The rectangle with dimensions {length} and {breadth} has an area of {area} and perimeter of {perimeter}")

#Operators
#math operations - Arithmetic operations
val1 = 10
val2 = 3
print(val1 + val2)
print(val1 - val2)
print(val1 * val2)
print(val1 / val2)
print(val1 ** val2) #power of val2
print(val1 // val2) #integer division -will result in integer only
print(val1 % val2) #modulo - remainder
print(16 ** 0.5)

#Comparison operators: == != < <= > >=
# input can be anything but output will always be BOOL value
a=10
b=3
c=10
print(a==b) #False
print(a!=b) #True
print(a==c) #True
print(a!=c) #False

print(a>b) #True
print(a>=c) #True
print(a<=c) #True
print(a<c) #False

#logical operators : AND OR NOT
#input has to be bool and output is also bool
#prediction; Sachin and Sehwag will open the batting for India
#actual: Sachin and Dravid opened the batting for India
# result - prediction is wrong

#prediction; Sachin or Sehwag will open the batting for India
#actual: Sachin and Dravid opened the batting for India
# result - prediction is Correct
print("Logical Operator:")
print(5>3 and 2 <6 or 8==9 and 7!=9 or 5!=7 and 10==10 or 4<5)

#T and T or F and T or T and T or T

#DAY 2: 12 DEC 2022
#########################
## Quadratic equation is of form: ax^2 + bx + c

# Discriminant: D = b^2-4ac
# (-b +/- sq root(D)) / 2a

# 3 x2 +x+5 = 0
a=3
b=1
c=5
D = b**2 - 4 * a * c
sol1 = (-b - D**0.5)/(2*a)
sol2 = (-b + D**0.5)/(2*a)

if D<0:
print("Discriminat: ",D)
print("Discriminant is -ve hence we have imaginary values for the x")
print(f"The value of x for the given quadratic equation is {sol1} and {sol2}")

#Prob 2: 2x2 -12x - 54 = 0
#sol1 = -3, 18 +36 - 54 = 0
#sol2 = 9: 162 -108 -54 = 0
a = 2
b = -12
c = -54
D = b**2 - 4 * a * c
sol1 = (-b - D**0.5)/(2*a)
sol2 = (-b + D**0.5)/(2*a)
if D<0:
print("Discriminant is -ve hence we have imaginary values for the x")
elif D>0:
print("Dicriminant is real and has 2 unique solutions")
print("Discriminat: ", D)
print(f"The value of x for the given quadratic equation is {sol1} and {sol2}")
else:
print("Dicriminant is real")
print("Dicriminant is real and has only one unique solution")
print(f"The value of x for the given quadratic equation is {sol1}")

number =-6
if number<0:
print("Its a negative number")
elif number>0:
print("Its positive number")
if number %2==0:
print("Its an even number")
if number%3==0:
print("The number is divisble by both 2 and 3")
else:
print("The number is divisble by 2 but not by 3")
else:
print("Its an odd number")
if number%3==0:
print("The number is divisble by only 3")
else:
print("The number is neither divisble by 2 nor by 3")
else:
print("Its zero")

marks1 =98
marks2 = 88
marks3 = 99
sum= marks1 + marks2 + marks3
avg = sum/3
print("Average marks obstained is :",avg)
if avg >=80:
print("Grade A")
if avg >=90:
print("You win President award")
elif avg >=70:
print("Grade B")
elif avg >=60:
print("Grade C")
elif avg >=50:
print("Grade D")
elif avg >=40:
print("Grade E")
else:
print("Grade F")

### DAY 4:
###################
#LOOPS - While loop - until condition is true
choice = "y"
while choice=="y" or choice=="Y":
print("Hello")
choice = input("Please type y to continue or anyother key to stop: ")



# For loop -
#range(a,b,c) : a=start value (inclusive), b=ending value(exclusive), c=increment value
# range() generates a range of values
# range(3,8,2) = 3,5,7
# range(3,9,2) = 3,5,7
# range(a,b) => c is default 1 (increment is 1)
# range(3,7) => 3, 4,5,6
# range(b) => default a = 0 , default c = 1
# range(4) => 0,1,2,3

for i in range(4):
print("Hello: ",i)

for i in range(3,8,2):
print("Hello: ",i)

print("hello",end=" ")
print("how",end=" ")
print("are",end=" ")
print("you")

for i in range(5):
print("*")

for i in range(5):
print("*",end=" ")
print()
start = 1
end = 10
for i in range(start,end+1):
if i ==end:
print(i)
else:
print(i,end=", ")

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

k = 1
for j in range(5):
for i in range(k):
print("*", end=" ")
print()
k += 1 # k = k+1

### Assignment
'''
*
* *
* * * *
* *


'''

### DAY 5: 14 DEC 2022
### ###############
#While
# if marks <0 and >100 it should ignore it


while True:
name = input("Enter the name of the student: ")
sum = 0
sub_count = 0
while sub_count <=2:
marks = int(input("Enter marks in subject "+str(sub_count+1)+": ",))
if marks >100 or marks <0:
print("Invalid marks try again!")
continue
sub_count+=1
sum+=marks
avg = sum/3
print(f"The total marks obtained is {sum} and the average is {avg:.2f}")
choice = input("Please enter y to continue or anyother key to stop: ")
if choice !="y" and choice!="Y": #y
break #it throws you out of the current loop

#continue is a command that will take you to the beginning of the loop
#WAP to guess the number between 1 and 100
num = 50
count = 0
max_try = 10
while True:
guess=int(input("Guess the number: "))

if guess<0 or guess>100:
print("Invalid option try again!")
continue
count+=1
if guess == num:
print(f"Congratulations, you have guessed it right in {count} steps!")
break
elif guess < num:
print("The actual number is higher!")
else:
print("The actual number is lower!")
if count >=max_try:
print("You have reached the maximum tries. Please stop")
break

#WAP to guess the number between 1 and 100
import random
num = random.randint(1,100)
count = 0
max_try = 10
while True:
guess=int(input("Guess the number: "))

if guess<0 or guess>100:
print("Invalid option try again!")
continue
count+=1
if guess == num:
print(f"Congratulations, you have guessed it right in {count} steps!")
break
elif guess < num:
print("The actual number is higher!")
else:
print("The actual number is lower!")
if count >=max_try:
print("You have reached the maximum tries. Please stop")
break

####
number = 50
steps=0
print("Number Guessing Game! Guess the Number Between 1 and 100.")
while True:
check = int(input("Enter the value to check: "))
if check<1 or check>100:
print("Invalid Value. Please Try Again!")
continue
steps+=1
if check==number:
print(f"Value Matched! You got it right in {steps} steps.")
break
elif check <number:
print("Value is smaller. Please Try Again!")
else:
print("Value is greater. Please Try Again!")

list_of_value = [5,10,15,20,25,30,35] #LIST
print(type(list_of_value))
print(list_of_value)
print(list_of_value[2])

l1 = [5,10,15,20,25,30,35]
print(l1*3)

#append
list_of_value.append(45)
list_of_value.insert(2,12)
print(list_of_value)
#insert

# Battleship Challenge
import random
battle_pattern = []

total_rows = 5
total_cols = 5
for i in range(total_rows):
battle_pattern.append(['0 ']*5)

# created a function named display_battle() - user defined function
def display_battle(pattern):
for p in pattern:
print(" ".join(p))

display_battle(battle_pattern)
missle_row = random.randint(0,total_rows-1)
missle_col = random.randint(0,total_cols-1)
print(f"HINT: Missile is at Row: {missle_row} column {missle_col}")

#Try to attack
for y in range(4):
pred_row = int(input("Input the x corrodinate: "))
pred_col = int(input("Input the y corrodinate: "))

if pred_row == missle_row and pred_col ==missle_col:
print("Congratulations ! Missle destroyed")
break
elif pred_row >4 or pred_col > 4:
print("What are you doing? Where are you shooting?")
elif battle_pattern[pred_row][pred_col] =="X ":
print("You have already got that wrong! A chance wasted!")
else:
print("Missle not found at the location")
battle_pattern[pred_row][pred_col] = "X "
display_battle(battle_pattern)


#While loop

while True:
sum = 0
for i in range(3):
marks1 = int(input("Enter the marks: "))
sum+=marks1
avg = sum/3
print("Average of marks is:",avg)
ch = input("Press Y to continue or any other key to stop: ")
if ch!='y':
break #it breaks the loop - throw you out of the loop

# we find sum of all positive numbers that are entered, enter -999 to stop accepting

sum=0
while True:
value = int(input("Enter the value:"))
if value==-999:
print("Sum of all the positive numbers that you have entered = ",sum)
break
if value<=0:
print("Negative value hence ignoring!")
continue #you will be pushed to the beginning of the loop
sum+=value

#Strings
val1 = "Hello" # str with "
print(type(val1))
val1 = 'Welcome'
print(type(val1))
val1 = '''How are you?
where are you?
How long will you be there?'''
print(type(val1))
print(val1)
val1 = """I am fine
I am in your city
I will be here for next 7 days"""
print(type(val1))
print(val1)

# What's your name?
val2 = "What's your name?"
print(val2)
# He asked,"Where are you going?"
val2='He asked,"Where are you going?"'
print(val2)
# He asked,"What's your name?"

print('''He asked,"What's your name?"''')
print("He asked,\"What's your name?\"")

val1 = "Good"
val2 = "Evening"
print(val1+val2)
print(val1*3)
sum=0
for i in val2:
if i=='a' or i=="e" or i=='i' or i=="o" or i=="u":
sum+=1
print(f"Given text has {sum} vowels")

sum=0
for i in val2.lower(): #lower() converts into lowercase
if i=='a' or i=="e" or i=='i' or i=="o" or i=="u":
sum+=1
print(f"Given text has {sum} vowels")

#in - membership test - left side value is present in the right side or not
sum=0
for i in val2.lower(): #lower() converts into lowercase
if i in "aeiou": #True only if i value is present in right side text
sum+=1
print(f"Given text has {sum} vowels")

text1 = "Hello all"
#len() - counts the number of characters
print("Total characters in text1 is",len(text1))

#indexing - extracting portion of the data - subset
# [] is used for indexing
print(text1[0]) #first member of text1
print(text1[2]) #third member of text1
print(text1[len(text1)-1]) #last member
print(text1[len(text1)-3]) #third last member

print(text1[-1]) #last member
print(text1[-3]) #third last member

###### 17 DECEMBER 2022 ##########
str1 = 'Hello'
str2 = "Good"
str3 = '''How are you?
Where are you?'''
str4 = """I am fine"""
str5 = "What's your name?"
print(str5)
str6 = 'He asked,"How are you?"'
print(str6)

#He asked,"What's your name?"
print('''He asked,"What's your name?"''')
print('He asked,"What\'s your name?"')

text1 = "Good Evening"
print(text1[0])
print(text1[-1])
print(text1[1:4]) #from second character to 5th (upto)
tot_chars = len(text1)
print(text1[tot_chars-3:tot_chars]) # 9 to 12
print(text1[tot_chars-3:])
print(text1[:])
print(text1[-11:-8])
print(text1[-3:])

print("Good"+"Morning"*3)
for i in text1:
print(i,end="")
print()
txt1 = "how are you?"
print(txt1.lower())
print(txt1.upper())

print(txt1.islower())

txt3="GoOD mOrNIng"
txt4 = ""
#lowercase to upper and uppercase to lowe
for i in txt3:
if i.islower():
txt4=txt4+i.upper()
else:
txt4 = txt4 + i.lower()
print(txt4)
#want to count the number of spaces a text has
txt3="Go OD mOrN I n g "
count=0
for i in txt3:
if i.isspace():
count+=1

print("Total spaces: ",count)
cnt = txt3.count("O")
print("Total spaces = ",cnt)

cnt = txt3.lower().count("o")
print("Total spaces = ",cnt)
txt4 = "How are you doing and where are you going"
print(txt4.split())
txt6 = " - ".join(['How', 'are', 'you', 'doing', 'and', 'where', 'are', 'you', 'going'])

print(txt6)

marks = input("Enter marks: ")
if marks.isdigit():
marks = int(marks)
else:
print("Invalid marks")

# username can have only alphabet or number
marks = input("Enter username: ")
if marks.isalnum():
print("Username accepted")
else:
print("Invalid username")

######### 28 DEC 2022 - LIST
#List
l1 = [50,30,40.5,"Hello",[4,6,8]]
print(type(l1))
print(len(l1))
print(l1[0])
print(type(l1[0]))
l2 = l1[-1]
print(type(l2))
print(l1[-1][1])
print([10,20,30]+[4,5,6])
print([10,20,30] * 3)

a=5
#print(a[0])
val = [10,20,30]
for i in val:
print(i)

#methods of list
val = [10,20,30]
val.append(40)
val[0] = 100
print(val)

str1="hello"
#str1[0]= "H"
str1 = str1.upper()
print(str1)

# strings are immutable whereas Lists are mutable (editable)
val.insert(1,200)
print(val)
val.pop(2) #takes index
print(val)
val.remove(200)
print(val)
val1 = [6,12,18,24]
val2 = val+val1
print(val2)
val.extend(val1) # val = val + val1
print(val)

for i in range(3):
val.pop(1)
print(val)
val = [100, 30, 40, 6, 12, 18, 24]
print(val)
#remove position 2,4,6 = [2,3,5] [6,4,2]
for i in [6,4,2]:
val.pop(i)
print(val)
val = [100, 30, 40, 6, 12, 18, 24]
print(val)
#remove values 100, 40, 12
for i in [100, 40, 12]:
val.remove(i)
print(val)
val = [100, 30, 40, 6, 12, 18, 24]
val.sort()
val.reverse()
print(val)

## get marks of 5 subjects and do the sum and avg
master_list = []
while True:
sum = 0
marks_list = []
for i in range(5):
marks = int(input("Enter the marks in subject "+str(i+1)+": "))
sum+=marks
marks_list.append(marks)
avg = sum/5
print(f"Marks entered are: {marks_list} \nThe total marks obtained is {sum} and average is {avg}")
ch = bool(input("Enter any key to continue or blank to stop: "))
master_list.append(marks_list)
if not ch:
break


print("Master List: ",master_list)


'''
[[99, 88, 77, 66, 55],
[75, 86, 97, 58, 69],
[59, 74, 68, 78, 76]]

list[0][0]
'''
master_list = [[99, 88, 77, 66, 55], [75, 86, 97, 58, 69], [59, 74, 68, 78, 76]]
students = ["Kapil","Sunil","Dhoni"]
subjects = ["English","Hindi","Maths","Science","Social"]

'''
Kapil Sunil Dhoni
English
Hindi
Maths
Science
Social
'''

print(end="\t\t")
for i in range(len(students)):
print(students[i],end="\t\t")
print()

#col_ind = 0
for col_ind in range(5):
print(subjects[col_ind],end="\t")
for row_ind in range(3):
print(master_list[row_ind][col_ind],end="\t\t\t")
print()


################
'''
Input:
Year: 2022
Month: 12
Date: 19
Output:
19th December 2022
'''
Months = ['January','February','March','April','May','June','July','August','September',
'October','November','December']
ending = ['st','nd','rd'] + 17*['th'] + ['st','nd','rd'] + 7*['th'] + ['st']
year= input("Year: ")
month_num = int(input("Month: "))
date_num = int(input("Date: "))
result = str(date_num)+ ending[date_num-1]+' '+Months[month_num-1]+' '+year
print(result)

# Tuple
#Same as list - linear but difference is its immutable
t1 = (2,4,6,7,8,9,2,4,2,4,2,4)
print(type(t1))
print(t1.count(2))
print(t1.index(6))
print(t1[-1])
for i in t1:
print(i, end=", ")
print()
#Lists can be converted to Tuple and vice versa
t1 = list(t1)
print(type(t1))
t1 = tuple(t1)

t1 = ()
t1 = (1,)
print(type(t1))
t1 = (1,2,3,4,5) #packing
a,b,c,d,e = t1 #unpacking

val1 = (3,4,6)
val2 = (3,1,88)


#packing and unpacking

#Dictionary
details = {
"name": "Sachin T", "Runs": 15000, "Runs_desc": "Too many","City" : "Mumbai"
}
print(type(details))
print(details)
print(details["City"])
details2 = {
"team1":"Mumbai", "team2":"Mumbai Indias","team3": "India"
}
details.update(details2)
print(details)


## get marks of 5 subjects and do the sum and avg
master_list = {}
while True:
sum = 0
marks_list = []
name=input("Name of the student: ")
for i in range(5):
marks = int(input("Enter the marks in subject "+str(i+1)+": "))
sum+=marks
marks_list.append(marks)
avg = sum/5
print(f"Marks entered are: {marks_list} \nThe total marks obtained is {sum} and average is {avg}")
ch = bool(input("Enter any key to continue or blank to stop: "))
master_list.update({name:marks_list})
if not ch:
break

print("All information: \n",master_list)

t1 = (2,4,6,8)
print(t1)
t1=list(t1)
t1.append(10)
t1 = tuple(t1)
print(t1)

# Dictionary
dict1 = {"name": "Sachin",101: "Mumbai","Teams":["India","Mumbai","Mumbai Indians"]}
dict2 = {"Runs": 15000}
print(type(dict1))
print(dict1['name'])
dict1.update(dict2)
print(dict1)
print(dict1.keys())
for i in dict1.keys():
print(i, "->",dict1[i])

for i,k in dict1.items():
print(i,"->",k)
for j in dict1.values():
print(j,end=", ")
print()
dict1.popitem()
dict1.pop(101)
print(dict1)


boys = {1:"Rohit",2:"Rahul",3:"Kohli", 4:"Surya"}
girls = {11:"Harmanpreet", 21:"Smriti",31:"Poonam",41:"Taniya"}

#equal to = points to same value
dict1 = boys
print(dict1)
#copy - creates duplicate copy
players = dict1.copy()
print(players)
players.update(girls)
print(players)

p_type = []
for i, j in players.items():
if j in boys.values():
p_type.append("Boy")
elif j in girls.values():
p_type.append("Girl")
else:
p_type.append("NA")
print("Final list: ",p_type)

#Set
# D M C K P
# P D M K C
# P P P P P
set1 = {"Pune","Pune","Pune","Pune","Pune"}
print(type(set1))
print(set1)

list1 = [4,5,6,4,5,6,7,8,7,8,8,8,8]
print(list1)
list1 = set(list1)
list1 = list(list1)
print(list1)

#SET THEORY
set1 = {2,4,6,8}
set2 = {1,3,5,7,2,6,8,4}
print(type(set1))
for i in set1:
print(i)

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

#INTERSECTION
print(set1 & set2)
print(set1.intersection(set2))

#DIFFERENCE
print(set1 - set2)
print(set1.difference(set2))

print(set2 - set1)
print(set2.difference(set1))

print(set1.symmetric_difference(set2))

print(set2.issuperset(set1))


#Functions: user defined functions
def myfunction1(a,b,c):
"""This is my own function to do something something
to just implement the function concept
@a: just a number
@b: another number
@c: another number
return: it returns the sum of a b and c"""
print(f"a={a}, b={b},c={c}")
print(a+b+c)
return a+b+c

def myfunction2(a,b=100,c=50): #default arguments
print(f"a={a}, b={b},c={c}")
print(a+b+c)

#keyword arguments (non-positional)
def myfunction3(a,b,c):
print(f"a={a}, b={b},c={c}")
print(a+b+c)

print("Here are a list of questions you need to ask:")
output = myfunction1(5,15,25)
print("Result is ",output)

myfunction2(20,30)
myfunction3(c=30,a=20,b=10) #keyword
l1 = [2,4,6]
putput = l1.append(8)
print(putput)
print(l1)

#1 required positional argument
print(myfunction1.__doc__)

import random
word_list = ["hello", "python","computer","india"]
word = random.choice(word_list)
#print(word.find("l"))
display_txt = "* "*len(word)
print("HINT: ",display_txt)
while True:
guess = input("Guess the character (a-z):")
guess = guess[0].lower()
if guess in word:
cnt_guess = word.count(guess)
st = 0
for i in range(cnt_guess):
idx = word.find(guess,st)
#0 -0 1 - 2 2 -4
display_txt = display_txt[:2*idx] + guess + display_txt[2*idx+1:]
st = idx+1
else:
print(f"{guess} not in the given word")
print(display_txt)
if "*" not in display_txt:
print("Congratulations! You have correctly guessed the word")
break

def input_num(n=0):
""" This function take number of elements for the size of list
and then takes the values, and returns list of values after using input"""
list1 = []
for i in range(n):
num = int(input("Enter number "+str(i+1)+": "))
list1.append(num)
return list1

def checkPrime(num):
isPrime = True
for i in range(2,num):
if num%i==0:
isPrime = False
return isPrime

def list_factors(num):
list_all_factors=[]
for i in range(1,num+1):
if num%i==0:
list_all_factors.append(i)
return list_all_factors

def create_fibo(n):
list_fibo = []
prev1,prev2=0,1
for i in range(n):
if i==0:
list_fibo.append(0)

elif i==1:
list_fibo.append(1)

else:
list_fibo.append(prev1+prev2)
prev1,prev2=prev2, prev1+prev2
return list_fibo

def sorting_val(type,*numbers, **address):
numbers=list(numbers)
if type==1: #bubble sort
for i in range(len(numbers)-1):
for j in range(len(numbers)-1-i):
if numbers[j]>numbers[j+1]:
numbers[j],numbers[j+1] = numbers[j+1], numbers[j]
print("Sorted elements are: ",numbers)
print("Address: \n",address)

items = int(input("Enter the number of elements to be declared: "))
values = input_num(items)
for value in values:
res = checkPrime(value)
if res:
print(f"The element {value} is a Prime,")
else:
print(f"The element {value} is not a Prime number.")
print(f"Factors of element {value} are: {list_factors(value)}")

values = create_fibo(items)
print("Values are: ",values)

sorting_val(1,12,5,17,18,7,19,3,4,7,name="Sachin", sports = "Cricket",city="Mumbai")


Access All the content on your Android Phone - Download Story Mantra App today!