Swapnil Saurav

##### 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 implicitprint(var_1+10)#variable naming rule: It shouldnt start with a number, only _ is a allowerd special charactervar_1 = 15print(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 / Falsevar_1 = 5jprint(var_1 * var_1) #25*-1= -25print(type(var_1))#operators & operation#Arithmetic operators:  +  -  *  /   // (integer division)  ** % (modulus - mod)num1 = 7num2 = 3print(num1/num2)print(50 // 6)print(num1 ** num2)print(50 % 6)#Comparison operators: ==  >  >=  <  <=  !=  Will always result in bool valuesnum1 = 10num2 = 10num3 = 15print(num1 == num2) #is num1 equal to num2 ? Trueprint(num1 != num3) #is num1 not equal to num2? Trueprint(num1 > num2) # Falseprint(num1 >= num2)  #Trueprint(num1 < num2) # Falseprint(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 = Truea,b,c=5,       10,10print(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 notnum1 = 0if 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")`

## Day 1: Watch The Video Here

`#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 1if num==0:    print("Its Zero")if num <0:    print("Its negative")if num >0:    print("Its positive")#case 2if 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.0marks_in_subject3 = 88marks_in_subject4 = 8marks_in_subject5 = 8total = marks_in_subject1 + marks_in_subject2 + marks_in_subject3+marks_in_subject4+marks_in_subject5avg = total/5print("Average = ",avg)#avg > 85 - A# avg>70 - B# avg > 60 - C#avg >50 - D#avg >40 - E#avg < 40 - F#avg >=90 - special awardif 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 - Repeatprint("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,4print("For loop 1:")for var in range(5):    #print("Value of var is ",var)    print("Hello")print("Using while: ")counter = 1while counter <=5:    counter = counter + 1    print("Hello")print("Thank You")`

## Day 2: Watch the video here

DAY 3:

`#Day 3: Loops#For loop - along with range() , how many times the loop has to runfor i in range(1,101):    print(i,end="\t")print()print("Hello")#by default print will give us a newlinen,m=5,6for j in range(m):    for i in range(n):        print("*",end=" ")    print()'''* * * * * * * * * * * * * * * * * * * * * * * * * '''n=5for j in range(n):    for i in range(j+1):        print("*",end=" ")    print()'''*  * *  * * *  * * * *  * * * * * '''n=5for 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 notnumber = 51# 51 - 1, 51isPrime = Truefor i in range(2,number//2):    if number%i==0:        isPrime=False        break        #break will throw you out of current loopif isPrime:    print("Number is prime")else:    print("Number is not Prime")total = 0for i in range(1,101):    total=total+iprint("\n total is ",total)#1: total= 0 + 1 = 1#2: total = 1 + 2 = 3#3: total = 3 + 3 = 6#Whilewhile True:    print("Hello")    if True:        breakimport randomrandom.seed(10)num = random.random() #generates random number between 0 and 1print("num = ",num)num1 = random.randint(1,10)  # integer values - between 1 and 10 (both inclusive)print("num1 = ",num1)attempts = 0actual = 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")`

## DAY 3: Video

`#Stringsvar1 = 'hello'print(type(var1))var2 = "good morning"print(type(var2))var3 = '''Hi therewhere are you goingI am here till you come'''print(type(var3))var4 ="""Hows goingI was waiting to talk to yousee 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 indexingprint("=====> 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)`

## DAY 4 Video - WHILE LOOP and STRINGS Intro

`#Stringsstr1 = "hellothere"  #str1 is an object of class strstr2 = "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 -independentnum1 = 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 = 0print("num1 = ",num1)# Exception Handling - to handle runtime errors - preferredstr1 = "HELLO"#strings are immutableprint(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,countprint("After Replace: ",str3)print("you" in str2)print(str2.lower().find("you",9))  #find: substring, start, endvar1 = str2.split("o")print(var1)str5 = "o".join(var1)print(str5)#abc => abcing#abing = abinglyinp_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 = 0for 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+cprint("Largest text is",l_str)`

## Day 5 Video - String methods

##### Python Zero to Hero
`### DAY 1print("Welcome")val1 = 5#val1 is a variable in this caseprint("val1")print("Value of variable val1 =",val1)#type() - it gives the datatype of variableprint(type(val1))   # <class 'int'> integer: nondecimal value- -5, -99,0,9999999val1 = 5.8print("Value of variable val1 =",val1)print(type(val1))   # <class 'float'> float: number with decimal value- -5.0, -99.1,0.0,9999999.5val1 = 5j #it is same as i of Maths, square root of -1print("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 textval1 = "55"val2 = 55val3 = 44;val4 = "44";print(val1 + val4);print(val2 + val3)val1 = True #/ Falseprint("Value of variable val1 =",val1)print(type(val1))   #<class 'bool'> - boolean just 2 values: True and False# input() - used to read value from the username = input("Enter your name: ")print(name)## DAY 2: 11 DEC 2022name = input("Enter your name: ") #automatically its gets converted into str - implicit conversionmarks1 = input("Enter marks in Subject 1: ")marks1 = int(marks1)  #explicit conversionmarks2 = int(input("Enter marks in Subject 2: "))marks3 = int(input("Enter marks in Subject 3: "))print(type(name))print(type(marks1))sum = marks1 + marks2 + marks3avg = sum / 3print(name, "scored a total of",sum,"marks at an average of",avg)# f string - format stringprint(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 * breadthperimeter = 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 operationsval1 = 10val2 = 3print(val1 + val2)print(val1 - val2)print(val1 * val2)print(val1 / val2)print(val1 ** val2) #power of val2print(val1 // val2)  #integer division -will result in integer onlyprint(val1 % val2)  #modulo - remainderprint(16 ** 0.5)#Comparison operators:  ==  !=   <  <=  >   >=# input can be anything but output will always be BOOL valuea=10b=3c=10print(a==b)  #Falseprint(a!=b)   #Trueprint(a==c)  #Trueprint(a!=c)  #Falseprint(a>b)  #Trueprint(a>=c)   #Trueprint(a<=c)  #Trueprint(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 Correctprint("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 = 0a=3b=1c=5D = b**2 - 4 * a * csol1 = (-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 = 0a = 2b = -12c = -54D = b**2 - 4 * a * csol1 = (-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 =-6if 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 =98marks2 = 88marks3 = 99sum= marks1 + marks2 + marks3avg = sum/3print("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 truechoice = "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,3for 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 = 1end = 10for 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 = 1for 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 itwhile 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 100num = 50count = 0max_try = 10while 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 100import randomnum = random.randint(1,100)count = 0max_try = 10while 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 = 50steps=0print("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]  #LISTprint(type(list_of_value))print(list_of_value)print(list_of_value[2])l1 = [5,10,15,20,25,30,35]print(l1*3)#appendlist_of_value.append(45)list_of_value.insert(2,12)print(list_of_value)#insert# Battleship Challengeimport randombattle_pattern = []total_rows = 5total_cols = 5for i in range(total_rows):    battle_pattern.append(['0 ']*5)# created a function named display_battle() - user defined functiondef 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 attackfor 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 loopwhile 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 acceptingsum=0while 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#Stringsval1 = "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 fineI am in your cityI 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=0for i in val2:    if i=='a' or i=="e" or i=='i' or i=="o" or i=="u":        sum+=1print(f"Given text has {sum} vowels")sum=0for i in val2.lower():  #lower() converts into lowercase    if i=='a' or i=="e" or i=='i' or i=="o" or i=="u":        sum+=1print(f"Given text has {sum} vowels")#in - membership test - left side value is present in the right side or notsum=0for i in val2.lower():  #lower() converts into lowercase    if i in "aeiou": #True only if i value is present in right side text        sum+=1print(f"Given text has {sum} vowels")text1 = "Hello all"#len() - counts the number of charactersprint("Total characters in text1 is",len(text1))#indexing - extracting portion of the data - subset# [] is used for indexingprint(text1[0]) #first member of text1print(text1[2]) #third member of text1print(text1[len(text1)-1])  #last memberprint(text1[len(text1)-3])  #third last memberprint(text1[-1]) #last memberprint(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 12print(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 lowefor 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 hastxt3="Go OD mOrN I n g    "count=0for i in txt3:    if i.isspace():        count+=1print("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 numbermarks = input("Enter username: ")if marks.isalnum():    print("Username accepted")else:    print("Invalid username")######### 28 DEC 2022 -  LIST#Listl1 = [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 listval = [10,20,30]val.append(40)val[0] = 100print(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 indexprint(val)val.remove(200)print(val)val1 = [6,12,18,24]val2 = val+val1print(val2)val.extend(val1)  # val = val + val1print(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, 12for 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 avgmaster_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:        breakprint("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       DhoniEnglishHindiMathsScienceSocial'''print(end="\t\t")for i in range(len(students)):    print(students[i],end="\t\t")print()#col_ind = 0for 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: 2022Month: 12Date: 19Output: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]+' '+yearprint(result)# Tuple#Same as list - linear but difference is its immutablet1 = (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 versat1 = list(t1)print(type(t1))t1 = tuple(t1)t1 = ()t1 = (1,)print(type(t1))t1 = (1,2,3,4,5)  #packinga,b,c,d,e = t1  #unpackingval1 = (3,4,6)val2 = (3,1,88)#packing and unpacking#Dictionarydetails = {  "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 avgmaster_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:        breakprint("All information: \n",master_list)t1 = (2,4,6,8)print(t1)t1=list(t1)t1.append(10)t1 = tuple(t1)print(t1)# Dictionarydict1 = {"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 valuedict1 = boysprint(dict1)#copy - creates duplicate copyplayers = 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 Pset1 = {"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 THEORYset1 = {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 valuesprint(set1|set2)print(set1.union(set2))#INTERSECTIONprint(set1 & set2)print(set1.intersection(set2))#DIFFERENCEprint(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 functionsdef 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+cdef 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)  #keywordl1 = [2,4,6]putput = l1.append(8)print(putput)print(l1)#1 required positional argumentprint(myfunction1.__doc__)import randomword_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")        breakdef 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 list1def checkPrime(num):    isPrime = True    for i in range(2,num):        if num%i==0:            isPrime = False    return isPrimedef 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_factorsdef 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_fibodef 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")`
##### 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’

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

### Day 21 - Watch the video here

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

Step 2: Install IDE

Step 3: Start Basic Programming

### DAY 23 VIDEO HERE

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 - argumentsname1 = '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 = 51breadth = 23area = length * breadthperimeter = 2 * (length + breadth)#A rectangle with length x and breadth y has area of a and perimeter of pprint('A rectangle with length',length,"and breadth",breadth,"has area of",area,"and perimeter of",perimeter)# format string - f stringprint(f"A rectangle with length {length} and breadth {breadth} has area of {area} and perimeter of {perimeter}")name1 = 'Laxman'  # str - stringprint(type(name1))length = 51   #  int - integer: -999, -88,0,9,100print(type(length))avg = 55.63   #float - 5.1, -6.9, 0.0, 5.0print(type(avg))isRight = True # False : bool - boolean True/Falseprint(type(isRight))num_val = 6j # j is the imaginary value (complex) - square root of -1print(type(num_val))  #complexlength = 53print(length)length = Trueprint(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 = 500print("Val1 is ",type(val1))val1 = str(val1)  # val1 = "500"print("Val1 is ",type(val1))val2 = "55A"val2 = int(val2)`

### DAY 24 : WATCH VIDEO HERE

`#arithmetic operations:  +  -  *  /  //  **  %val1 = 20val2 = 8print(val1 + val2)print(val1 - val2)print(val1 * val2)print(val1 / val2)print(val1 // val2)  # // just the integerprint(val1 ** val2) #power(val1, val2)print(val1 % val2)  ##comparison operators: Output is always boolean - True / Falseval1 = 20val2 = 8val3 = 20  # 20 should be assigned to val3# = assignment operator -assigning the valueprint(val1 == val2) # is val1 equal to val2 ?print(val1 != val3) # is val1 not equal to val3 ?print(val1 > val2) # Tprint(val1 >= val3)  # is Val1 greater or equal to val3print(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 battingprint(True and True)print(False and True)print(True and False)print(False and False)val1,val2,val3 = 20, 8, 20print(val2 == val3 and val1 <=val2 and val3 >=val1 and val2==val3)# F# or - even if one value is TRUE entire result will be Trueprint(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)# Tprint(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) /2aa,b,c = 6, -17, 12d = b**2 - 4*a*csol1 = (-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 + ccheck2 = a*sol2**2 + b*sol2 + cprint(f"Checking if both the check are zero: {check1} and {check2}")`

### Watch Day 25 Video Here

`#Conditionsavg = 30if 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")#Conditionsavg = 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, zero2. If positive then check for Odd or Even3. If positive check for if its divisible by 2 and 34. If its divisible by both 2 and 3 then check for 5 also'''num = 30  # 0  -10   10  9if 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 >=6a,b,c = 80,60,40if 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,3for 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 = 0for i in range(1,11):    print(i,end=", ")    sum = sum+iprint("\nSum of the values = ",sum)val = 1sum = 0while val <=10:    print(val)    sum += val    val+=1 #val=val+1print("Sum = ",sum)n=5for 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 avgnum = int(input("Enter length: "))print("num = ",num)print("type of num = ",type(num))sum=0for i in range(5):    marks = int(input("Enter the marks in subject "+str(i+1)+": "))    sum+=marksprint(f"The total marks is {sum} and average is {sum/5}")`

`### WHILEimport randomnumber = random.randint(1,100)attempt = 0ch = input("Do you want to play this game? (y for yes): ")low = 1high = 100while 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-1print("Thank you")'''take 2 numbers and perform operation based on given choice:1. To add2. To multiply3. Divide4. 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!")#stringsstr1 = 'Hello'str2 = "Hi"str3 = '''How are youWhere are you'''str4 = """I am fineI am here"""print(type(str1),type(str2),type(str3),type(str4))print(str3)print(len(str3))  #size - total characters in a stringprint(str1+" "+(str3 +"\n")*3)for i in str1:    print(i)for i in range(len(str1)):    print(str1[i])str1 = "Hello" #indexing starts from zeroprint(str1[0])print(str1[2])print(str1[4])  #last elementprint(str1[-1])  #last elementprint(str1[-3])  #3rd last elementprint(str1[1:4])  #start is inclusive /end is exclusiveprint(str1[:4])print(str1[:])print(str1[-4:-1])  #start is inclusive /end is exclusiveprint(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 Methodsstr2 = "HELLO HOW ARE YOU"print(str2.isupper())print(str1.istitle())  #first character of every word needs to be capitallength = input("Enter the length: ")if length.isdigit():    length = int(length)else:    print("Invalid length value, exiting the program")#username can have only characters and numbersusername = 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 spacename = input("Enter your name")isValid = Truefor ch in name:    if ch.isalpha() or ch.isspace():        pass    else:        isValid = False        breakif 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 capsprint(str1.title())  #first letter of every word is capssplit_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 possiblestr2 = "h"+str2[1:]print(str2)print(str2.count("ou",4,10))print(str2.find("ou",10,22))`

### Day 29 Video

DAY 29 – DECEMBER 22 2022

`#LISTl1 = [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 endl2.insert(1,50)  #index, valuel2.pop(0) #remove element at the given indexl2.remove(30) #delete the given valuel2[1] = 70print(l2)l3 = l2  #both are pointing to same list - Deep copyl4 = l2.copy()  #Shallow copyprint("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 + l3l2.extend(l2+l3)print(l2)print(l2.index(50))  #index of the first matching valueind = 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:        breakprint("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 subjectfor 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 collectiont1 = ()t1 = (5,)t1 = (5,6,7)print(type(t1))t1 = list(t1)t1.append(8)t1 = tuple(t1)#packing & unpackinga,b,c,d = t1print(a)print(t1[0])print(16 in t1)a = (2,99,15)b = (2,99,15)#Dictionary - non-linear unordered mutable collectiond1 = {}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 valuesprint(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 createdd3 = d1.copy()  # at this point they are copyt2= {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 = 0while 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:        breakprint("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`

## Day 31 : Tuple and Dictionary Tutorial

`#SETset1 = {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 elementsprint(set1 | set2)   #min - # of the elements in bigger setprint(set1.intersection(set2))  #max: size of lower setprint(set1 & set2)    #min : no elements repeated#if no elements are repeated we call them disjoint setseta={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 setbprint(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()`

## DAY 32 A - SETS Tutorial3

`# 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 argumentsdef 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+bmyquestions()result = myadd(55,65) #passing the parameter to the function definitionprint(result)myadd2(55,35)myadd2(55)myadd2()#keywords = removes restriction of positionala=5b=6myadd(b=b,a=a)  #not being positional - keyword#required  positional default  keyword#global and local scope of variabledef 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 variableprint("printing in main a =",a)mytest()`

## DAY 32 - Functions in Python Tutorial - 1

`#Functions#DocString - are multi line comments added as first line in function definitiondef 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 resultdef 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 resultdef 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 functionsout1 = p1.myfun2(b=10,a=20)print(out1)out1 = p1.myfun1(10,20)print(out1)#annoynomous or oneline or lambdalf1 = lambda x,y:x+yprint(lf1(10,90))# recursion - function calling itselfdef myfun_facto(n):    if n==0:        return 1    return n * myfun_facto(n-1)  #stackprint(myfun_facto(5))# 5! = 5 * 4 * 3 * 2 * 1# 5! = 5 * 4!`

## DAY 33 B - Complete Function Tutorial

`#Class & Objectclass 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)`

## DAY 34 - CLASS & OBJECTS SESSION 1 VIDEO

`#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 classfrom abc import ABCMeta, abstractmethodclass 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()`

### DAY 35 - ACCESS VIDEO HERE

`import sqlite3con_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)#updateupdate_q = '''Update Students set fees=110 where roll=1003'''con_str.execute(update_q)con_str.commit()#Deletedelete_q = '''Delete from Students where roll=1004'''con_str.execute(delete_q)##insert based on user inputroll_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 StarHow I wonder what you are'''if file_con.writable():    file_con.write(content)`

## DAY 36 VIDEO Recording

`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 - jsonjson_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()#####  Exceptionsprint("Hello")print(5-3)#runtime errors - Exceptionstry:    num1 = int(input("Enter a number: "))  # ValueError exception    50 / 0  # ZeroDivisionError exceptionexcept 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`

## Day 40 Video

`import numpy as npx = range(16)  #0...15x=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 multiplicationprint(x@y)  #matrix multiplicationprint(x/y)### Pandasimport pandas as pddata = [["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)`

## DAY 41 Video Here

`import pandas as pd#you can read csv files using read_csv irrepective of the locationusage_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 datasetsresult_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 pdhotel_df = pd.read_csv("C:/Users/Hp/Downloads/Dataset-master/Dataset-master/hotel_bookings.csv")print(hotel_df)import matplotlib.pyplot as pltimport seaborn as snsplt.style.use('ggplot')cols = hotel_df.columns[:30]colors = ["#085838","#f4deb4"]sns.heatmap(hotel_df[cols].isnull(), cmap=sns.color_palette(colors))plt.show()`

## DAY 42 VIDEO HERE

`import pandas as pdhotel_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 nullimport matplotlib.pyplot as pltimport seaborn as snscols = 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 missinghotel_df = hotel_df.drop(['company'],axis=1) #axis=1 for column#check % missingimport numpy as npfor  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 rowfor  col in hotel_df.columns:    missing = hotel_df[col].isnull()    num_missing = np.sum(missing)    if num_missing>0:        hotel_df[f'{col}_ismissing'] =missingismissing_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 valueshotel_df=hotel_df.drop(ind_missing,axis=0) #axis=0 for rows#check again after rows and col dropimport numpy as npfor  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 valuesfor 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")`

## DAY 46 - Day 2 of Tableau

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

3. Merge the data

4. Now prepare viz

## DAY 58: DATA WAREHOUSING- SESSION 2

##### Quest Learning DS December 2022

Day 1:

`a=5#data type is integerprint(a)print(type(a))a='''hellohow are youI am fine'''#type is stringprint(a)print(type(a))a="""hello"""#type is stringprint(a)print(type(a))a=5.0print(a)print(type(a))a = True  #Falseprint(a)print(type(a))a=5jprint(a);print(type(a));print(a*a)print("How are you?",end=" -> ")print("I am doing good.")quant = 40price = 10total_cost = quant * priceprint("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 = 50breadth = 20area = 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 = 10b = 3print(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 valuea=10b=3print(a==b) #Fprint(a!=b)  #Tprint(a > b)print(a>=b)print(a<=b)print(a<b)## Logical:  and or  nota = 10b = 3print(a >b and b !=a)  # T and T = Tprint( 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=23print(bin(a))  #bin - converts  to binary( 0b)  oct - octal  0c  hex - hexadecimal  0xprint(hex(a))print("23 >> 1: ",23 >> 1)  #bitwise: right shiftprint("23 >> 2: ",23 >> 2)  #bitwise: right shiftprint(23 << 2)  #bitwise: left shiftprint(int(0b1011))#  10111.   1011print(" & : ",23 & 12)# 1 0 1 1 1# 0 1 1 0 0#&#--------------# 0 0 1 0 0# 1 1 1 1 1print(" | : ",23|     12)a=-5if a < 0:    print()    print()    print()    b = 6+4    print(b)print("Thank you 1")a = -5if a<0:    print("This is a negative number")else:    print("This is not a negative number")a=0if a<0:    print("Negative number")elif a>0:    print("Positive number")else:    print("Zero value")`

`number = 6if 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,2for i in range(3):    print(i)# While Loopch="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 userprint(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+marks3print("Total marks obtained is ",sum)avg = sum/3print(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+marks3print("Total marks obtained is ",sum)avg = sum/3print(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 Failif avg >=40:    print("Result: PASS")else:   #default condition , executed only when if is false    print("Result: FAIL")'''80 to 100: Grade A  - IF70 to 80: Grade B   - ELIF60 to 70: Grade C   - ELIF50 to 60: Grade D   - ELIF40 to 50: Grade E   - ELIF<40: Grade F   - ELSE'''#avg = 90if 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 = 11if 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 = 5if 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 numbersfor 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 = -11while counter <=10:    print(counter)    counter+= 1   #  a = a X  5   =>  a X= 5# Sum of first 10 natural numberssum=0for i in range(1,11):    sum+=i  # sum = sum + iprint("Sum from For loop: ",sum)# Sum of first 10 natural numberssum=0counter = 1while counter <=10:    sum+=counter    counter+=1print("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)`
`#Listlist1 = [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 removel1.remove(19)  #value to removeprint(l1)l1[1] = 18print(l1)l11 = l1l21 = 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+l2print(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 = t1t1 = (3,)print(type(t1))t1 = (3)print(type(t1))dict1 = {55:"Sachin", "Name": "Cricket"}`
`word = "hello"guess = "ll"ind = 0word1 = word.replace("l","L",1)print(word1)for i in range(word.count(guess)):    ind = word.find(guess,ind)    print(ind)    ind=ind+1word3 = "How are you doing"l1 = word3.split("o")print(l1)word4 = "o".join(l1)print(word4)#Stringsword = "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")#Listl1 = [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 positionl1.remove(6.5) #valuel2 = l1l3 = l1.copyprint("Set 1: ")print("l1 : ",l1)print("l2 : ",l2)print("l3 : ",l3)print("Set 2: ")print("l1 : ",l1)print("l2 : ",l2)print("l3 : ",l3)print("######")'''2212202222nd 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_userprint(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 mutablemain_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_dictmain_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)#keysfor i in main_dict.keys():    print(i)#valuesfor i in main_dict.values():    print(i)#itemsfor i,j in main_dict.items():    print(i," : ",j)`
`# List functions### MAPlist1 = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29]#find cube of all these valuesresult = list(map(lambda x:x**3,list1))print("Result = ",result)### FILTERresult = filter(lambda x:x>=15,list1)print("Filtered values: ",list(result))### REDUCEfrom functools import reduceresult = 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 outsideimport sqlite3con_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=10b=10c =a/bprint("A/B = ",c)  #ZeroDivisionError: division by zeronum1 = 0num2 = 0try:    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'`