Swapnil Saurav

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


Data Analytics Jan 2023

https://learn.swapnil.pwLearn and Practice Python

 

Refer Python notes here for installation of software:   https://learn.swapnil.pw

#Scipy - scientific python
import scipy

#Permutation & Combination
## Both are about choosing r things from given n things
## default case replacement is not allowed

## Permutation order is important - n! / (n-r)!
## Combination is where order is not important - n! /(n-r)! r!

## 6 B & 4 G - I need to form a committe with 4 members, there has to be atleast a Boy
## 3B - 1G - x1
## 2B - 2 G - x2
## 1B - 3G - x3
## 4B - x4
## total= x1 + x2 + x3 + x4
from scipy.special import comb, perm
sum = 0
cnt = comb(6,3,repetition=False) * comb(4,1)
sum+=cnt
cnt = comb(6,2) * comb(4,2)
sum+=cnt
cnt = comb(6,1) * comb(4,3)
sum+=cnt
cnt = comb(6,4) * comb(4,0)
sum+=cnt
print("Total combination possible is ",sum)

#Permutation
# 4 coats, 5 waist coats, 6 caps - 3 members
#abcd lmnop
cnt1 = perm(4,3)
cnt2 = perm(5,3)
cnt3 = perm(6,3)
print("Total permutation = ", cnt1*cnt2*cnt3)

#####################################
######### OPTIMIZATION PROBLEM #####
#####################################
# There is a company that makes: laptops (profit = 750) and desktops (1000)
#objective is to Maximize profit
# x = no. of laptops = 750x
# y = no. of desktops = 1000x
#solution = 750x + 1000y
## constraint 1 =Processing chips = 10,000 = requires 1 chip each
## ==> x + y <= 10,000
## Memory chipset 1 GB size - Latops need 1GB memory , Desktops need 2GB
## ==> x + 2y <= 15,000
##Time to assemble 1 laptop = 4min, desktop = 3min, total time 25,000 min available
## ==> 4x + 3y <=25,000

## x+y <= 10
## x+2y <=15
## 4x+3y <=25
import numpy
from scipy.optimize import linprog, minimize,LinearConstraint



l = 1 #num of laptops
d = 1 #num of desktops
profit_l = 750
profit_d = 1000
total_profit = l*profit_l + d * profit_d
objective =[-profit_l, -profit_d] #minimization problem
## x+y <= 10
## x+2y <=15
## 4x+3y <=25
lhs_cons = [[1,1],
[1,2],
[4,3]]
rhs_val = [10000,
15000,
25000]
bnd = [(0,float("inf")),(0,float("inf"))]
optimize_sol = linprog(c=objective, A_ub=lhs_cons, b_ub=rhs_val,bounds=bnd,method="revised simplex")
if optimize_sol:
print(optimize_sol.x[0], optimize_sol.x[1])
print("Total profit = ",optimize_sol.fun*-1)


print("==================")
lhs_cons=[]
rhs_val=[]
while True:
l1 = int(input("Enter the value for notebook: "))
l2 = int(input("Enter the value for desktop: "))
y1 = int(input("Enter the value for Y: "))
lhs_cons.append([l1,l2])
rhs_val.append(y1)
ch=input("Do you have more constraints: ")
if ch!="y":
break
print("LHS Constraints = ",lhs_cons)
print("RHS Values = ",rhs_val)

#Pandas - dataframe - is a way to read data in table format (row & column)
import pandas as pd

data = [["Sachin",47],["Virat",33],["Rohit",35]]
df1 = pd.DataFrame(data,columns=['Name','Age'])
print(df1)
import pandas as pd
import sqlite3
con_str = sqlite3.connect("LibraryMS.db")
cursor = con_str.cursor()
q1 = "select * from students"
rows = cursor.execute(q1)
list2 = list(rows.fetchall())

con_str.close()
data_df = pd.DataFrame(list2)
print(data_df)

list1=[["Q1 2022",2300,3400,1900],
["Q2 2022",2300,3400,1900],
["Q3 2022",2300,3400,1900],
["Q4 2022",2300,3400,1900]]
print(list1)
columns=["Quarter","Apple","Banana","Oranges"]
ind=["Jan-March","April-June","Jul-Sep","Oct-Dec"]
data_df = pd.DataFrame(list1, columns=columns,index=ind)
print(data_df)
# df.iloc & loc
print(data_df.iloc[0:3,-3:])
print(data_df.iloc[0:3,[1,3]])

print(data_df.loc[['Jan-March',"Oct-Dec"],['Apple',"Oranges"]])

import pandas as pd

data_df1 = pd.read_csv("https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/user_usage.csv")
print(data_df1)
data_df2 = pd.read_csv("https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/user_device.csv")
print(data_df2)
import pandas as pd
import unicodedata
import nltk


#remove accent functions
def remove_accent(text):
txt = unicodedata.normalize('NFKD',text).encode('ascii',errors='ignore').decode('utf-8')
return txt
#getting the stop words set
STOP_WORDS = set(remove_accent(word) for word in nltk.corpus.stopwords.words('portuguese'))

#defining a function to perform NLP processes
def nlp_analysis_1(comment):
#nlp 1. convert to lowercase
comments = comment.lower()
#nlp 2. remove accents
comments = remove_accent(comments)
#nl 3. tokenize the content
tokens = nltk.tokenize.word_tokenize(comments)
return tokens

reviews = pd.read_csv("C:\\Users\\Hp\Downloads\\OnlineRetail-master\\order_reviews.csv")
#print(reviews['review_comment_message'])
#Step 1: removed the null values
comment_text = reviews[reviews['review_comment_message'].notnull()].copy()
print(comment_text.columns)
comment_text['review_comment_message'] = comment_text['review_comment_message'].apply(nlp_analysis_1)
print(comment_text['review_comment_message'])

SQL Learning

livesql.oracle.com

Select * from hr.employees;

 

select first_name, last_name,hire_date,salary from hr.employees;

 

select first_name FirstName, last_name,hire_date,salary from hr.employees;

 

select first_name || ‘ ‘|| last_name  FULLNAME,hire_date,salary from hr.employees;

 

select first_name || ‘ ‘|| last_name  FULLNAME,hire_date,salary *12 ANNUAL_SALARY from hr.employees;

 

select first_name || ‘ ‘|| last_name  FULLNAME,hire_date,salary *12 ANNUAL_SALARY from hr.employees order by Last_name;

 

 

select first_name || ‘ ‘|| last_name  FULLNAME,hire_date,salary *12 ANNUAL_SALARY 

from hr.employees 

order by Hire_date, Last_name;

 

select first_name || ‘ ‘|| last_name  FULLNAME,hire_date,salary *12 ANNUAL_SALARY , COMMISSION_PCT

from hr.employees 

order by COMMISSION_PCT NULLS First;

 

 

select first_name “First Name”, last_name,hire_date,salary from hr.employees;

 

select first_name, last_name,hire_date,salary from hr.employees where salary>=9000;

 

select first_name, last_name,hire_date,salary from hr.employees 

where salary>=9000 and salary <=12000;

 

select first_name, last_name,hire_date,salary from hr.employees 

where salary BETWEEN 9000 and 12000;

 

select first_name, last_name,hire_date,salary, DEPARTMENT_ID from hr.employees 

where salary>=9000 or DEPARTMENT_ID =80;

 

select distinct salary from hr.employees;

 

— Tendulkar  9000

— Tendulkar  15000

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!
Data Analytics Nov 2022- Part 2

DAY 21

 

select * from HR.Employees;

 

— explicit conversion

select Last_name, Hire_date, to_char(hire_date, ‘MONTH DD, YYYY’), Salary, to_char(salary,’$999999.9′) from HR.Employees;

 

select ‘12345.66’, to_number(‘12345.66′,’9999999’) from Dual

 

select ‘December 11, 2022, 6:00 AM’, To_date(‘December 11, 2022, 6:00 AM’, ‘Month dd, YYYY, HH:MI AM’) from Dual

 

— Multiple conditions

Select Decode(‘BBC’,’ABC’,’Text Matched to ABC’,DECODE(‘CBC’,’BBC’,’Text Matched to BBC’,’Something else’)) from Dual

 

Select Decode(Hire_date, ’17-JUN-03′,’FIRST DAT AT WORK’,’OLD TIMER’) from hr.employees

 

Select last_name, salary, case  When Salary <6000 then ‘Grade 1’

                                    When Salary >=6000 and Salary <12000   then ‘Grade 2’

                                else ‘Grade 3’

                                End Case 

                                from hr.employees;

                                

 

—  Aggregate Functions – which will aggregate and give single result

 

select count(*) from hr.employees

 

select avg(Salary) from hr.employees

 

select sum(Salary) from hr.employees

 

 

select count(*) ‘Total Employees’ , avg(Salary) ‘Average Salary’,  sum(Salary) ‘Total Salary’, Min(Hire_date) ‘Oldest Employee’, Max(Hire_date) ‘Newest Employee’ from hr.employees

 

select count(*) Total , avg(Salary) Average,  sum(Salary) “Total Salary”, Min(Hire_date) Oldest , Max(Hire_date)  from hr.employees

 

select DEPARTMENT_ID,JOB_ID, avg(salary) from hr.employees  group by Department_ID, JOB_ID  HAVING  avg(salary) >10000

 

— JOIN

select convert(int, 12.99) from dual


select cast(12.99 as int) from dual


select * from hr.employees


select * from hr.departments


select * from hr.locations


— Inner join (default)

select department_name, first_name Manager from  hr.departments d join hr.employees e on (e.EMPLOYEE_ID = d.manager_id)


select department_name, first_name from  hr.departments d , hr.employees e



select department_name, first_name, last_name from  hr.departments d join hr.employees e on (e.department_ID = d.department_ID)


select department_name, first_name, last_name from  hr.departments d join hr.employees e Using (department_ID)  order by DEPARTMENT_NAME DESC


— LEFT /RIGHT OUTER JOIN based on + sign

select department_name, first_name from  hr.departments d , hr.employees e where e.department_ID = d.department_ID(+) 


— Full outer Join

select department_name DEPARTMENT, x.department_ID, first_name, last_name from  hr.departments x full outer join hr.employees e on (e.department_ID = x.department_ID)



Select First_name, department_name, city from hr.departments d,  hr.employees e, hr.locations l where d.department_ID = e.department_ID and d.location_ID=l.location_ID


— Lex De Haan

select first_name from hr.employees where employee_ID = (select employee_ID from hr.employees where first_name=’Lex’ and last_name=’De Haan’)


select first_name from hr.employees where employee_ID in (select employee_ID from hr.employees where department_ID = 60)




select first_name from hr.employees where employee_ID in (select employee_ID from hr.employees where department_ID = 60)

UNION

select first_name from hr.employees where employee_ID = (select employee_ID from hr.employees where first_name=’Lex’ and last_name=’De Haan’)


STARTING PYTHON PROGRAMMING

Learn to install different software… follow below links to install software:

Step 1: Video: Click here to download and install Python 

 

Step 2: Install IDE

 

Step 3: Start Basic Programming

DAY 24 :  DAY 2 OF PYTHON TUTORIAL 

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

# passing any value to functions - arguments
name1 = 'Laxman'
print("name1: ",name1)
print("name1: ",name1)
print("name1: ",name1)
print("name1: ",name1)
print("name1: ",name1)

#variable names: can not start with a number: name1 is valid but 1name is not a valid variable name
# _ is the only special character that is allowed in the variable name
# variable name accepts - alphabets(a-z A-Z) 0-9 and _

n1ame = "Hello"
length = 51
breadth = 23
area = length * breadth
perimeter = 2 * (length + breadth)
#A rectangle with length x and breadth y has area of a and perimeter of p
print('A rectangle with length',length,"and breadth",breadth,"has area of",area,"and perimeter of",perimeter)

# format string - f string
print(f"A rectangle with length {length} and breadth {breadth} has area of {area} and perimeter of {perimeter}")


name1 = 'Laxman' # str - string
print(type(name1))
length = 51 # int - integer: -999, -88,0,9,100
print(type(length))
avg = 55.63 #float - 5.1, -6.9, 0.0, 5.0
print(type(avg))
isRight = True # False : bool - boolean True/False
print(type(isRight))
num_val = 6j # j is the imaginary value (complex) - square root of -1
print(type(num_val)) #complex

length = 53
print(length)
length = True
print(length)
length = "Sachin"
print(length)

length = "54"
breadth = "43"
print(length + breadth)

#<class 'str'> str()
#<class 'int'> int()
#<class 'float'> float()
#<class 'bool'> bool()
#<class 'complex'> complex()
val1 = 500
print("Val1 is ",type(val1))
val1 = str(val1) # val1 = "500"
print("Val1 is ",type(val1))

val2 = "55A"
val2 = int(val2)
#arithmetic operations:  +  -  *  /  //  **  %
val1 = 20
val2 = 8
print(val1 + val2)
print(val1 - val2)
print(val1 * val2)
print(val1 / val2)
print(val1 // val2) # // just the integer
print(val1 ** val2) #power(val1, val2)
print(val1 % val2) #

#comparison operators: Output is always boolean - True / False
val1 = 20
val2 = 8
val3 = 20 # 20 should be assigned to val3
# = assignment operator -assigning the value
print(val1 == val2) # is val1 equal to val2 ?
print(val1 != val3) # is val1 not equal to val3 ?
print(val1 > val2) # T
print(val1 >= val3) # is Val1 greater or equal to val3
print(val1 > val3)
print(val1 < val2)
print(val1 <= val2)
print(val1 < val3)

#logical operator" input is boolean and the output is also a boolean
# prediction: Sachin and Sehwag will open the batting
# actual - Sachin and Laxman opened the batting
print(True and True)
print(False and True)
print(True and False)
print(False and False)
val1,val2,val3 = 20, 8, 20
print(val2 == val3 and val1 <=val2 and val3 >=val1 and val2==val3)
# F

# or - even if one value is TRUE entire result will be True
print(True or True)
print(False or True)
print(True or False)
print(False or False)
print(val2 == val3 or val1 <=val2 or val3 >=val1 or val2==val3)
# T
print(not True)
print(not False)
print(not val2 == val3 or val1 <=val2 or val3 >=val1 or val2==val3)

print(val2 == val3 or val1 <=val2 and val3 >=val1 or val2==val3)
#F
# 2+2*3 =

# ax sq + bx + c = 0, find x when a,b and c are given

# D = bsq - 4ac

# solution 1: (-b - sq root D) /2a
# solution 2: (-b + sq root D) /2a

a,b,c = 6, -17, 12
d = b**2 - 4*a*c
sol1 = (-b - d**0.5)/(2*a)
sol2 = (-b + d**0.5)/(2*a)
print(f"Solutions for the given quadratic equation is {sol1} and {sol2}")

check1 = a*sol1**2 + b*sol1 + c
check2 = a*sol2**2 + b*sol2 + c
print(f"Checking if both the check are zero: {check1} and {check2}")
#Conditions
avg = 30

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

#40%
if avg>=40:
print("You have passed!")
else:
print("Sorry, You have failed!")


if avg >=90:
print("You win President's award")
print("90+ is too good score")


print("Thank You")

#Conditions
avg = 90

#40%
if avg>=40:
print("You have passed!")
if avg >= 80:
print("You scored Grade A")
if avg >= 90:
print("You win President's award")
print("90+ is too good score")

elif avg >= 70:
print("You scored Grade B")
elif avg >= 60:
print("You scored Grade C")
elif avg >= 50:
print("You scored Grade D")
else:
print("You scored Grade E")
print("You have passed!")
else:
print("You scored Grade F")
print("Sorry, You have failed!")

print("Thank You")

###
'''
1. Check for positive, negative, zero
2. If positive then check for Odd or Even
3. If positive check for if its divisible by 2 and 3
4. If its divisible by both 2 and 3 then check for 5 also
'''

num = 30 # 0 -10 10 9

if num>0:
print("Number is positive")
if num%2==0:
print("Its an even number")
if num%3==0:
print("Its divisible by 2 and 3 both")
if num%5==0:
print("Yes, this is divisible by 5 also")
else:
print("Its divisible by 2 but not 3")
else:
print("Its an odd number")
if num%3==0:
print("Its divisible by 3 only")
else:
print("Its not divisible by 2 or 3")
elif num<0:
print("Number is negative")
else:
print("Number is neither positive nor negative")

###
# arrange the numbers in increasing order
# 5,6,3 => 3 >=5 >=6
a,b,c = 80,60,40
if a<b: #a < b
if a<c: #a <c
if b<c: #b <c
print(f"{a}<={b}<={c}")
else: # a<b, a<c, c<b
print(f"{a}<={c}<={b}")
else: #a < b c<a
print(f"{c}<={a}<={b}")
else: # b< a
if a<c: #a <c
if b<c: #b <c
print(f"{b}<={a}<={c}")
else: #b<a c <a
if b<c:
print(f"{b}<={c}<={a}")
else:
print(f"{c}<={b}<={a}")
#loops -
# 1 to 10

#range(a,b,c) - a: starting value (including), b: ending value (excluding), c: increment
#range(2,11,3) - 2,5,8
#range(a,b) - c= default = 1
#range(3,8) - 3,4,5,6,7
#range(b) a default = 0, c default = 1
#range(4) - 0,1,2,3

for i in range(4):
print("Hello, value of i = ",i)
for i in range(3,8):
print("Hi, value of i = ",i)
for i in range(2,11,3):
print("Hello, value of i = ",i)

if 'H' in "hello":
print("There")

sum = 0
for i in range(1,11):
print(i,end=", ")
sum = sum+i
print("\nSum of the values = ",sum)

val = 1
sum = 0
while val <=10:
print(val)
sum += val
val+=1 #val=val+1

print("Sum = ",sum)

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

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

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

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

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

## read marks of 5 subjects and find sum and avg
num = int(input("Enter length: "))
print("num = ",num)
print("type of num = ",type(num))

sum=0
for i in range(5):
marks = int(input("Enter the marks in subject "+str(i+1)+": "))
sum+=marks
print(f"The total marks is {sum} and average is {sum/5}")
### WHILE
import random
number = random.randint(1,100)
attempt = 0
ch = input("Do you want to play this game? (y for yes): ")
low = 1
high = 100
while ch=="y":
guess = random.randint(low,high) #int(input("Guess the number (1-100): "))
if guess<1 or guess>100:
print("Invalid guess, try again...")
continue # it will take you to the beginning of the loop
attempt+=1
if guess==number:
print(f"Awesome! You guessed it correctly in {attempt} attempts.")
break #throw you out of the loop
elif guess < number:
print("You have guessed a lower number")
low=guess+1
else:
print("You have guessed a higher number")
high=guess-1

print("Thank you")
'''
take 2 numbers and perform operation based on given choice:
1. To add
2. To multiply
3. Divide
4. Quit
'''

while True:
n1 = int(input("Enter a number: "))
n2 = int(input("Enter another number: "))
print("Give your choice of operation:")
print("1. Addition\n2. Multiplication\n3. Division\n4. Quit")
ch=input("Enter your option: ")
if ch=="1":
print("Addition of numbers: ",n1+n2)
elif ch=="2":
print("Multiplication of numbers: ", n1 * n2)
elif ch=="3":
print("Division of numbers: ", n1 / n2)
elif ch=="4":
break
else:
print("Invalid option! Try Again...")
continue
print("Great work!")

#strings
str1 = 'Hello'
str2 = "Hi"
str3 = '''How are you
Where are you'''
str4 = """I am fine
I am here"""
print(type(str1),type(str2),type(str3),type(str4))
print(str3)
print(len(str3)) #size - total characters in a string
print(str1+" "+(str3 +"\n")*3)

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

str1 = "Hello" #indexing starts from zero
print(str1[0])
print(str1[2])
print(str1[4]) #last element
print(str1[-1]) #last element
print(str1[-3]) #3rd last element
print(str1[1:4]) #start is inclusive /end is exclusive
print(str1[:4])
print(str1[:])
print(str1[-4:-1]) #start is inclusive /end is exclusive
print(str1[:-1])
print(str1[-len(str1):-1])
print(str1[-3:])
print(str1[:])
str1 = "Good Evening Everyone"
print(str1[0])
print(str1[-1])
print(str1[-3:])
# functions that are part of a class are called Methods
str2 = "HELLO HOW ARE YOU"
print(str2.isupper())
print(str1.istitle()) #first character of every word needs to be capital
length = input("Enter the length: ")
if length.isdigit():
length = int(length)
else:
print("Invalid length value, exiting the program")

#username can have only characters and numbers
username = input("Enter username: ")
if username.isalnum():
print("Username accepted")
else:
print("Invalid username.")

str1 = "Hello"
print(str1.isalpha())
str3 = " "
print(str3.isspace())

# enter name: alpha and space
name = input("Enter your name")
isValid = True
for ch in name:
if ch.isalpha() or ch.isspace():
pass
else:
isValid = False
break

if isValid:
print("Valid Name")
else:
print("Invalid Name")

str1 = "HOw arE YOU ONE doING ToDaY"
print(str1.lower())
print(str1.upper())
print(str1.capitalize()) #Only the first character is caps
print(str1.title()) #first letter of every word is caps

split_cont = str1.split()
print("Split: ", split_cont)

split_cont = str1.title().split("o")
print("Split: ", split_cont)

print("o".join(split_cont))
str2 = "How Are You Doing Are You Ok Are You Coming"
print(str2.replace("You","You'll",2))
print(str2)

# Strings are IMMUTABLE
#str2[0] = "h" - not possible
str2 = "h"+str2[1:]
print(str2)

print(str2.count("ou",4,10))

print(str2.find("ou",10,22))

DAY 29 – DECEMBER 22 2022

 

#LIST
l1 = [20,40,20.5,True,"Hello",[2,4,6]]
print(len(l1))
print(l1[1])
print(l1[-1][1])
print(type(l1[-1][1]))
print(type(l1))
l2 = [10,20,30]
print(l1+l2*2)
for i in l2:
print(i)
for i in range(len(l2)):
print(i, "--> ",l2[i])

l2.append(40) #append will add at the end
l2.insert(1,50) #index, value
l2.pop(0) #remove element at the given index
l2.remove(30) #delete the given value
l2[1] = 70
print(l2)

l3 = l2 #both are pointing to same list - Deep copy
l4 = l2.copy() #Shallow copy
print("Set 1")
print("l2: ",l2)
print("l3: ",l3)
print("l4: ",l4)
l2.append(45)
l3.append(70)
l3.append(55)
l4.append(65)
print("Set 2")
print("l2: ",l2)
print("l3: ",l3)
print("l4: ",l4)
print("printing IDs: ")
print("l2: ",id(l2))
print("l3: ",id(l3))
print("l4: ",id(l4))
total_count = l2.count(70)
print(total_count)
print(l2.reverse())
l2.sort()
print(l2)
#l2 = l2 + l3
l2.extend(l2+l3)
print(l2)
print(l2.index(50)) #index of the first matching value
ind = l2.index(50)
print(l2.index(50,ind+1))


marks_masterlist = []
while True:
sum=0
marks_list = [] #student ID, 5 values marks, 7th Sum, 8 avg
id_st = input("Enter the Student ID: ")
marks_list.append(id_st)
for i in range(5):
marks = int(input("Enter the marks in subject "+str(i+1)+": "))
marks_list.append(marks)
sum+=marks

#print("List of marks: ",marks_list)
#print(f"Total marks obtained is {sum} and average is {sum/5}")
avg = sum/5
marks_list.append(sum)
marks_list.append(avg)

marks_masterlist.append(marks_list)
ch=input("Enter N to stop, Enter to continue: ")
if ch:
break

print("Master list:\n",marks_masterlist)
master_list = [['1000', 99, 88, 77, 66, 55, 385, 77.0],
['1002', 33, 44, 55, 66, 77, 275, 55.0],
['1003', 77, 55, 99, 66, 88, 385, 77.0]]
print(len(master_list[0]))

#average of all the students:
for i in range(len(master_list)):
print(master_list[i][0], ":",master_list[i][-1])

#highest marks in each subject
for subcode in range(1,6):
max=-99
for i in range(len(master_list)):
#print(master_list[i][1])
if max <master_list[i][subcode]:
max = master_list[i][subcode]
print(f"Maximum marks in Subject {subcode} is ",max)
#Tuples - linear ordered immutable collection
#List - linear ordered mutable collection

t1 = ()
t1 = (5,)
t1 = (5,6,7)
print(type(t1))
t1 = list(t1)
t1.append(8)
t1 = tuple(t1)

#packing & unpacking
a,b,c,d = t1
print(a)
print(t1[0])
print(16 in t1)

a = (2,99,15)
b = (2,99,15)

#Dictionary - non-linear unordered mutable collection
d1 = {}
print(type(d1))
d1 = {2:"Hello","Two": 999}
print(d1["Two"])
t1 = {True:"Sunday"}
d1.update(t1)
print(d1)

#items: list of tuple of key,value
#keys : list of keys
#values: list of values
print(d1.items())
for i in d1.items():
print(i)

print(d1[2])
for i in d1.items():
if i[0]==2:
print(i[1])

d2 = d1 # points to each other - no new copy created
d3 = d1.copy() # at this point they are copy
t2= {99:"Ninety Nine"}
d1.update(t2)
print(d1)
print(d2)
print(d3)

d1.popitem()
d1.pop(True)
print(d1)

#to get the value when key is given:
a= d1.get(2)
print(a)
#print(d1[888])

d1.clear()
print(d1)

master_data = {}
student = 0
while True:
student+=1
roll = input("Enter the Roll Number for Student "+str(student)+": ")
sum=0
list1 = []
for i in range(3):
m = int(input("Enter marks for subject "+str(i+1)+ " for student "+str(student)+" :"))
sum+=m
list1.append(m)

master_data.update({roll:list1})
ch=input("Hit Enter to continue else to stop: ")
if ch:
break
print("All data: \n",master_data)
#{'1': [5, 5, 5], '2': [8, 8, 8]}

#Set - - linear un-ordered mutable collection

# Lion Tiger Elephant Deer Panther
# P D E T L
# PDE Jaguar Camel
# total how many were named: 7 - Union
# Common between S1 & S2 : 3 - Intersection
#Remove animals from S1 as told by S2, what is left: 2 L & T - Minus (S1-S2)
# S2 - S1 : J & C
# Symmetric Difference: L, T, J , C


# 1. L 2 L 3 L 4L 5L
#SET
set1 = {1,2,3,4,5}
set2 = {3,4,5,6,7,8}
print(type(set1))
#union - giving you all data (minus dup)
print(set1.union(set2)) #max - sum of the # of elements
print(set1 | set2) #min - # of the elements in bigger set

print(set1.intersection(set2)) #max: size of lower set
print(set1 & set2) #min : no elements repeated
#if no elements are repeated we call them disjoint set

seta={1,2,3}
setb={1,2,3}
setc = {1,2,3,4,5}
#setc is superset of seta, seta as subset of setc
#seta = setb = union = intersection: seta is superset as well as subset of setb

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

print(set1.symmetric_difference_update(set2))
print(set1 ^ set2)
print(set1)
#update() -union update
#intersection_update() set1 = set1 & set2
#difference_update()
#symmetric_difference_update()
# Functions
##print()
##type()

def myquestions():
print("How are you",end="? ")
print("Hows going")
print("Where are you")

def myadd(a,b): #arguments #positional #required
print("A: ",a)
print("B: ", b)
sum = a+b
#return sum

#default arguments
def myadd2(a=5,b=0,c=4,d=4,e=5): #arguments #positional #a required b as default
print("A: ",a)
print("B: ", b)
sum = a+b

myquestions()
result = myadd(55,65) #passing the parameter to the function definition
print(result)

myadd2(55,35)
myadd2(55)
myadd2()

#keywords = removes restriction of positional
a=5
b=6
myadd(b=b,a=a) #not being positional - keyword

#required positional default keyword
#global and local scope of variable
def mytest():
global a
print("Inside mytest 2 a = ", a)
a=5 #local variable
#always local takes preference over global
print("Inside mytest 1 a = ",a)

a=10 #global variable
print("printing in main a =",a)
mytest()
#Functions
#DocString - are multi line comments added as first line in function definition
def myfun1(a,b): #required positional argument
'''
This is a sample function to learn about function. This will perform some basic math ops
:param a: this is a number that will take part in math operation
:param b: this is another number that will take part in math operation
:return: a tuple with 3 values - each for addition, multiplication and division
'''
s = a+b
m = a*b
d = a/b
result = [s,m,d] #packing
print(type(result))
return result
def myfun2(a=10,b=20): #default arguments
s = a+b
m = a*b
d = a/b
result = [s,m,d] #packing
print(type(result))
return result

def myfun3(roll,*marks,**attr): # *var -all arguments, **var will read all your keyword arg
print("Roll No:",roll)
print("Marks obtained: ",marks)
print(type(marks))
print("Attributes of student: ",attr)
print(type(attr))

if __name__ =='__main__':

output1 = myfun1(10,5)
print("Output: ",output1)
output1 = myfun2()
print("Output: ",output1)
output1 = myfun2(b=10,a=20)
print("Output: ",output1)

output1 = myfun3(1001, 65,76,87,56,78,76,78,name="Sachin",sports="Cricket",city="Mumbai")

print(help(print)) #doc string
print(print.__doc__)
print(myfun1.__doc__)

#######################
import p1 #import module - file containing functions
out1 = p1.myfun2(b=10,a=20)
print(out1)

out1 = p1.myfun1(10,20)
print(out1)

#annoynomous or oneline or lambda

lf1 = lambda x,y:x+y
print(lf1(10,90))

# recursion - function calling itself

def myfun_facto(n):
if n==0:
return 1
return n * myfun_facto(n-1) #stack


print(myfun_facto(5))

# 5! = 5 * 4 * 3 * 2 * 1
# 5! = 5 * 4!
#Class & Object
class Person:
population=0
def __init__(self,name):
#this function should be called automatically when you create an object
Person.population += 1
self.name = name

def display_info(self):
print(f"Hello How are you? My name is {self.name}")

@classmethod
def display_pop(cls):
print("Population is ",cls.population)


o1=Person("Sachin") #auto calling of __init__
o2=Person("Kapil") #auto calling of __init__
o3=Person("Sunil") #auto calling of __init__
o4=Person("Dhoni") #auto calling of __init__
o5=Person("Virat") #auto calling of __init__
o1.display_info()
o2.display_info()
o3.display_info()
#o4.display_info()
#o5.display_info()
print(type(o1))
print(o1.population)
print(o3.population)
print(o1.name)
print(o3.name)

l1 = [3,4,5]
l1.append(5)
#Inheritance
#Encapsulation
#Polymorphism
#Abstraction
################
class School:
def __init__(self,schoolname):
self.schoolname = schoolname
def display_school(self):
print("School name is: ",self.schoolname)
self.__display_state()
def display_loc(self):
print("We are located in the City")
def __display_state(self):
print("We are located in the State")
class Student(School):
def __init__(self,sname, stname):
School.__init__(self,sname)
self.sname = sname
self.stname = stname
def display_student(self):
print("Student name is: ",self.stname)
def display_loc(self):
print("Calling from STUDENT Class: We are located in the City")
class MySelf:
def MySelfMethod(self):
School.display_loc(self)

s1 = School("ABC International School")
s1.display_school()
st1 = Student("XYZ Intermational School","Sachin")
st1.display_school()
st1.display_student()
st1.display_loc()
#st1.__display_state()
m1 = MySelf()
m1.MySelfMethod()

#Encapsulation:
# public - the members are available to be accessed by anyone
# protected (_membername) members can be called only
# its own and derived class: Practically not implemented in Python
# private options (__membername) - cant be accessed outside the class

from abc import ABCMeta, abstractmethod
class Shape(object):
__metaclass__ = ABCMeta
def __init__(self):
print("Shape is created")

@abstractmethod
def area(self):
print("I will do nothing")
def information(self):
print("I belong to class Shape")

class Rectangle(Shape):
def __init__(self):
print("rectangle is created")
class Circle(Shape):
def __init__(self):
print("circle is created")

s1 = Shape()
c1 = Circle()
c1.area()
s1.area()
c1.information()

PYTHON PROJECT WORK

import sqlite3
con_str = sqlite3.connect("ies1.db")
creat_tab ='''Create Table Students(
Roll Integer primary key,
name text,
fees real,
admission_date date)'''
#con_str.execute(creat_tab)
insrt1 = '''Insert into Students(ROll,Name) values(1001,'Sachin')'''
#con_str.execute(insrt1)
insrt1 = '''Insert into Students(ROll,Name) values(1002,'Kapil')'''
#con_str.execute(insrt1)
insrt1 = '''Insert into Students(ROll,Name) values(1003,'Sunil')'''
#con_str.execute(insrt1)
insrt1 = '''Insert into Students(ROll,Name) values(1004,'Kohli')'''
#con_str.execute(insrt1)
insrt1 = '''Insert into Students(ROll,Name) values(1005,'Dhoni')'''
#con_str.execute(insrt1)

select_q = "Select * from Students"
cursor_obj = con_str.execute(select_q)
rows = cursor_obj.fetchall()
for row in rows:
print(row)

#update
update_q = '''Update Students set fees=110 where roll=1003'''
con_str.execute(update_q)
con_str.commit()

#Delete
delete_q = '''Delete from Students where roll=1004'''
con_str.execute(delete_q)

##insert based on user input
roll_no = int(input("Enter the roll number: "))
name_st = input("Enter the name: ")
insrt1 = '''Insert into Students(ROll,Name) values(?,?)'''
dy_val = (roll_no,name_st)
con_str.execute(insrt1,dy_val)
con_str.commit()


##########################
### WORKING WITH FILES ##
##########################
file_con = open("abc1.txt",mode="a") #default is read
# r read - only read, w write - you can write, a append - you can only append
# r+ , w+ , a+
content = '''Twinkle Twinkle Little Star
How I wonder what you are'''
if file_con.writable():
file_con.write(content)
fh=open("file1.txt","a")
story='''Once upon a time, there lived a deer in the forest. He was a gentle creature who loved to explore the forest and make new friends. He often encountered various animals on his explorations, including a lion.

The deer and the lion were wary of each other when they first met, but soon they developed a mutual respect and even a friendship. The lion was impressed with the deer's courage and wisdom, while the deer admired the lion's strength and nobility.

The two began to meet often, and they would often go on adventures together. The lion would show the deer the best spots to find food and the deer would help the lion hunt. They both enjoyed the company of each other, and the friendship between them grew stronger.

One day, the deer and the lion were out exploring the forest when they came upon a group of hunters. The deer was terrified and wanted to run away, but the lion saw the hunters and told the deer to stay put. The lion then charged at the hunters, roaring and showing his full strength. The hunters were so scared that they ran away, leaving the deer and the lion unharmed.

The deer was so grateful for the lion's bravery that he promised to always be there for his friend. From that day on, the deer and the lion remained inseparable. They went on countless adventures together, and they were always there to help each other when they needed it.'''
fh.write(story)
fh.close()

fh=open("file1.txt","r")

#content = fh.read(200)
#print(content)
fh.seek(100)
content = fh.read(300)
#print(content)
fh.seek(0)
print(fh.readline(50000))
print(fh.readlines())
fh.close()
############### JSON
#JavaScript Object Notation - json
json_str = '''
{"Name":"Sachin",
"Sport":"Cricket",
"Fav Shots":["Cover Drive","Square Cut"],
"Teams":[
{
"TName":"Mumbai",
"Games": "Ranji"
},
{
"TName":"Mumbai Indians",
"Games": "IPL"
}
]}
'''
print(json_str)
print(type(json_str))

import json

# 4 methods: load(), loads(), dump(), dumps()
json_obj = json.loads(json_str)
print(type(json_obj))
print(json_obj["Teams"])
json_dumps = json.dumps(json_obj,indent=4,sort_keys=True)
print(json_dumps)
fp=open("json_file.json","w")
json.dump(json_obj,fp,indent=4)
fp.close()
import json
##
fp=open("json_file.json","r")
file_content = json.load(fp)
print(file_content)
print(type(file_content))
fp.close()

##### Exceptions

print("Hello")
print(5-3)
#runtime errors - Exceptions
try:
num1 = int(input("Enter a number: ")) # ValueError exception
50 / 0 # ZeroDivisionError exception

except ValueError:
print("You have not entered a valid number hence setting it to zero")
except ZeroDivisionError:
print("Sorry cant divide by zero")
except Exception:
print("Some error has occured")
else: #if there is no error then do else
print("Number you have entered is ",num1)
finally: #will execute in both cases - error or no error
print("Demo program for exception handling")


#50/0 #ZeroDivisionError exception

# try - except - else -finally
import numpy as np
x = range(16) #0...15
x=np.reshape(x,(4,4))
print(x[1:3,:3])

y = range(11,27)
y=np.reshape(x,(4,4))
print(y)

print(x+y)
print(x-y)
print(x*y) #element multiplication
print(x@y) #matrix multiplication

print(x/y)

### Pandas
import pandas as pd
data = [["Apple",1200,2100,900,870],
["Oranges",500,900,300,400],
["Banana",132,456,768,333],
["Mangoes", 1111,3333,2222,4444]]
print(data)

headers=['Fruit',"Q1 2022","Q2 2022","Q3 2022","Q4 2022"]
inx = ["Fruit 1","Fruit 2","Fruit 3","Fruit 4"]
data_df = pd.DataFrame(data,columns=headers,index=inx)
print(data_df)
import pandas as pd
#you can read csv files using read_csv irrepective of the location
usage_df = pd.read_csv("C:/Users/Hp/Downloads/Dataset-master/Dataset-master/user_usage.csv")
print(usage_df)
device_df = pd.read_csv("C:/Users/Hp/Downloads/Dataset-master/Dataset-master/user_device.csv")
print(device_df)

#merge these two datasets
result_df = pd.merge(usage_df,device_df, on="use_id",how="right")
print(result_df)
#########################################
######### EXAMPLE: DATA CLEANING ######
#########################################
#missing data?
#data correct? type, range
#
import pandas as pd
hotel_df = pd.read_csv("C:/Users/Hp/Downloads/Dataset-master/Dataset-master/hotel_bookings.csv")
print(hotel_df)

import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('ggplot')
cols = hotel_df.columns[:30]
colors = ["#085838","#f4deb4"]
sns.heatmap(hotel_df[cols].isnull(), cmap=sns.color_palette(colors))
plt.show()
import pandas as pd

hotel_df = pd.read_csv("C:/Users/Hp/Downloads/Dataset-master/Dataset-master/hotel_bookings.csv")
print(hotel_df)

#Data cleaning
## 1. missing values - 1)remove the values 2)replace the missing values
## 2. Incorrect data - 1) extreme values, not possible, different data type - make it null
import matplotlib.pyplot as plt
import seaborn as sns

cols = hotel_df.columns[:30]
colors = ["#2b80ff","#05f6d5"]
sns.heatmap(hotel_df[cols].isnull(),cmap=sns.color_palette(colors))
#plt.show()
#dropping column company since it has more than 95% values missing
hotel_df = hotel_df.drop(['company'],axis=1) #axis=1 for column

#check % missing
import numpy as np
for col in hotel_df.columns:
pct_missing = np.mean(hotel_df[col].isnull())
print(f"{col} has {pct_missing*100}%")

#calculate total missing values for each row
for col in hotel_df.columns:
missing = hotel_df[col].isnull()
num_missing = np.sum(missing)
if num_missing>0:
hotel_df[f'{col}_ismissing'] =missing

ismissing_col = []
for col in hotel_df.columns:
if 'ismissing' in col:
ismissing_col.append(col)
#total the values of missing cols for each row:
hotel_df['num_missing'] = hotel_df[ismissing_col].sum(axis=1)

print("Missing data: ",ismissing_col)
ind_missing = hotel_df[hotel_df['num_missing']>12].index
#drop the rows which has more than 12 missing values
hotel_df=hotel_df.drop(ind_missing,axis=0) #axis=0 for rows

#check again after rows and col drop
import numpy as np
for col in hotel_df.columns:
pct_missing = np.mean(hotel_df[col].isnull())
if pct_missing>0.0:
print(f"{col} has {pct_missing*100}%")
'''
children has 2.0498257606219004%
babies has 11.311318858061922%
meal has 11.467129071170085%
country has 0.40879238707947996%
deposit_type has 8.232810615199035%
agent has 13.68700576330250
'''

hotel_df['meal'] = pd.Categorical(hotel_df['meal'])
hotel_df['country'] = pd.Categorical(hotel_df['country'])
hotel_df['deposit_type'] = pd.Categorical(hotel_df['deposit_type'])

med = hotel_df['children'].median()
hotel_df['children'] = hotel_df['children'].fillna(med)
med = hotel_df['babies'].median()
hotel_df['babies'] = hotel_df['babies'].fillna(med)
med = hotel_df['agent'].median()
hotel_df['agent'] = hotel_df['agent'].fillna(med)

non_num_cols = hotel_df.select_dtypes(exclude=np.number)
for col in non_num_cols:
missing = hotel_df[col].isnull()
num_missing = np.sum(missing)
if num_missing > 0:
#replace the missing values with mode
top = hotel_df[col].describe()['top']
hotel_df[col] = hotel_df[col].fillna(top)

print("After update the missing columns are:")
#check again for missing values
for col in hotel_df.columns:
missing = hotel_df[col].isnull()
num_missing = np.sum(missing)
if num_missing > 0:
print(f"{col} has total missing values {pct_missing}")


#####
hotel_df['children'] = hotel_df['children'].fillna(-999)
hotel_df['country'] = hotel_df['country'].fillna("NOT AVAILABLE")

This is a practice excercise which requires you to clean and merge dataset belong to different categories but having same kind of information.

1. Clean the data

2. Add category

3. Merge the data

4. Now prepare viz

Quest Learning DS December 2022

Day 1:

a=5
#data type is integer
print(a)
print(type(a))
a='''hello
how are you
I am fine'''
#type is string
print(a)
print(type(a))
a="""hello"""
#type is string
print(a)
print(type(a))

a=5.0
print(a)
print(type(a))

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

a=5j
print(a);print(type(a));print(a*a)

print("How are you?",end=" -> ")
print("I am doing good.")

quant = 40
price = 10
total_cost = quant * price
print("Product quantity is",quant,"and bought at",price,"will cost total of Rs",total_cost)
print(f"Product quantity is {quant} and bought at {price} will cost total of Rs {total_cost}")

length = 50
breadth = 20
area = length * breadth #calc
#output: A rectangle with length 50 and breadth 20 will have area of area_val and perimter of perimeter_vl

#Operators:
##Arithematic operators + - * / ** (power) // (integer division) % (reminder)
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** b)
print(a // b)
print(a % b)

##Comparison operator: == != > >= < <=
#input as numbers and output will be boolean value
a=10
b=3
print(a==b) #F
print(a!=b) #T
print(a > b)
print(a>=b)
print(a<=b)
print(a<b)

## Logical: and or not
a = 10
b = 3
print(a >b and b !=a) # T and T = T
print( True and True)
print( False and True)
print( False and False)
print( True and False)
print(not a!=b)
print( True or True)
print( False or True)
print( False or False)
print( True or False)

#bitwise: >> << & | ~
a=23
print(bin(a)) #bin - converts to binary( 0b) oct - octal 0c hex - hexadecimal 0x
print(hex(a))

print("23 >> 1: ",23 >> 1) #bitwise: right shift
print("23 >> 2: ",23 >> 2) #bitwise: right shift
print(23 << 2) #bitwise: left shift
print(int(0b1011))
# 10111. 1011

print(" & : ",23 & 12)
# 1 0 1 1 1
# 0 1 1 0 0
#&
#--------------
# 0 0 1 0 0
# 1 1 1 1 1

print(" | : ",23| 12)

a=-5

if a < 0:
print()
print()
print()
b = 6+4
print(b)
print("Thank you 1")

a = -5
if a<0:
print("This is a negative number")
else:
print("This is not a negative number")

a=0
if a<0:
print("Negative number")
elif a>0:
print("Positive number")
else:
print("Zero value")

Video Link Day 1

number = 6

if number<0:
print("Its negative")
elif number>0:
print("its positive")
if number%2==0:
print("Even")
if number%3==0:
print("Divisible by 3 and 2 both")
else:
print("Its divisible by 2 only")
else:
print("Odd")
if number%3==0:
print("Divisible by 3 only")
else:
print("Its not divisible by either 2 or 3")
else:
print("Its zero")

########## LOOP
# FOR Loop
#range(a,b,c): a = starting value (inclusive), b=ending value(exclusive), c=increment
#range(2,8,2): 2,4,6
#range(a,b): c is default 1
#range(3,7): 3,4,5,6
#range(3): a=0, c=1 => 0,1,2
for i in range(3):
print(i)

# While Loop
ch="n"
while ch=='y':
print("I am in While")
ch=input("Input your choice: ")

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):
print("*",end=" ")
print()

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

print("\n\n")
for j in range(5):
for k in range(4-j):
print(" ",end="")
for i in range(j+1):
print("*",end=" ")
print()
choice = "y"
while choice=='y' or choice=='Y':
print("Hello")
choice = input("Enter Y to continue: ")

while True:
print("Hello")
choice = input("Enter Y to continue: ")
print("Hello 2")
if choice == 'B' or choice == 'b':
continue #Take you to the beginning of loop
print("Hello 3")
if choice!='y' and choice!='Y':
break #break which will throw you out of current loop
print("Hello 4")

print("Hello 5")
val1 =input("Enter your name: ")  #reading input given by the user
print(val1)
print(type(val1))

marks1 = input("Enter your marks in subject 1: ")
marks1 = int(marks1)
marks2 = int(input("Enter your marks in subject 2: "))
marks3 = int(input("Enter your marks in subject 3: "))
sum = marks1 +marks2+marks3
print("Total marks obtained is ",sum)
avg = sum/3
print(f"{val1} has scored a total of {sum} marks with an average of {avg:.2f}")

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

###############
choice = input("Do you want milk (Y/N): ")
if choice =='Y' or choice =='y':
print("Give milk")
print("So you want milk tea")

print("Done")
val1 = "Sachin Tendulkar"
marks1 = input("Enter your marks in subject 1: ")
marks1 = int(marks1)
marks2 = int(input("Enter your marks in subject 2: "))
marks3 = int(input("Enter your marks in subject 3: "))
sum = marks1 +marks2+marks3
print("Total marks obtained is ",sum)
avg = sum/3
print(f"{val1} has scored a total of {sum} marks with an average of {avg:.2f}")

if avg >=90:
print("Congratulations, you won President Medal")

#if avg >=40, Pass and its not then say Fail
if avg >=40:
print("Result: PASS")
else: #default condition , executed only when if is false
print("Result: FAIL")


'''
80 to 100: Grade A - IF
70 to 80: Grade B - ELIF
60 to 70: Grade C - ELIF
50 to 60: Grade D - ELIF
40 to 50: Grade E - ELIF
<40: Grade F - ELSE
'''
#avg = 90
if avg>=80:
print("Grade: A")
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")

number = 11
if number %2==0:
print("Its an even number")
else:
print("Its an odd number")
number = int(input("Enter a number: "))
if number <0:
print("Its a negative number")
elif number >0:
print("Its a positive number")
if number %2==0:
print("Its an even number")
if number %3 ==0:
print("Its divisible by both 2 and 3")
else:
print("Its an odd number")
else:
print("Its Zero")


number = 5
if number %5==0 and number %3==0:
print("Number is divisible by both 5 and 3")
else:
print("Its neither divisible 5 nor 3")

if number %5==0:
if number%3 ==0:
print("Divisible by both 5 and 3")
else:
print("Divisible only by 5")
else:
if number%3 ==0:
print("Divisible by only 3")
else:
print("Its neither divisible 5 nor 3")


if number ==0:
print("Zero")
else:
print("Its either positive or negative")

# Loops : FOR - you know how many times (boil water for 2 min)
#range(a,b,c): a is the starting value, b is the ending value minus 1 (UPTO), c increment
#range(2,8,2): 2,4,6
#range(2,5): 2 values these are a and b, c is default =1 || 2,3,4
#range(3) : 1 value indicate b, default a=0,c=1 || 0,1,2

#WAP to generate first 10 natural numbers
for i in range(10):
if i==9:
print(i)
else:
print(i, end=', ')


#Loops: WHILE - you know until when (boil water till you see bubble)

counter = -11
while counter <=10:
print(counter)
counter+= 1 # a = a X 5 => a X= 5



# Sum of first 10 natural numbers
sum=0
for i in range(1,11):
sum+=i # sum = sum + i
print("Sum from For loop: ",sum)

# Sum of first 10 natural numbers
sum=0
counter = 1
while counter <=10:
sum+=counter
counter+=1
print("Sum from While loop: ",sum)
 
str1 = 'hello'
str2 = "hi"
str3 = '''Hello there'''
str4 = """Good evening"""
print(str4[-1])
print(str4[:4])
print(str4[1:4])
print(str4[-3:])
print(str1.count('l'))
print(str4.upper())
print(str1.upper().isupper())
num1 = input("Enter a number: ")

print(num1)
#List
list1 = [2,4,6,8.9,"Hello",True,[2,3,4]]
print(type(list1))
print(list1)
print(type(list1[-1]))
var = list1[-1]
print(list1[-1][0])
print(list1[-3:])
print(len(list1[-1]))

for i in list1:
print(i, end=" , ")
print()
l1 = [2,4,6,8]
l2 = [1,3,5,7]
print((l1+l2)*3)

l1.append(19)
print(l1)
l1.insert(2,"Hello")

l1.pop(0) #index / positive to remove
l1.remove(19) #value to remove
print(l1)
l1[1] = 18
print(l1)

l11 = l1
l21 = l1.copy()
print("1")
print("L1: ",l1)
print("L11: ",l11)
print("L21: ",l21)
l11.append(66)
l1.append(55)
l21.append(66)
print("2")
print("L1: ",l1)
print("L11: ",l11)
print("L21: ",l21)

l1.extend(l11) # l1 = l1+l2
print(l1)
#l1.sort()
l1.reverse()
print(l1)
print(l1.count(66))
print(l1.index(8))
t1 = tuple(l1)
t1 = list(t1)
t1 = (2,4,5)
n1,n2,n3 = t1

t1 = (3,)
print(type(t1))
t1 = (3)
print(type(t1))

dict1 = {55:"Sachin", "Name": "Cricket"}
word = "hello"
guess = "ll"
ind = 0
word1 = word.replace("l","L",1)
print(word1)
for i in range(word.count(guess)):
ind = word.find(guess,ind)
print(ind)
ind=ind+1

word3 = "How are you doing"
l1 = word3.split("o")
print(l1)
word4 = "o".join(l1)
print(word4)

#Strings
word = "hEllo".lower()
print(word)
display_text = "* "*len(word)
print(display_text)
while True:
guess = input("Guess the character: ")
guess = guess[0].lower()

if guess.isalpha():
if guess in word:
ind = 0
for i in range(word.count(guess)):
ind = word.find(guess, ind)
#now time to reveal
#0 - 0, 1-2, 2-4
display_text = display_text[:ind*2] + guess+display_text[ind*2+1:]
ind = ind + 1
print(display_text)

if "*" not in display_text:
print("Congratulations!")
break
else:
print("Given character is not in the original word")
else:
print("Invalid character")

#List
l1 = [2,4,6.5,"Hello",True,[2,4,6]]
l1.append(11)
l1.insert(1,"Good evening")
l1.pop(0) #removes element from the given position
l1.remove(6.5) #value

l2 = l1
l3 = l1.copy
print("Set 1: ")
print("l1 : ",l1)
print("l2 : ",l2)
print("l3 : ",l3)

print("Set 2: ")
print("l1 : ",l1)
print("l2 : ",l2)
print("l3 : ",l3)
print("######")
'''
22
12
2022

22nd December 2022
'''
month_txt = ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
dt_ending = ["st","nd","rd"]+["th"]*17 +["st","nd","rd"]+["th"]*7 +["st"]
date_user = int(input("Enter Date: "))
month_user = int(input("Enter month:"))
year_user = input("Enter the year: ")
display_txt = str(date_user) +dt_ending[date_user-1]+" " + month_txt[month_user-1]+" " +year_user

print(display_txt)

l1 = [5,10,15,20,25,30]
print(len(l1))


sample = [[1,2,3,4,5],
[2,4,6,8,10],
[3,6,9,12,15]]
#dictionary: unordered collection mutable
main_dict = {}
d1 = {"name":"sachin"}
d2 = {"city":"mumbai"}
main_dict.update(d1)
main_dict.update(d2)
key="sports"
val="cricket"
temp={key:val}
main_dict.update(temp)

main_dict2 = main_dict
main_dict3 = main_dict.copy()
print("Set 1")
print("Dict 1: ",main_dict)
print("Dict 2: ",main_dict2)
print("Dict 3: ",main_dict3)
key="marks"
val=[55,44,66,77,88]
temp={key:val}
main_dict.update(temp)
print(main_dict)

print("Set 1")
print("Dict 1: ",main_dict)
print("Dict 2: ",main_dict2)
print("Dict 3: ",main_dict3)

print("Set Mem Loc")
print("Dict 1: ",id(main_dict))
print("Dict 2: ",id(main_dict2))
print("Dict 3: ",id(main_dict3))

main_dict.pop('city')
print("Dict 1: ",main_dict)
main_dict.popitem()
print("Dict 1: ",main_dict)
#keys
for i in main_dict.keys():
print(i)
#values
for i in main_dict.values():
print(i)
#items
for i,j in main_dict.items():
print(i," : ",j)
# List functions

### MAP
list1 = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29]
#find cube of all these values

result = list(map(lambda x:x**3,list1))
print("Result = ",result)

### FILTER
result = filter(lambda x:x>=15,list1)
print("Filtered values: ",list(result))

### REDUCE
from functools import reduce
result = reduce(lambda x,y:x+y,list1)
print("Sum is ",result)

result = reduce(lambda x,y:x+y,[1,2,3,4,5,6,7])
print("Sum is ",result)

# 1,2,3,4,5,6,7 =
## 1. x=1, y=2 , x+y = 3
## 2. x=3, y=3, x+y=6
## 3. x=6, y=4, x+y = 10
## 4. x=10, y=5 = 15
## 5. x=15, y=6 = 21
## 6. x=21,y=7 = 28

#how to connect to the database from Python
#SQLITE3 - installed on local machine, nobody can connect from outside
import sqlite3

con_str = sqlite3.connect("classnotes.db")
cursor = con_str.cursor()
q1 = '''Create table Notes(
ID int primary key,
description text,
subject varchar(30))'''
#cursor.execute(q1)

q2 = '''Insert into Notes(ID, Description, Subject)
values(2,"This is a sample Maths notes to perform sone action",'MATHS')'''
#cursor.execute(q2)

q4 = '''UPDATE Notes set subject='Science' where ID=2 '''
cursor.execute(q4)
q4 = '''DELETE From Notes where ID=1 '''
cursor.execute(q4)

con_str.commit()
q3 = '''Select * from Notes'''
recordset = cursor.execute(q3)
#print(list(recordset))
for i in recordset:
for j in i:
print(j,end=" ")
print()

con_str.close()

##########
a=10
b=10
c =a/b
print("A/B = ",c) #ZeroDivisionError: division by zero
num1 = 0
num2 = 0
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))

except ValueError:
#print("We cant proceed further because input is not valid")
print("Invalid input, setting both the numbers to zero")

finally:
sum = num1 + num2
print("Sum is ", sum)
print("Thank you for using this program. See you soon")


#ValueError: invalid literal for int() with base 10: '8t'
Data Analytics – November 2022

Assignment

Develop

1. Library Management System – think of different tables it can have and also add columns to those tables

2. Add constraints to columns as applicable

3. Add data types to each column

4. Add atleast 5 sample data to each table

 

SQL Server 

 

DATATYPES:

.Approximate numeric data types (Float)

This data type is used to store floating-point and real values. It is mainly used in scientific calculations.

Date and Time data types

We use these data types to hold the temporal values such as date and time, including time offset in a column.

Character string data type

This data type allows us to define the character data type only, which can be fixed or variable in length.

Unicode character string data types

This data type allows us to define the full range of Unicode character sets encoded in the UTF-16 character set.

Binary data types

This data type allows storing image, audio, and video files of fixed and variable length into a database location. It stores information in 0 and 1 format.

 

Creating a table

— Creating a table

Create Table Library.dbo.Members(

MemberID INT IDENTITY PRIMARY KEY,

Full_name Varchar(40) NOT NULL,

Phone char(10),

emailid Varchar(20)

)

 

— Create table databasename.schemaname.tablename()

— Within the bracket we need to give the column names and the data types

— Add constraints if any: Primary Key

— We can use Identity to generate unique integer values: SQL SERVER

 
Deleting a table and creating it again

USE [Library]

GO

 

/****** Object:  Table [dbo].[BOOKS]    Script Date: 24-11-2022 07:04:04 ******/

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BOOKS]’) AND type in (N’U’))

DROP TABLE [dbo].[BOOKS]

GO

/****** Object:  Table [dbo].[BOOKS]    Script Date: 24-11-2022 07:03:22 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

CREATE TABLE [dbo].[BOOKS](

[BOOKID] [int] IDENTITY PRIMARY KEY,

[BTITLE] [nchar](10) NULL,

[AUTHOR] [nchar](10) NULL,

[COST] [real] NULL

GO

Codd’s Rules (defines RDBMS systems)

  • Rule 1 Information rule: information needs to be stored in a table format and each cell has to have one unique data => Table format
  • Rule 2 Guaranteed access: Each single data has to be accessible => each table has a primary key
  • Rule 3 Handling NULL values uniformly for all tables: data missing/not known/not applicable
  • Rule 4 Active online catalog: Data Dictionary (managed by system) should have all the information about metadata. => sys.objects in MSSS
  • Rule 5 comprehensive sub-language rule: database language to access data in a linear syntax format => SQL
  • Rule 6 Updating Rule (about Table): data needs to be updatable  => Update/Delete/Alter
  • Rule 7 Insert, Update, Delete available (Database)  => UNION,INTERSECTION etc
  • Rule 8 Physical data independence: can only be changed from within the database. No external factor can change the stored data. 
  • Rule 9 Logical data independence: Application should not be impacted by any change in the database
  • Rule 10 Integrity independence: database design can not be influenced by anyother team
  • Rule 11 Distribution independence: User need/should not know where the data is stored.
  • Rule 12 Non subversion: access to the lowest level => if you have access to a table, you should be able to access all the records/tuples in that table

Design

  • Table
  • Tuple
  • Record
  • Relation instance: group of columns that gives the relationship
  • Employee table: EMP_NAME & EMP_PHONE
  • Schema: Group of tables and other database objects
  • Relation key (KEY): set of columns that will uniquely identify each row
  • EMP_ID, NAME & DOB, Phonenumber & NAME
  • Referential Integrity constraint (FOREIGN KEY): link 2 tables, in current table its called FOREIGN KEY and in Other table, it has to be a Primary Key
 

E R Diagram

Example: (Member entity)

 

Handling Many to Many relationship:

 

Click here to Watch the Video

Home, Assignments and Projects

Homework 1:

Image Search for 3 ER diagrams from internet (preferably related to your domain of interest)

 

Re-draw it and just add 3-4 lines about that ER

 

Assignment 1:

E R diagram: Library Management System and We will later convert these into database

 

Project 1: Develop the conceptual model with an EntityRelationship Diagram (ERD)

1. What are the entities in our database (nouns – these will be the tables) – Draw these as rectangles

2. What are their attributes? (properties/characteristics of an entity that we want to collect and store in the DB) – think about what would uniquely identify a particular instance of the entity)

– Draw these as bubbles off the square

– Underline the attribute(s) that uniquely identifies instance

 

3. What are the relationships between entities? (what is the cardinality of that relationship? (1-1? 1-many? Etc.)

– Draw lines between entities – put a label on the line in a diamond

– Indicate by crow’s feet (or #’s) the cardinality at each end of the relationship

 

E R Diagram Refresher :

Rectangle — Entity

Ellipses — Attribute (underlined attributes are [part of] the primary key)

Double ellipses — multi-valued attribute

Dashed ellipses– derived attribute, e.g. age is derivable from birthdate and current date

Keys:

– Superkey:  an  attribute  or  set  of  attributes  that  uniquely  identifies  an entity–there  can  be  many  of  these

– Composite  key:  a  key  requiring  more  than  one  attribute

– Candidate  key:  a  superkey  such  that  no  proper  subset  of  its  attributes is  also  a  superkey  (minimal  superkey  – has  no  unnecessary attributes)

– Primary  key:  the  candidate  key  chosen  to  be  used  for  identifying entities  and  accessing  records.    Unless  otherwise  noted  “key”  means “primary  key”

– Alternate  key:  a  candidate  key  not  used  for  primary  key

– Secondary  key:  attribute  or  set  of  attributes  commonly  used  for accessing  records,  but  not  necessarily  unique

– Foreign  key:  term  used  in  relational  databases  (but  not  in  the  E-R model)  for  an  attribute  that  is  the  primary  key  of  another  table  and  is used  to  establish  a  relationship  with  that  table  where  it  appears  as  an attribute  also. So  a  foreign  key  value  occurs  in  the  table  and  again  in the  other  table.  This  conflicts  with  the  idea  that  a  value  is stored  only once;  the  idea  that  a  fact  is  stored  once  is  not  undermined.

Using Management Studio:

USE [Library]

GO

 

/****** Object:  Table [dbo].[Transactions]    Script Date: 29-11-2022 06:36:52 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

CREATE TABLE [dbo].[Transactions](

[TID] [smallint] IDENTITY(1,1) NOT NULL,

[MemberID] [int] NOT NULL,

[BookID] [int] NOT NULL,

[IssueDate] [date] NULL,

[ReturnDate] [date] NULL,

 CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED 

(

[TID] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

GO

 

ALTER TABLE [dbo].[Transactions]  WITH CHECK ADD  CONSTRAINT [FK_Transactions_Transactions] FOREIGN KEY([MemberID])

REFERENCES [dbo].[Members] ([MemberID])

GO

 

ALTER TABLE [dbo].[Transactions] CHECK CONSTRAINT [FK_Transactions_Transactions]

GO

 

ALTER TABLE [dbo].[Transactions]  WITH CHECK ADD  CONSTRAINT [FK_Transactions_Transactions1] FOREIGN KEY([BookID])

REFERENCES [dbo].[BOOKS] ([BOOKID])

GO

 

ALTER TABLE [dbo].[Transactions] CHECK CONSTRAINT [FK_Transactions_Transactions1]

GO

 

USING QUERY EDITOR:

 

Create Table BOOKDETAILS (

BDID SMALLINT PRIMARY KEY,

BOOKID INT FOREIGN KEY REFERENCES BOOKS(BOOKID),

CITY varchar(15),

Publisher varchar(15) 

)

Go

— Insert data into the tables

Insert into dbo.Members(Full_name,Phone,emailid) values(‘Sachin’,’23456′,’sachin@sachin.com’)

GO

Insert into dbo.Members(Full_name,Phone,emailid) values(‘Kapil’,’45456′,’kapil@sachin.com’)

GO

 

— Reading is done by Select query

Select MemberID, Full_name from dbo.Members

 

— Practice https://livesql.oracle.com/

 


 

— ALTER is used to change the structure of your table – add, drop, Alter (modify in some versions) table members

 

ALTER TABLE dbo.BOOKS

ADD ISBN char(13)

GO

ALTER TABLE dbo.BOOKS

ADD ISBN_10 char(10)

Go

 

— Drop column ISBN_10

ALTER TABLE dbo.BOOKS

DROP COLUMN ISBN_10

Go

 

— Change the datatype of a column

ALTER TABLE dbo.BOOKS ALTER COLUMN ISBN int

 

— ####################################

— Properties of a Foreign Key

— On DELETE OR UPDATE:

— 1. NO ACTION

— 2. CASCADE

— 3. SET TO NULL

— 4. DEFAULT

 

— DELETE – when value in main table is deleted, it performs above selected option in the secondary table

— UPDATE – when value in main table is updated, it performs above selected option in the secondary table

 

— BOOKS : 1 , 2, 3

 

— Delete : SET TO NULL

— UPDATE : CASCADE

 

ALTER TABLE dbo.BOOKS ALTER COLUMN BTITLE nchar(30)

GO

ALTER TABLE dbo.BOOKS ALTER COLUMN AUTHOR nchar(30)

GO

 

Insert into dbo.Books(BTITLE,AUTHOR) values (‘SQL Programming’,’Sachin’)

 

select * from dbo.BOOKS

go

select * from dbo.members

go

 

select * from dbo.Transactions

go

 

Insert into dbo.Transactions (MemberID,BookID,IssueDate) Values (1,2,GETDATE())

 

Insert into dbo.Transactions (MemberID,BookID,IssueDate) Values (2,2,GETDATE())

 

–Update the existing value in table

Update dbo.Transactions Set BookID = 3 where TID=2

 

 

Update dbo.Members Set MemberID = 100 where MemberID=1

 

Delete from dbo.Members where MemberID=1

DAY 16: using SELECT in SQL  (livesql.oracle.com)

 

select * from hr.employees;

 

Select EMPLOYEE_ID, LAST_NAME, FIRST_NAME, EMAIL, HIRE_DATE from hr.Employees;

 

 

Select EMPLOYEE_ID, LAST_NAME “LASTNAME”, FIRST_NAME, EMAIL, SALARY, HIRE_DATE from hr.Employees;

 

Select EMPLOYEE_ID, LAST_NAME AS LASTNAME, FIRST_NAME, EMAIL, SALARY, HIRE_DATE from hr.Employees;

 

 

Select EMPLOYEE_ID, LAST_NAME “LASTNAME”, FIRST_NAME, EMAIL, SALARY, SALARY*12 “ANNUAL SALARY”, HIRE_DATE from hr.Employees;

 

Select Distinct last_name , first_name from hr.Employees

 

Select Distinct last_name , first_name, COMMISSION_PCT from hr.Employees ORDER BY COMMISSION_PCT

 

Select Distinct last_name , first_name, COMMISSION_PCT from hr.Employees ORDER BY COMMISSION_PCT NULLS FIRST

 

Select first_name || ‘ ‘ || last_name “Employee_Name” from hr.Employees

 

Select first_name || ‘ ‘ || last_name || ‘ Earns $’ || Salary*12 || ‘ Annually’ “Message” from hr.Employees

 

Select FIRST_NAME || ‘ ‘ || last_name || ‘ Earns $’ || Salary*12 || ‘ Annually’ “Message” from hr.Employees Where Department_ID = 60 AND first_name = ‘Alexander’

 

Select first_name || ‘ ‘ || last_name || ‘ Earns $’ || Salary*12 || ‘ Annually’ “Message” , Department_ID from hr.Employees Where Department_ID = 60 OR Department_ID = 90

 

select * from hr.employees;

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null;

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT >= .2;

 

— order by to sort

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT >= .2 order by COMMISSION_PCT  desc;

 

select first_name, last_name, salary, COMMISSION_PCT, HIRE_DATE from hr.employees where COMMISSION_PCT >= .2 order by HIRE_DATE 

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null and rownum <=5;

 

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null and rownum <=5 order by COMMISSION_PCT ;

 

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null order by COMMISSION_PCT ASC , FIRST_NAME ASC

 

— You can also refer column using a number – 1 indicate first column which is first_name

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null order by COMMISSION_PCT ASC, 1;

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where first_name like ‘%d%’ order by COMMISSION_PCT NULLS FIRST

 

— AND : first_name like ‘D%’ and salary > 5000   – MIN RECORD 0  MAX RECORD  10  – COUNT = 5  –  INTERSECTION

— OR  : first_name like ‘D%’ or salary > 5000  – MIN RECORD 20  MAX RECORD  30  – COUNT = 25 – UNION

 

— 10 records where names which starts with D , 20 records which has salary greater than 5000  / 5 rows which are common

 

select count(*) from hr.employees where first_name like ‘D%’ ;  –9

select count(*) from hr.employees where salary >=5000;  –58

select count(*) from hr.employees where salary >=5000 and first_name like ‘D%’  ; — 5

 

select first_name, last_name from hr.employees where salary >=5000

INTERSECT

select first_name, last_name from hr.employees where first_name like ‘D%’;

 

select count(*) from hr.employees where salary >=5000 or first_name like ‘D%’;

select first_name from hr.employees where salary >=5000

UNION

select first_name from hr.employees where first_name like ‘D%’;

 

— OPERATORS in SQL

—  Identity / negation   + –

— Multiplication Division    * /

— Addition, Subtraction, Concatenation    + –  ||

— Comparison operators:     =   !=   <   >   <=    >=  IS NULL   LIKE   BETWEEN   IN

— Logical Operators:   NOT   AND    OR

— Set operators:   UNION   INTERSECT  MINUS

 

select * from hr.employees where salary <0

 

select * from hr.employees  where -salary < 0   — negation

 

select FIRST_NAME, LAST_NAME, Salary*12 Annual_Salary from hr.employees   — Multiplication

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* COMMISSION_PCT Total_Salary , COMMISSION_PCT, Salary  from hr.employees

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees where salary between 5000 and 10000 

 

— IT_PROG   AD_VP  (60,90)

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees where DEPARTMENT_ID IN (90,60)

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees where JOB_ID IN (‘IT_PROG’,’AD_VP’)

 

select * from hr.departments

 

select DEPARTMENT_ID from  hr.departments  where LOCATION_ID in (1700, 1800, 1500)

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name  from hr.employees where DEPARTMENT_ID IN (select DEPARTMENT_ID from  hr.departments  where LOCATION_ID in (1700, 1800, 1500))

 

 

select FIRST_NAME, LAST_NAME, LOCATION_ID , emp.DEPARTMENT_ID from hr.employees emp, hr.departments dept where COMMISSION_PCT is not null and emp.DEPARTMENT_ID = dept.DEPARTMENT_ID

 

— OPERATORS in SQL

 

—  Identity / negation   + –

 

— Multiplication Division    * /

 

— Addition, Subtraction, Concatenation    + –  ||

 

— Comparison operators:     =   !=   <   >   <=    >=  IS NULL   LIKE   BETWEEN   IN  ANY SOME ALL

 

— Logical Operators:   NOT   AND    OR

 

— Set operators:   UNION   INTERSECT  MINUS

 

Select * from hr.employees

 

Select * from hr.employees where salary = ANY (3000,6000)

 

Select * from hr.employees where salary = 3000 or salary =6000

 

Select * from hr.employees where salary = SOME (3000,6000)

 

Select * from hr.employees where salary >= ALL (3000,6000)

 

Select * from hr.employees where salary = 3000 and salary =6000

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

UNION

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

UNION ALL

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

INTERSECT

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

 

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

INTERSECT

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

 

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

MINUS

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

 

— (1,3,5,6) – (2,4,6,7)  =  (1,3,5)

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

MINUS

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

DEFINE salary_val = 3000

Select First_name, last_name from hr.employees where salary = &salary_val

UNDEFINE salary_val

 

— FUNCTIONS – String/text

Select lower(first_name), upper(last_name), initcap(email) from hr.employees

 

select concat(concat(first_name,’ ‘), last_name) from hr.employees — 2 strings

 

— Substring : SUBSTR    returns the position of a char:  INSTR

select first_name, substr(first_name,1,5), instr(upper(first_name),’A’) from hr.employees

 

— RPAD LPAD

 

select RPAD(first_name,12,’.’) || ‘ ‘ || LPAD(last_name,10,’x’)  from hr.employees

 

select RPAD(first_name,9,’ ‘) || ‘ ‘ || LPAD(last_name,9,’ ‘) || ‘ works as ‘ || LPAD(JOB_ID,8,’ ‘) MESSAGE from hr.employees

 

 

— — Number Functions

select * from dual


select sqrt(36) from dual


select distinct sqrt(salary) from hr.employees


select salary + COMMISSION_PCT TOTAL_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, round(salary + COMMISSION_PCT) ROUND_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, trunc(salary + COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, ceil(salary + COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, floor(salary + COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


select salary * -COMMISSION_PCT TOTAL_SALARY, ABS(salary * -COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


Select MOD(19,5) from dual


— — DATE FUNCTIONS

select * from hr.employees


select sysdate from dual


select FIRST_NAME, LAST_NAME, HIRE_DATE, floor(sysdate-hire_date)  from hr.employees


select FIRST_NAME, LAST_NAME, HIRE_DATE,  floor(sysdate-hire_date)  DAYS_SERIVICE, MONTHS_BETWEEN(sysdate,hire_date) MONTHS_SERVICE  from hr.employees


select ADD_MONTHS(sysdate,5) from dual


select NEXT_DAY(sysdate,1)  from dual — date of the first weekday 1 for Sunday, 2 for Monday ….


select NEXT_DAY(sysdate,’FRIDAY’)  from dual — date of the first weekday


select last_day(sysdate)   from dual


select last_day(‘1-Feb-2023’)   from dual


select next_day(‘1-Feb-2023’,2)   from dual


select ADDDATE(day,1,sysdate)   from dual


— year, quarter, month, day


select sysdate + 1 from dual


select DateAdd(sysdate, “1”, 10) from dual



select to_char(sysdate+100, ‘Dy DD-Month-YYYY HH24:MI:SS’) as “Current Time” from dual;


select dayofweek(sysdate) from dual


select now() from dual


Digitalfirm Nov 2022

Day 1:

Installation:

Python:  https://learn.swapnil.pw/python/pythoninstallation

 Pycharm:  https://learn.swapnil.pw/python/pythonides

 R & RStudio:   https://swapnil.pw/uncategorized/installating-r-studio

https://www.mckinsey.com/featured-insights

 

print("terterterg feererg eryey erytey eytytyt",end='\n')
print(10+5);print("10+5+3+1");print(10+5+3+1)
print("10+5+3+1 =",10+5+3+1, "and 5 + 4 + 95 =", 5+4+95);

# \n is used to move the content to new line
print('Hello',end='. ')
print("How are you",end='. ')
print("Thank you",end='\n') #I am printing thank you here
'this is a sample content print("Thank you")'
'''
multiline
text

'''
print(''' this is a sample text''')
print("\n is use for newline") #printing text is 2 different lines
print("\\n is use for newline") # \\ will be read as \

########################################
num1 = 18+4+2+10
print(num1)
print(num1)

print(num1)
print(num1)

quantity = 13
cost = 19
total = quantity * cost
print(total)
#output: The cost of each pen $19 so the total cost of 17 pens will be $323
print("The cost of each pen $",cost,"so the total cost of",quantity,"pens will be $",total)
#using f string - use variables within strings - variable should be in {}
print(f"The cost of each pen ${cost} so the total cost of {quantity} pens will be ${total}")

# basic variables
#integer
#float
#string
#bool
#complex
#data types
a = 50 #int - numbers without decimal
print("a = 50 => ", type(a))
a = 50.0 #float - numbers decimal
print("a = 50.0 => ", type(a))
a = "50" #str - text
print("a = '50' => ", type(a))
a = True # or False - 2 values , bool
print("a = True => ", type(a))
a = 5j #j is square root of -1
print("a = 5j => ", type(a))
print(a*a)

#Operators
print("Arithematic operations")
a=5
b=8
print(a+b)
print(a-b)
print(a*b)
print(b/a) #float as output
print(a**b) #** power/exponential
print(a//b) #integer division
print(b//a) #integer division
print(a%b) # 5
print(b%a)

print("Conditional Operators")
#input as integer/float - output will be bool
a=8 #assignment, assigning the value 5 to a
b=8
print(a>b) #is a greater than b
print(a<b)
print(a>=b)
print(a<=b)
print(a==b) # == asking a question
print(a!=b) #is a not equal to b
#Logical operators: I/P: Bool and O/P: Bool
# P1: Sachin and Dravid will open the batting
# P2: Sachin or Dravid will open the batting
# A: Sachin and Sehwag opened the batting -
#AND - even one condition is FALSE - entire thing would be False
#OR - even one condition is TRUE - entire thing would be TRUE
a = 10
b = 20
print("a>b or b>a and b!=a: ",not(a>b or b>a and b!=a))
print("not b==a: ",not b==a)
# TRUE

#membership: in
l1 = [3,4,5,6,7]
print(l1)
print(type(l1))
print(5 not in l1)

#convert into different number systems
a= 10 #integer - decimal number system
print(bin(a))
b=0b10
print("b = ",int(b))
#hex for hexadecimal (0x5050) and oct for octal (0o) - number systems
print(oct(b))
print(hex(b))
###### example 1
marks1 = 89
marks2 = 90
marks3 = 56
marks4 = 67
marks5 = 78
sum = marks1 + marks2+marks3 + marks4 + marks5
avg = sum/5
print(f"Total marks obtained in 5 subjects is {sum} and average is {avg} %")

###### example 2
marks1 = input("Enter marks in Subject 1: ")
marks1 = int(marks1)
marks2 = int(input("Enter marks in Subject 2: "))
marks3 = 56
marks4 = 67
marks5 = 78
sum = marks1 + marks2+marks3 + marks4 + marks5
avg = sum/5
print(f"Total marks obtained in 5 subjects is {sum} and average is {avg} %")

# Conditional statements
if avg>=50:
print("You have passed")
print("In IF")
print("Hello")
print("hi")
else:
print("You have failed")

print("Thank you")
#
##Assignment 1: Input a number from the user and Check if the number is positive or not
##Assignment 2: Input number of sides from the user and check if its triangle or not
n=4  #s2 = 0 s1 =5
if n<3:
print("Invalid Shape")
elif n==3:
print("Its a triangle")
elif n==4:
s1 = int(input("Enter length: "))
s2 = int(input("Enter breadth: "))
if s1==s2:
print("Its a square")
if s1==0:
print("Area is not possible")
else:
print("Area is: ",s1*s2)
else:
print("Its a rectangle")
if s1==0:
print("Area is not possible")
else:
if s2==0:
print("Area is not possible")
else:
print("Area is: ",s1*s2)

elif n==5:
print("Its a pentagon")
s1 = int(input("Enter length: "))
s2 = int(input("Enter breadth: "))
if s1 == s2:
print("Its a square")
if s1 == 0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
else:
print("Its a rectangle")
if s1 == 0 or s2==0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
elif n==6:
print("Its a hexagon")
s1 = int(input("Enter length: "))
s2 = int(input("Enter breadth: "))
if s1 == s2:
print("Its a square")
if s1 == 0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
else:
print("Its a rectangle")
if s1 == 0:
print("Area is not possible")
elif s2==0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
elif n==7:
print("Its a heptagon")
elif n==8:
print("Its an octagon")
else:
print("Its a complex shape")


#Assignment: Program to find sum and avg of 5 marks
# and assign grade on the basis on:
# avg > 90: A
#avg >75: B
#avg >60: C
#avg >50: D
#avg >40: E
#avg<40: F
#Loops- repeat given block of code

#For loop - exactly how many times to repeat
for i in range(1,10,2): #range(start - included,end-excluded,increment): 1,3,5,7,9
print(i,":Hello")

for i in range(3, 6): # range(start - included,end-excluded,increment=1): 3,4,5
print(i, ":Hello")

for i in range(3): # range(start=0,end-excluded,increment=1): 0,1,2
print(i, ":Hello")
sum=0
for i in range(5):
marks = int(input("Enter marks: "))
sum+=marks
avg = sum/5

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

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

'''
*
* *
* * *
* * * *
* * * * *
'''
#While
i=0
while i<5:
print("Hello")
i+=1

#adding 2 numbers till user says yes
ch='y'
while ch=='y':
a=30
b=50
print("Sum is 80")
ch=input("type y to continue, anyother key to stop: ")



#rewriting same program using While True
while True:
a = 30
b = 50
print("Sum is 80")
ch = input("type y to continue, anyother key to stop: ")
if ch!='y':
break

#lets write a program to print addition of 2 numbers only when they are even
#otherwise ignore, continue till user wants

while True:
n1 = int(input("Enter first number: "))
if n1%2==1:
continue #continue will take you the beginning of the loop
n2 = int(input("Enter second number: "))
if n2 % 2 == 1:
continue
sum = n1 + n2
print("Sum is ",sum)
ch=input("Hit enter to continue, anyother key to stop: ")
if len(ch)!=0:
break #break will throw you out of the loop

Assignments

1.     # Assignment 1: Modify the Total Avg marks calculation program to do it for 5 students
# Assignment 2: Modify your Voting program (eligible to vote or not) to a repeat it for multiple input until
# user wants to continue

  1. Write a Python program that computes the factorial of an integer.
  2. Program to find sum N natural numbers
  3. Write code to display and count the factors of a number
  4. Program to check if eligible to vote in India
  5. Enter marks of 3 subjects for 5 students and grade them. Check for data validity and use BREAK and CONTINUE where necessary
  6. Check the type of a Triangle: Isosceles, Equilateral, Scalene, Right Angle
  7. Input 3 numbers and re-arrange them in ascending order. Use BOOLEAN
#STRINGS
name1 = "Sachin"
#first character
print(name1[0]) #0 is for first character
print(name1[2]) #3rd character
size = len(name1)
print(name1[size-1]) #last character
print(name1[-1]) #last character
print(name1[1:4]) #2,3,4 th characters
print(name1[:3]) #no val on left of : means its zero
print(name1[3:6]) #last 3 characters
print(name1[size-3:size]) #last 3 characters
print(name1[-6:-3]) #first 3 characters
print(name1[-size:3-size]) #first 3 characters
print(name1[-3:]) #last 3 char - no val on right of :mean go till last

print("For loop")
for i in name1:
print(i)

for i in range(len(name1)):
print(f"the chracter at the index {i} is {name1[i]}")

for i in enumerate(name1):
print(i)

for i,j in enumerate(name1):
print(f"the chracter at the index {i} is {j}")

print("S" in name1)
name2 = "Tendulkar"
print(name1 + " " + name2)

print((name1 +" ")* 4)
#STRINGS
name1 = "Sachin"
#first character
print(name1[0]) #0 is for first character
print(name1[2]) #3rd character
size = len(name1)
print(name1[size-1]) #last character
print(name1[-1]) #last character
print(name1[1:4]) #2,3,4 th characters
print(name1[:3]) #no val on left of : means its zero
print(name1[3:6]) #last 3 characters
print(name1[size-3:size]) #last 3 characters
print(name1[-6:-3]) #first 3 characters
print(name1[-size:3-size]) #first 3 characters
print(name1[-3:]) #last 3 char - no val on right of :mean go till last

print("For loop")
for i in name1:
print(i)

for i in range(len(name1)):
print(f"the chracter at the index {i} is {name1[i]}")

for i in enumerate(name1):
print(i)

for i,j in enumerate(name1):
print(f"the chracter at the index {i} is {j}")

print("S" in name1)
name2 = "Tendulkar"
print(name1 + " " + name2)

print((name1 +" ")* 4)
# String methods
val1 = "Sachin 10Dulkar"
print(val1.isalnum())
print(val1.islower())
print(val1.istitle())
val2 = "12345"
print(val2.isdigit())
#lower upper title
print("Second set of functions")
val3 = "how ARE you doiNG todaY?"
print(val3.upper())
print(val3.lower())
print(val3.title())
#find
txt_to_search = "Are"
val4 = val3.lower()
print(val4.find(txt_to_search.lower()))
print(val3.replace("ARE","is"))
val3 = val3.lower().replace("are","is")
print(val3)

#split and join
val3 = "how ARE you are doiNG todaY?"
print(val3.split())
val4 = "HOW|ARE|YOU|DOING|TODAY"
print(val4.replace("|"," "))
val4_list = val4.split("|")
val6_str = " ".join(val4_list)
print(val6_str)
val7 = " how ARE you doiNG todaY? "
val7_strip = val7.strip()
print(val7_strip)
val_cnt = val3.lower().count("area")
print(val_cnt)
# LIST
str1 = "Hello"
print(str1[1])
# str1[1] = "Y" #this is not possible
# strings are called as immutable data types
list1 = [50, 4, 5.5, "Hello", True]
print(type(list1))
print(len(list1))
print(list1[3][2])
print(type(list1[3]))

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

l1 = [1, 2, 3, 4]
l2 = [10, 20, 30]
l3 = l1 + l2
print("Adding two list: ", l3)
print("Multiply: ", l2 * 3)
print(30 not in l2)

print(l2[2])
l2[2] = "Thank You" # lists are mutable
print(l2[2])

sum = 0
marks = []
for i in range(0):
m1 = int(input("Enter marks: "))
sum += m1
marks.append(m1)

print("Total marks", sum)

# append will add at the end
# insert - pos and value: value is added at the given pos
marks.insert(2, 11) # [11
marks.insert(2, 22) # [11,22]
marks.insert(2, 33) # [11,22,33]
marks.insert(2, 44) # [11,22,44,33]
marks.insert(2, 55) # [11,22,55,44,33]
marks.insert(2, 66) # [11,22,66,55,44,33]
marks.insert(2, 77) # [11,22,77,66,55,44,33]
# marks[7] = 100 - error since index 7 isnt there
print("Marks obtained are: ", marks)
# pop - removes from the given position
# remove - removes given value
val_remove = 77
if val_remove in marks:
marks.remove(val_remove)
else:
print("Value is not present in the list")
print("Marks obtained are: ", marks)
pos_remove = 2
if pos_remove < len(marks):
marks.pop(pos_remove)
else:
print("List doesnt have that index")

print("Marks obtained are: ", marks)
marks.clear()
print("Marks obtained are: ", marks)

Assignment


 

Assignments

1. Write a Python program to sum all the items in a list.

2. Write a Python program to multiplies all the items in a list.

3. Write a Python program to get the largest number from a list.

4. Write a Python program to get the smallest number from a list.

5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. 

Sample List : [‘abc’, ‘xyz’, ‘aba’, ‘1221’]

Expected Result : 2

6. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. 

Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

7. Write a Python program to remove duplicates from a list.

8. Write a Python program to check a list is empty or not.

9. Write a Python program to clone or copy a list.

10. Write a Python program to find the list of words that are longer than n from a given list of words.

11. Write a Python function that takes two lists and returns True if they have at least one common member.

12. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.

Sample List : [‘Red’, ‘Green’, ‘White’, ‘Black’, ‘Pink’, ‘Yellow’]

Expected Output : [‘Green’, ‘White’, ‘Black’]

13. Write a Python program to generate a 3*4*6 3D array whose each element is *.

14. Write a Python program to print the numbers of a specified list after removing even numbers from it.

15. Write a Python program to shuffle and print a specified list.

16. Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).

17. Write a Python program to generate and print a list except for the first 5 elements, where the values are square of numbers between 1 and 30 (both included).

18. Write a Python program to generate all permutations of a list in Python.

19. Write a Python program to get the difference between the two lists.

20. Write a Python program access the index of a list. 

DAY 8

 

def myreverse(a):
print("A = ", a)
a.reverse()
return a[0]


list1 = [50, 4, 5.5, "Hello", True]
list2 = [90, 20, 50, 40, 30, 70]
list2.reverse()
# print(list2)
print("Myreverse: ", myreverse(list2))
print(list2.reverse())
list2.sort()
# print(list2)
list1.extend(list2)
print("New set: ", list1)
a = "5"
# print(int(a))
print("Learning COPY")
list2 = [90, 20, 50, 40, 30, 70]
list3 = list2 # shallow copy
list4 = list2.copy() # deep copy
print("list2: ", list2)
print("list3: ", list3)
print("list4: ", list4)
list2.append(10)
print("list2: ", list2)
print("list3: ", list3)
print("list4: ", list4)

print("Stack Implementation")
list_master = []
while True:
print("1. Add to the stack")
print("2. Remove from the stack")
print("3. Clear the stack")
print("4. Quit")
op = int(input("Enter your option"))
if op == 1:
val = int(input("Enter the element to add: "))
list_master.append(val)
print("After adding list: ", list_master)
elif op == 2:
if len(list_master) > 0:
list_master.pop(-1)
print("After adding list: ", list_master)
else:
print("List is empty!")
elif op == 3:
list_master.clear()
print("After adding list: ", list_master)
elif op == 4:
print("Thank you for using the program.")
break
else:
print("Invalid option, Try again!")

############### LIST #######################

# TUPLE
t2 = ()
t3=(55,)
t1 = (5, 4, 6, 8, 4)
print(type(t1))
t1 = list(t1)
print(t1.count(8))
# Dictionary
# list: linear ordered mutable collection
# tuple: linear ordered immutable collection
# dictionary: non-linear ordered mutable collection (unordered untill 3.7)
# dictionary is made up of key & value
dict1 = {} # empty dictionary
print(type(dict1))
dict1 = {"Name": "Sachin", "City": "Mumbai", "Runs": 12900, "IsPlaying": False}
print(dict1)
print(dict1["City"])
print(dict1.get("City"))
val = "India"
key = "Country"
t_dict = {key: val}
dict1.update(t_dict)
print("Dictionary after Update: \n", dict1)
print("Size of dictionary: ", len(dict1))

print("keys:", dict1.keys())
for i in dict1.keys():
print(i)
for i in dict1.values():
print(i)
for i in dict1.keys():
print(dict1[i])

for i, j in dict1.items():
print(i)

if "City" in dict1: # default it checks in keys
print("We have City")
if "Mumbai" in dict1.values():
print("We have City Mumbai")
else:
print("Mumbai is not there")

print("Dict1: ", dict1)
dict1.pop("City") # key as input
print("Dict1: ", dict1)
dict1.popitem() # key as input
print("Dict1: ", dict1)
print(type(dict1.values()))
dict1.pop(list(dict1.keys())[list(dict1.values()).index("Sachin")])
# print()
print("Dict1: ", dict1)
#Set - also mutable
set1 = {"New York"}
print(type(set1))
set1.add("Chicago")

#update
#union
s1 = {1,3,5,7,2,4}
s2 = {2,4,6,8}
print("Union: ",s1.union(s2))
print("Union: ",s1 | s2)
#s1.update(s2)
#print("Union Update: ",s1)

#difference
print("difference :",s1-s2)
print("difference :",s2-s1)
print("Difference: ",s1.difference(s2))
#s1.difference_update(s2)
#print("Difference update: ",s1)
print("Symmetric Difference: ", s1 ^ s2)


#intersection
print("intersection :",s1.intersection(s2))
print("intersection: ",s1 & s2)
print("intersection update: ",s1.intersection_update(s2))
print(s1)
s1.intersection_update(s2)
print("intersection update: ",s1)

print(set1)
l1 = [5,10,10,15,15,15,20,20,25]
l1 = list(set(l1))
print(l1)

### Functions



def myfunc1(name): #which takes ONE input argument and doesnt return anything
print("Hello ",name)
print("How are you?")
print("Where are you going?")

def myfunc2(name): #which takes ONE input argument and doesnt return anything
print("Hello ",name)
print("How are you?")
print("Where are you going?")
return "Thank You", "Bye"

def myfunc(): #this is an example which doesnt take any input argument and doesnt return
print("Hello")
print("How are you?")
print("Where are you going?")

myfunc()
print("second time: ")
myfunc1("Kapil") #1 required positional argument: 'name'
print(myfunc2("Sachin"))


#functions

#required positional arguments
## Function definition
def calculate(a,b):
print("Value of a is ",a)
print("Value of b is ",b)
sum = a+b
diff = a-b
mul = a*b
div = a/b
return sum,diff,mul,div

## Function definition - Default argument
def calculate1(a,b=50):
print("Value of a is ",a)
print("Value of b is ",b)
sum = a+b
diff = a-b
mul = a*b
div = a/b
return sum,diff,mul,div

result = calculate(30,20)
print("Addition of given 2 values is ", result[0])
result = calculate1(30,5)
print("Addition of given 2 values is ", result[0])
result = calculate1(30)
print("Addition of given 2 values is ", result[0])
#non positional
result = calculate1(b=30,a=5) #nonpositional => Keyword arguments
print("Addition of given 2 values is ", result[0])

#variable name arguments
def mycalculation(a,c,*b,**d): # * takes multiple values
print("A = ",a)
print("B = ", b)
print("C = ", c)
print("D = ", d)

mycalculation(5,6,7,8,9,10,11,name="Sachin", runs=5000)

def check_prime(a):
result1 = True
for i in range(2,a//2):
if a%i == 0:
result1 = False
break
return result1

result = check_prime(1100)
if result:
print("Its a prime number")
else:
print("Its not a prime number")

#generate prime numbers between 500 and 1000
prime_num = []
for i in range(500,1001):
if check_prime(i):
prime_num.append(i)
print("Prime numbers are: ",prime_num)
#Recursive function
def myfunc(number):
if number <1:
return 0
print(number)
myfunc(number-1)

def factorial(n):
if n<1:
return 1
return n * factorial(n-1)


if __name__ =="__main__":
myfunc(100)
# 5! = 5 * 4 * 3 * 2 * 1!
fact = factorial(5)
print("Factorial is ",fact)
class Person:
population = 0
def welcome(self,name):
self.name = name
print("Welcome to the world")
Person.population+=1

def display(self):
print("Welcome to ",self.name)
print("Total Population: ",Person.population)

p1 = Person()
p1.welcome("Sachin")
p3 = Person()
p3.welcome("Laxman")

p2 = Person()
p4 = Person()
p5 = Person()
p2.welcome("Rekha")
p4.welcome("Geeta")
p5.welcome("Rohit")
p3.display()
p4.display()
class Person():
def __method1(self):
print("Method 1")
def _method2(self):
print("Method 2")
def method3(self):
print("Method 3")
self.__method1()
class Student(Person):
def read(self):
print("I am studying")

p1 = Person()
#p1.__method1() - private members cant be called
p1.method3()
p1._method2()

s1 = Student()
s1.read()
s1.method3()

# public
#protected _ :practically its like public, but theoritically it cant be accessed outside the class
#private __ : members can not be used outside the class

19 DEC 2022

#Class
str1="555"
print(type(str1))
str2 = "Good day"
print(str1.upper())

class Apple:
loc = "World"
def getvalue(self,name):
self.name = name
def display(self):
print(f"I am {self.name}")
@classmethod
def setaddress(cls):
cls.loc = "Universe"
@classmethod
def address(cls):
print(f"Location: {cls.loc}")

a1=Apple()
a1.getvalue("Sachin")
a2=Apple()
a2.getvalue("Kapil")
a3=Apple()
a3.getvalue("Laxman")
a4=Apple()
print(type(a1))
a1.display()
a1.setaddress()
a2.address()

class MySum:
def getval(self):
self.num1 = int(input("Enter value 1: "))
self.num2 = int(input("Enter value 2: "))
def printsum(self):
self.sum = self.num1 + self.num2
print("Sum of the values: ",self.sum)

m1 = MySum()
m1.getval()
m1.printsum()
class Employee:
population = 0

def __init__(self,name,age, salary):
self.name = name
self.age = age
self.__salary = salary
Employee.population +=1

def edit_details(self,name,age,salary):
self.name = name
self.age = age
self.__salary = salary
def _getsalary(self):
return self.__salary

@classmethod
def display_pop(cls):
print("Total Count of Objects = ",cls.population)

p1 = Employee("Sachin",48,1500) # this is calling __init__()
p2 = Employee("Virat", 29,1400)
p3 = Employee("Rohit", 29,1300)
#print(p1.__salary)
p1.display_pop()
print(p1._getsalary())
#print(p2.getsalary())
#print(p3.getsalary())

'''
Encapsulation:
access modifiers:
3 types: Public (variablename), Private (__variablename) -only to class, Protected (_variablename)
'''
word = "hello"
guess = "ll"
ind = 0
word1 = word.replace("l","L",1)
print(word1)
for i in range(word.count(guess)):
ind = word.find(guess,ind)
print(ind)
ind=ind+1

word3 = "How are you doing"
l1 = word3.split("o")
print(l1)
word4 = "o".join(l1)
print(word4)

#Strings
word = "hEllo".lower()
print(word)
display_text = "* "*len(word)
print(display_text)
while True:
guess = input("Guess the character: ")
guess = guess[0].lower()

if guess.isalpha():
if guess in word:
ind = 0
for i in range(word.count(guess)):
ind = word.find(guess, ind)
#now time to reveal
#0 - 0, 1-2, 2-4
display_text = display_text[:ind*2] + guess+display_text[ind*2+1:]
ind = ind + 1
print(display_text)

if "*" not in display_text:
print("Congratulations!")
break
else:
print("Given character is not in the original word")
else:
print("Invalid character")

class Book:
book_count = 0
def __init__(self, author, title, book_id):
self.author = author
self.title = title
self.book_id = book_id
Book.book_count+=1

def getbook(self):
print(f"{self.title} is written by {self.author}")

@classmethod
def getBookCount(cls):
print("Total books available: ",cls.book_count)

book1 = Book('Swapnil Saurav','Learn and Practice Python', 9012)
book1.getbook()
book1.getBookCount()
#Inheritance
class School:
def __init__(self,schoolname):
self.schoolname = schoolname

def _displaydetails(self):
print("School name is ",self.schoolname)

class Student (School):
def __init__(self,stname, schoolname):
School.__init__(self,schoolname)
self.stname = stname

def displaydetails1(self):
print("Student name is ",self.stname)
def displaydetails1(self,name):
print("Student name is ",self.stname)

def displaydetails1(self,name,age):
print("Student name is ", self.stname)

class Teacher (School):
def __init__(self,tname):
self.tname = tname

def displaydetails(self):
print("Teacher name is ",self.tname)

sc1 =School("ABC International School")
st1 = Student("Sachin Tendulkar","XYZ International School")
t1 = Teacher("Kapil Dev")
sc1._displaydetails()
st1.displaydetails1()
t1.displaydetails()

'''
Public
Protected _var (single underscore)
Private __var (double underscore)
'''
#1. declare a class calc
#2. initialize functon to read 3 variables
#3. create another method to calculate: sum. multiply minus
#4. Display the result using another method
#5. Create another class to perform arithematic operators
## that you have learnt in Python: + - * / % ** //

class Calc:
def __init__(self,a,b,c):
self.n1 = a
self.n2 = b
self.n3 = c
self.add = "Addition not yet done"
self.mul = "Multiplication not yet done"
self.min = "Difference not yet done"

def calc(self):
self.add = self.n1 + self.n2
self.mul = self.n1 * self.n2
self.min = self.n1 - self.n2

def display(self):
print("Sum = ",self.add)
print("Multiplication = ",self.mul)
print("Difference = ",self.min)

class Arithmatic(Calc):
def __init__(self,a,b,c):
Calc.__init__(self,a,b,c)
self.n1 = a
self.n2 = b
self.n3 = c
self.div = "Division not yet done"
self.mod = "Modulus not yet done"
self.pow = "Power not yet done"
self.intdiv = "Integer Division not yet done"

def calc(self):
Calc.calc(self)
self.div = self.n1 / self.n2
self.mod = self.n1 % self.n2
self.pow = self.n1**self.n2
self.intdiv = self.n1 // self.n2

def display(self):
Calc.display(self)
print("Division = ",self.div)
print("Modulus = ",self.mod)
print("Power = ",self.pow)
print("Integer Division = ", self.intdiv)

c1 = Arithmatic(10,5,12)
c1.calc()
c1.display()

c2 = Calc(3,4,6)
c2.calc()
c2.display()

TYPES OF FUNCTION

 

def myfun1(a,b):
'''Example of Required Positional Argument'''
print(f"a is {a} and b is {b}")
sum = a + b
print("Sum: ",sum)
#return sum

def myfun2(a=16,b=6):
'''Example of Default Positional Argument'''
print(f"a is {a} and b is {b}")
sum = a + b
print("Sum: ",sum)
#return sum

def myfun3(a,*b,**c): #variable length arguments
print("a = ",a)
print("b = ", b) # * means tuple
print("c = ", c) # **- dictionary


myfun3(50,5,6,7,8,9,9,11,14,name="sachin",game ="Cricket")


#Keyword argument
n1,n2=14,26
print(myfun2(a=n2,b=n1))
result = myfun2(b=34)


n1,n2=14,26
print(myfun2(n1,n2))
result = myfun2(34)
#result*=2
print(result)

n1,n2=54,66
print(myfun1(n1,n2))
result = myfun1(34,76)
#result*=2
print(result)

#Types of functions based on input parameter:
## 1. Required positional arguments: YOu have to provide value and in same order (left to right)
## Default (positional) arguments
import os
print(os.name)
if os.name=="nt":
print("Its a Windows machine")
elif os.name=="posix":
print("its a Linux/Mac")
else:
print("Other OS")

print(os.getcwd())
#os.rmdir("Nov_2")
#os.rename("file1.txt", "file1dec.txt")
print("iterate in folder:")
from pathlib import Path
path_list = Path("C:\\Users\\Hp\\Poems\\")
for i in path_list.iterdir():
print(i)
os.mkdir("Test2")

fp= open(r"C:\Users\Hp\Poems\Poem1.txt","r") #r for read w for write a append
content = fp.read(200)
print(type(content))
print(content)
fp.seek(0)
content = fp.readline(500)
print(type(content))
print(content)

content = fp.readlines()
print(type(content))
print(content[4])
fp.close()
fp1 = open(r"C:\Users\Hp\Poems\testCopy\sample.txt","a")
if fp1.writable():
fp1.writelines(content)

fp1.close()
#Numpy
import numpy as np
x = range(16)
# range: 0 to upto 16 - 0...15
x = np.reshape(x,(4,4))
print(type(x))
print(x)
size = x.shape
print("Total rows = ",size[0])
print("Total columns = ",size[1])

#indexing
print(x[1,2])
print(x[3,1])
print(x[0,:])
print(x[:,0])
print(x[1:3,1:3])

#
x = np.zeros((3,3))
print(x)
x = np.ones((3,3))
print(x)
x = np.full((3,3),99)
print(x)

x = np.random.random((3,3))
print(x)

l1 = [[5,10,15],[9,10,11],[2,3,1]]
print(type(l1))
l1 = np.array(l1, dtype=np.int8)
print(l1)
print(type(l1))
l2 = np.array([[3,6,9],[7,14,21],[2,4,6]])
print(l2)

#addition
print(l1 + l2)
print(np.add(l2,l1))

print(l1 - l2)
print(np.subtract(l2,l1))

print(l1 / l2)
print(np.divide(l2,l1))

print("==========================")
print(l1,"\n",l2)
print(l1 @ l2)
print(np.matmul(l2,l1))

for i in l1.flat:
print(i)

x = np.identity(6)
print(x)
print("Printing l1:\n",l1)
print("Printing Transpose of l1:")
l1_t = np.transpose(l1)
print(l1_t)

l1_det = np.linalg.det(l1)
print("Determinant of L1 is ",l1_det)
l1_inv = np.linalg.inv(l1)
print("Inverse of L1 is ",l1_inv)

#Singular matrix have determinant zero so we cant find inverse of that matrix

# 2x-3y = 8
# 3x-4y = 12
# what is x & y?
# Numpy to solve linear algebra
# 2x +5y + 2z = -38
# 3x - 2y + 4z = 17
# -6x +y -7z = -12
import numpy as np
Coeff = [[2,5,2],[3,-2,4],[-6,1,-7]]
Coeff_mat = np.array(Coeff)
Coeff_det = np.linalg.det(Coeff_mat)
if Coeff_det ==0:
print("There are no possible solution for given equations")
else:
Const = [[-38],[17],[-12]]
Coeff_inv = np.linalg.inv(Coeff_mat)
sol = np.matmul(Coeff_inv,Const)
print("Solution is: \n",sol)
print(f"x={sol[0,0]}, y={sol[1,0]}, z={sol[2,0]}")
#SETS
set1 = {1,5,9,10,20}
print(type(set1))
set1.add(22)
print(set1)

set2 = set1 #deep copy - set2 and set1 will point to same location in memory
set3 = set1.copy() #shallow copy - create a duplicate copy
print("printing 1: ")
print("Set 1: ",set1)
print("Set 2: ",set2)
print("Set 3: ",set3)
set2.add(25)
set2.add(29)

print("printing 2: ")
print("Set 1: ",set1)
print("Set 2: ",set2)
print("Set 3: ",set3)
print("Set 1: ",id(set1))
print("Set 2: ",id(set2))
print("Set 3: ",id(set3))

#union, intersection, difference, symmetric difference
Set2 = {1, 20, 5, 22, 9, 10, 29, 25}
Set3 = {1, 20, 5, 22, 9, 10,31,35}
print(Set2.union(Set3))
print(Set2 | Set3)

print(Set2.intersection(Set3))
print(Set2 & Set3)

print(Set2.difference(Set3))
print(Set3 - Set2)

print(Set2.symmetric_difference(Set3))
print(Set2 ^ Set3)
print("Set 2: ",Set2)
print("Set 3: ",Set3)
print(Set2.symmetric_difference_update(Set3))
print("Set 2: ",Set2)
print("Set 3: ",Set3)

from datetime import datetime
currenttime = datetime.now()
print("Current time: ",currenttime)

n=10000
counter = 0
for i in range(n):
for j in range(n):
counter+=1
if counter*100 % (n*n)==0:
print(f"{counter*100//(n*n)}% Task Completed")

endtime = datetime.now()
print("Total time taken by the program is ",endtime-currenttime)

from datetime import datetime, timedelta
print("Current time: ",datetime.now())
print("Current date: ",datetime.now().strftime("%Y,%m-%d"))
print("Current year: ",datetime.now().year)
print("Current month: ",datetime.now().month)
print("Current day: ",datetime.now().day)
print("Current hour: ",datetime.now().hour)
print("Current minute: ",datetime.now().minute)
print("Current second: ",datetime.now().second)

import time
print("Current time: ",time.strftime("%Y,%m-%d"))
print("Total time: ",time.time())
print("Tomorrow's time: ",datetime.now()+timedelta(days=1))
from pytz import timezone
print("Current time in US Eastern is",datetime.now(timezone("US/Eastern")).strftime("%Y-%m-%d"))

# random numbers
import random
random.seed(100)
print("Random = ",random.random()) # randon no. between 0 & 1
print("Random = ",int(random.random()*1000))
print("Random Integer values: ",random.randint(500,9000))
choices = ["ONE","TWO","THREE","FOUR","FIVE","SIX"]
print("One value from the list: ",random.choice(choices))
random.shuffle(choices)
print("random shuffle: ",choices)

#MAP - works with List where you want to apply same calculation to all the numbers
distances = [1100,1900,4500,6500,3400,2900,5400]*500
dist_ft = 0 #3.1 *
from datetime import datetime

start=datetime.now()
dist_ft = list(map(lambda x:3.1*x,distances))
end=datetime.now()
print("Total time taken by MAP = ",end-start)

start=datetime.now()
dist_ft2 = []
for i in distances:
val = i*3.1
dist_ft2.append(val)
#print("Output using Loops = ",dist_ft2)
end=datetime.now()
print("Total time taken by LOOP = ",end-start)