LGS
(Edited 4 Aug)
Introduction To Python.txt
Introduction to Python Python is a widely used general-purpose, high-level programming language. It was created by Guido van Rossum, and released in 1991. It is used as a support language for software developers. Python ranks among the most popular and fastest-growing languages in the world. World's biggest app "Instagram" uses Python on its backend. Uber also uses Python somewhere as its backend language. Python is popular because: 1. Emphasis is on code readability, shorter codes, and ease of writing. 2. Closer to the English language and easy to Learn. 3. Inbuilt functions for almost all of the frequently used concepts. 4. Logical concepts are expressed in fewer lines of code in comparison to other languages such as C++ or Java. Python is an interpreted language and a python interpreter is a program that knows how to execute a python code, it converts the code written in Python into a language that our computer can understand. # Uses: 1. It is used to build web applications. 2. It provides GUI library to develop a user interface, ex - Tkinter, PyQt, etc. 3. It is used in software development. 4. It is used in Business Applications, ex- E-commerce. 5. Image Processing Applications. 6. Game Development. 7. Artificial Intelligence and Machine Learning. # Features : 1. It is a case-sensitive language. 2. Indentations are used. 3. Variables are used without declaration. 4. It is a dynamically typed language. 5. It consists of a large library, etc. # IDLE (Integrated Development and Learning Environment) Python- It is a code editor which allows the user to write and execute a python program. It provides two window options: 1. Interpreter Window: It allows us to enter commands directly into python. On pressing enter, python will execute it and display the result. (Print function is not required) 2. Program Window: This window is purely for commands to be given. Programs are written , comments can be given and print statement is used to obtain result/output.
theVeryBasics.py
#Output Function:
#print('Hello World')
#comments are identified by a # symbol
#comments are written by a programmer to write his thought
#process while writing the code
#indentation
#it refers to adding whitespaces at the beginning of a statement.
#-----------------------------------------------------------------
# -------end-------
#end = "" is used to add two strings
print("Hello World", end=" ")
print("it's a Lovely day !")
#---------------------------------------------------------------
# Escape Sequence Characters:
#An escape character is a backslash '\' followed by any
#character needed to insert
# \n - newline character
# \t - tab
# \' - single quote
# \" - double quotes
# \\ - backslash
# print('Hello \nWorld')
# print('hello\tWorld')
# print('Father\'s name')
# print("\"All\'s well that ends well\"")
# print('This inserts a backslash\\ in a string')25 Jul
home.py
name = "xyz" age = 12 ##print(name) ##print(age) name1 = input("please enter your name: ") age = input("enter age: ") ##print("the name is", name1, "and the age is", age) # format method: print("the name is {} and the age is {}".format(name1,age)) # formatted string: print(f"the name is {name} and the age is {age}")theBasicFunctions.py#Raw String: ##Raw string are used to write something as it is. ##it doesn't escape any character and treats single backslash as ##literal character. ##print(r'Hello \nWorld') ##print(r'hello\tWorld') ##print(r'"\"All\'s well that ends well\""') #---------input() Function------------------------------ ##In Python, you can take input from the user using the input() ##function. ##userInput = input('enter something:' ) ##print(userInput) ## ##name = input('enter your name: ') ##print('Hello' ,name) ##---------type() Function ------------------------ ##In Python, The type() function is used to check the type of an object. # a = 'orange' # print(type(a)) # b = '12' # print(type(b)) # c = 3 # print(type(c)) # d = 3.2 # print(type(d)) # e = 'true' # print(type(e)) # f = True # print(type(f)) # ------------- Format() Method ------------- ##In Python, the format() method is used to create formatted strings. ##It helps you build strings where you can insert values or ##variables in specific positions within the string. ##name = 'xyz' ##Hobby = 'Programming' ## ##print('My Name is {}, My Hobby is {}.'.format(name,Hobby)) ##userName = input('enter your name: ') ##age = input('enter your age: ') ##print('My name is {}, I am {} years old.'.format(userName,age)) ##---------formatted string------------ ##print(f'My Name is {name}, My Hobby is {Hobby}.') ##print(f'I am {userName} and i am {age} years old.')28 JularithmeticOperators.py#Arithmetic Operators in Python: print(2+2) print(2-2) print(5*2) x = 20 y = 2 print("addition: ",x+y) print("subtraction: ",x-y) print("multiplication: ",x*y) print("division: ",x/y) # normal division in python #------------------------------------------------------------- # modulo (%): # modulo gives you the remainder. print("remainder: ",x%y) #------------------------------------------------------------- # floor divison in python(//): # floor gives you the quotient. print("quotient", 11//3) #-------------------------------------------------------------- # Comparison operators in Python: # > greater than operator # < less than operator # >= greater than equal to # <= less thaneq ual to # == equal to operator # != not equal to operator a = 10 b = 6 print(a>b) print(a<b) print(a>=b) print(a<=b) print(a==b) print(a!=b) print(a==10) #------------------------------------------------------------ ## raise to the power: print(2**2) # prints the square of a number print(2**3) # prints the cube of a number29 JullogicalOperators.py#--------------Logical Operators----------------------- #--------and -------------- #returns True if both statements are true ##x = 6 ##y = 7 ##if (x == 6 and y == 7): ## print("yes") #--------or---------------- #returns True if one of the statements is true ##x = 6 ##y = 7 ##if (x == 6 or y == 5): ## print("yes") #--------not--------------- #reverse the result, returns False if the result is true a = 2 b = 4 ##print(not a == 2) ##print(a==2 and b==5) ##print(not(a==2 and b==5))join_split.py#------------------------------- Split() Function ---------------------------- splits a string into a list based on the separator given : newStr = 'have a beautiful day !' print(newStr.split()) variable = 'apple,mango,papaya' print(variable.split(",")) variable_2 = 'monkey#horse#cat#dog' print(variable_2.split("#")) #-------------------------------- Join() Function ---------------------------------- converts a list into a string : alist = [ 'a', 'b', 'c', 'd', 'e' ] a = ",".join(alist) print(a) alist = [ 'a', 'b', 'c', 'd', 'e' ] a = "#".join(alist) print(a) mySeparator = "HELLO" b = mySeparator.join(alist) print(b)If-else.py############### if-else statements ############### #These are decision making statements #Used to execute a block of code #if a condition is true, if part is executed #if a condition is false, else part is executed #if a user wants to check multiple conditions, #if-elif-else ladder is used #elif is executed only when the condition passed in if block is false ##num1 = int(input("Enter a number : ")) ##if num1>10: ## print("Greater than 10") ##elif num1==10: ## print("Number is 10") ##else: ## print("Less than 10") ##num1 = int(input('enter a number')) ##num2 = int(input('enter another number')) ##if num1>num2: ## print(f'{num1} is greater than {num2}') ##elif num1<num2: ## print(f'{num2} is greater than {num1}') ##else: ## print(f'{num1} and {num2} are equal') #--------------------------------------------------------- ##num = 9 ##if num%2 == 0: ## print(f"{num} is an even number.") ##else: ## print(f"{num} isn't an even number.") #--------------------------------------------------------- ##age = int(input("enter your age: ")) ##if age>= 18: ## print("eligable to vote") ##else: ## print("not eligable to vote") #--------------------------------------------------------- #to check whether a user input is positive, negative or zero ##x = int(input("Enter a number : ")) ##if (x>0): ## print("Number is Positive") ##elif (x==0): ## print("Number is Zero") ##else: ## print("Number is Negative")home.py##name = "xyz" ##age = 12 ## ## ##print(name) ##print(age) ##name1 = input("please enter your name: ") ##age = input("enter age: ") ##print(name1) ##print(age) ##print("the name is {} and the age is {}".format(name1,age)) ## ##print(f"the name is {name} and the age is {age}") ##Twinkle, twinkle, little star, ## How I wonder what you are! ## Up above the world so high, ## Like a diamond in the sky. ##Twinkle, twinkle, little star, ## How I wonder what you are! name = "hjhjkhhj" ##print(len(name)) ##print(2+2) ##print(8-2) ##print(2*5) ##x = int(input("enter a number: ")) ##y = int(input("enter another number: ")) ## ##print(x+y) ##print(2**3) ##print(2*2*2) x= 2 y = 6 ##print(x>=y) ##print(y>=x) ## ##print(not x==2) ##print(x!=2) ##print(x==2 or y==6) ##a = "apple" ## ##print(a.upper()) ## ##b = "BANANA" ## ##print(b.lower()) ## ##c = "Hello" ## ##print(c.lower()) ##newStr = 'have a beautiful day !' ##print(newStr.split()) ##variable_2 = 'monkey#horse#cat#dog' ##print(variable_2.split("#")) alist = [ 'a', 'b', 'c', 'd', 'e' ] ##a = "#".join(alist) ##print(a) ##print(type(a)) ##myOwnSeparator = "Mariya" ##new = myOwnSeparator.join(alist) ##print(new) num = 10 ##if num>=10: ## print("num is greater than 10") ##else: ## print("number is smaller than 10") #to check whether a user input is positive, negative or zero ##x = int(input("Enter a number : ")) ##if (x>0): ## print("Number is Positive") ##elif (x==0): ## print("Number is Zero") ##else: ## print("Number is Negative") x = int(input("enter a number: ")) y = int(input("enter another number: ")) operator = input("enter an operator: ") if operator == '+': print(x+y) elif operator == '-': print(x-y) elif operator == '*': print(x*y) elif operator == '/': print(x/y) else: print("invalid operator")home.py##name = "xyz" ##age = 12 ## ## ##print(name) ##print(age) ##name1 = input("please enter your name: ") ##age = input("enter age: ") ##print(name1) ##print(age) ##print("the name is {} and the age is {}".format(name1,age)) ## ##print(f"the name is {name} and the age is {age}") ##Twinkle, twinkle, little star, ## How I wonder what you are! ## Up above the world so high, ## Like a diamond in the sky. ##Twinkle, twinkle, little star, ## How I wonder what you are! name = "hjhjkhhj" ##print(len(name)) ##print(2+2) ##print(8-2) ##print(2*5) ##x = int(input("enter a number: ")) ##y = int(input("enter another number: ")) ## ##print(x+y) ##print(2**3) ##print(2*2*2) x= 2 y = 6 ##print(x>=y) ##print(y>=x) ## ##print(not x==2) ##print(x!=2) ##print(x==2 or y==6) ##a = "apple" ## ##print(a.upper()) ## ##b = "BANANA" ## ##print(b.lower()) ## ##c = "Hello" ## ##print(c.lower()) ##newStr = 'have a beautiful day !' ##print(newStr.split()) ##variable_2 = 'monkey#horse#cat#dog' ##print(variable_2.split("#")) alist = [ 'a', 'b', 'c', 'd', 'e' ] ##a = "#".join(alist) ##print(a) ##print(type(a)) ##myOwnSeparator = "Mariya" ##new = myOwnSeparator.join(alist) ##print(new) num = 10 ##if num>=10: ## print("num is greater than 10") ##else: ## print("number is smaller than 10") #to check whether a user input is positive, negative or zero ##x = int(input("Enter a number : ")) ##if (x>0): ## print("Number is Positive") ##elif (x==0): ## print("Number is Zero") ##else: ## print("Number is Negative") #--- Creating a Calculator using If else Statements in Python: --- ##x = int(input("enter a number: ")) ##y = int(input("enter another number: ")) ##operator = input("enter an operator: ") ## ##if operator == '+': ## print(x+y) ## ##elif operator == '-': ## print(x-y) ## ##elif operator == '*': ## print(x*y) ##elif operator == '/': ## print(x/y) ## ##else: ## print("invalid operator") #---------------------------------------------------------------------------------------- first_name = "xyz" last_name = "khan" ##print(first_name + " " + last_name) ##string = "January" ##print(string[2]) ##x = 5 ##str(x) ##string = " ava " ##print(string.strip()) ##string = ",,...hgjh ava ..." ##string_2 = string.strip(",.hgj ") ##print(string) ##print(string_2) ##name = "Mariya Khan" ####print(name) ##newName = (name.replace("Mariya", "Ibrahim")) ##print(name) ##print(newName) ##newStr = "papaya papaya banana papaya orange orange" ## ##print(newStr.count('papaya')) ##print(newStr.count('orange')) ##print(newStr.count('a')) ##print(newStr.count(" "))stringMethods.py# strip function is used to remove any whitespace from the starting # and from the ending of a string: string = " ava " ##print(string.strip()) # strip can also be used to remove a specific characters if mentioned # specified in the code: string_1 = " ,,,!!!.... ava ....,,ttt" ##print(string.strip(" ,.!t")) #-------------------- Replace Function ------------------------ ##name = "Ravi Kumar" ##newName = name.replace("Kumar","Shankar") ##print(name) ##print(newName) #-------------------- Count Function -------------------------- # counts the accurance of a substring: newStr = "papaya papaya banana papaya orange orange" ##print(newStr.count('papaya')) ##print(newStr.count('orange')) ##print(newStr.count('banana')) #-------------------- startswith() Method -------------------- # The startswith() method checks if a string starts with specified #pattern or not. # if it does, it returns True, otherwise returns False. string_1 = "Hello World!" print(string_1.startswith('Hello')) print(string_1.startswith('H')) print(string_1.startswith('He')) print(string_1.startswith('Hello')) print(string_1.startswith('Hi')) #--------------------- endswith() Method --------------------- print(string_1.endswith('Hello')) print(string_1.endswith('!')) print(string_1.endswith('He')) print(string_1.endswith('World')) print(string_1.endswith('World!')) #--------------------- title() Method ------------------------ # The title() method converts the first letter of each word in a #string to uppercase and the rest to lowercase. a = "hello world" b = a.title() print(a) print(b)home.py##name = "xyz" ##age = 12 ## ## ##print(name) ##print(age) ##name1 = input("please enter your name: ") ##age = input("enter age: ") ##print(name1) ##print(age) ##print("the name is {} and the age is {}".format(name1,age)) ## ##print(f"the name is {name} and the age is {age}") ##Twinkle, twinkle, little star, ## How I wonder what you are! ## Up above the world so high, ## Like a diamond in the sky. ##Twinkle, twinkle, little star, ## How I wonder what you are! name = "hjhjkhhj" ##print(len(name)) ##print(2+2) ##print(8-2) ##print(2*5) ##x = int(input("enter a number: ")) ##y = int(input("enter another number: ")) ## ##print(x+y) ##print(2**3) ##print(2*2*2) x= 2 y = 6 ##print(x>=y) ##print(y>=x) ## ##print(not x==2) ##print(x!=2) ##print(x==2 or y==6) ##a = "apple" ## ##print(a.upper()) ## ##b = "BANANA" ## ##print(b.lower()) ## ##c = "Hello" ## ##print(c.lower()) ##newStr = 'have a beautiful day !' ##print(newStr.split()) ##variable_2 = 'monkey#horse#cat#dog' ##print(variable_2.split("#")) alist = [ 'a', 'b', 'c', 'd', 'e' ] ##a = "#".join(alist) ##print(a) ##print(type(a)) ##myOwnSeparator = "Mariya" ##new = myOwnSeparator.join(alist) ##print(new) num = 10 ##if num>=10: ## print("num is greater than 10") ##else: ## print("number is smaller than 10") #to check whether a user input is positive, negative or zero ##x = int(input("Enter a number : ")) ##if (x>0): ## print("Number is Positive") ##elif (x==0): ## print("Number is Zero") ##else: ## print("Number is Negative") #--- Creating a Calculator using If else Statements in Python: --- ##x = int(input("enter a number: ")) ##y = int(input("enter another number: ")) ##operator = input("enter an operator: ") ## ##if operator == '+': ## print(x+y) ## ##elif operator == '-': ## print(x-y) ## ##elif operator == '*': ## print(x*y) ##elif operator == '/': ## print(x/y) ## ##else: ## print("invalid operator") #---------------------------------------------------------------------------------------- first_name = "xyz" last_name = "khan" ##print(first_name + " " + last_name) ##string = "January" ##print(string[2]) ##x = 5 ##str(x) ##string = " ava " ##print(string.strip()) ##string = ",,...hgjh ava ..." ##string_2 = string.strip(",.hgj ") ##print(string) ##print(string_2) ##name = "Mariya Khan" ####print(name) ##newName = (name.replace("Mariya", "Ibrahim")) ##print(name) ##print(newName) ##newStr = "papaya papaya banana papaya orange orange" ## ##print(newStr.count('papaya')) ##print(newStr.count('orange')) ##print(newStr.count('a')) ##print(newStr.count(" ")) ##stri = " ,, ava ," ##print(stri.strip(" ,")) #### ##stri = " ,, ava ,.! " ##stri = stri.replace(",", "").replace(".","").replace("!","") ####stri = stri.strip() ##print(stri) ##name = "Ravi Kumar" ##newName = name.replace("Kumar","Shankar") ##print(name) ##print(newName) ## ## ##newStr = "papaya papaya banana papaya orange orange" ## ##print(newStr.count('papaya')) ##print(newStr.count('orange')) ##print(newStr.count('banana')) ## ##string_1 = "Hello World!" ##print(string_1.startswith('Hello')) ##print(string_1.startswith('H')) ##print(string_1.startswith('He')) ##print(string_1.startswith('Hello')) ##print(string_1.startswith('Hi')) ## ##print(string_1.endswith('Hello')) ##print(string_1.endswith('!')) ##print(string_1.endswith('He')) ##print(string_1.endswith('World')) ##print(string_1.endswith('World!')) ## a = "hello world" b = a.title() ##print(a) ##print(b) ##num1 = int(input('enter a number: ')) ##num2 = int(input('enter a number: ')) ##num3 = int(input('enter a number: ')) ## ##if num1>num2 and num1>num3: ## print(f"{num1} is the greatest number.") ## ##elif num2>num1 and num2>num3: ## print(f"{num2} is the greatest number.") ## ##else: ## print(f"{num3} is the greatest number.") li = [1,2,3,'a','b','c','true','1'] ## ##print(type(li)) ##print(len(li)) ##print(li[3]) ##print(li[6]) ##print(type(li[6])) ##print(type(li[7])) ##blist = list(range(1,21,2)) ##print(blist) animals = ['cat','dog','giraffe','peacock','fish'] print(animals[0]*5) print(animals[3]*4)list.py#List in python: #In Python, lists are used to store multiple items in a single variable. #list items are indexed hence, ordered. #lists are mutable, #and allows duplicate values. #by default 1st item in a list has 0th index #lists in python are created using square [] brackets. #a list can contain different data types at the same time. ##li = [1,2,3,4,5] ##print(li) ##print(len(li)) ##fruits = ['apple','oranges','banana','mangoes','papaya'] ##print(fruits) ##print(fruits[4]) #printing an element using it's index value ##print(len(fruits)) ##print(type(fruits)) #a list containing different data types : ##alist = ['12',12,'apple',2.3,'60','fifteen',False] ##print(alist[2]) ##print(type(alist)) ##print(type(alist[2])) ##print(type(alist[6])) #----------------------------------------------------------------- #----range Function---------------------------------- #You can use range to generate a sequence of numbers and convert it #to a list. This is useful when you need a list of consecutive #numbers. ##newList = list(range(5)) ##print(newList) ## output = [0, 1, 2, 3, 4] ##alist = list(range(1,10)) ##print(alist) ##output = [1, 2, 3, 4, 5, 6, 7, 8, 9] ##blist = list(range(1,21,2)) # the 2 in the last will skip one element after ##print(blist) # each element. ##output =[1, 3, 5, 7, 9, 11, 13, 15, 17, 19] ##clist = list(range(1,21,3)) # the 3 in last will skip two elements. ##print(clist) #-------Combining two lists----------------------------- a = ['Hello',12,'15',True,5.5,3] ##b = [1,2,3,4,5,6,7] ## ##c = a + b ##print(c) #----- printing an element multiple times--------------- animals = ['cat','dog','giraffe','peacock','fish'] ##print(animals[0]*5) ##print(animals[3]*4) #------Counting the occurance of an element------------- fruits = ['apple','apple','apple','orange','papaya','apple'] ##print(fruits.count('apple')) ##print(fruits.count('papaya')) #-------index() method------------------------------------ ##The index() method returns the index of the first occurrence of #the specified element. ##print(fruits.index('apple')) ##print(fruits.index('orange')) #-------Use of "in" & "not in" keyword------------------------------- #In Python, you can use the in keyword to check if an element is #present in a list. ##my_list = [10, 20, 30, 40, 50] ##print(30 in my_list) # returns True ##print(35 in my_list) # returns False ##print(60 not in my_list) # returns True ##print(10 not in my_list) # returns False #-------Replacing List elements--------------------------- flowers = ['rose','marigold','daisy'] ##print(flowers) ##flowers[0] = 'lavender' ##print(flowers) output = ['lavender', 'marigold', 'daisy'] ##flowers[2] = 'Sunflower' ##print(flowers) #-------remove() method---------------------- #It is used to remove the first occurrence of a specified element #from the list. ##flowers.remove('rose') ##print(flowers) #--------pop() method ------------------------ # In Python, the pop() method is a list method used to remove and #return the last item from a list or an item at a specified index. #flowers = ['rose','marigold','daisy'] ##flowers.pop() # removes last element as index not specified. ##print(flowers) ## ##flowers.pop(1) # will remove element present on 1st index. ##print(flowers) #-------- del keyword in python--------------- ##flowers = ['rose','marigold','daisy','lavender','sunflower'] ##del flowers[2] ##print(flowers) #--------- clear() method---------------------- #In Python, the clear() method is used to remove all elements from #a list. ##flowers.clear() ##print(flowers) #--------- append() method--------------------- #In Python, the append() method is a built-in method for lists. #It is used to add an element to the end of an existing list. #the append() method modifies the original list in place and does #not return a new list. # append takes one only arguement at a time. flowers = ['rose','marigold','daisy','lavender','sunflower'] ##flowers.append('lily') ##print(flowers) ## ##flowers.append('tulip') ##print(flowers) #--------- insert() method-------------------- #It is used to insert an element at a specified position(index) #within a list. #insert() takes 2 arguments (index, element) #syntax : # insert(index, elements) ##flowers.insert(0, 'dandelion') ##print(flowers) #---------- extend() method-------------------- #In Python, the extend() method is a built-in method for lists. #It is used to append elements to the end of an existing list. flowers = ['rose','marigold','daisy','lavender','sunflower'] flowers2 = ['dandelion','jasmine','Hibiscus','Bougainvillea'] flowers.extend(flowers2) print(flowers)2 Auglist (1).py# Use of sum, max, min intList = [2,3,6,8,4,1] ##print(intList) ##print('Maximum:',max(intList)) #print maximum from the list ##print('Minimum Value:',min(intList)) #print minimum from the list ##print('Sum of all items:',sum(intList)) #add all elements of a list # ------------------- SORTING LISTS ------------------- # sort() function changes the original list ##intList.sort() ##print(intList) ##print(intList[0]) # for arranging in descending order ##intList.sort(reverse = True) ##print(intList) #----------------------------------------------------------- ##sorted() function will create a new list ## containing a sorted version of the list it is given newList = sorted(intList) ##print(newList) # descending order using sorted newList = sorted(intList, reverse = True) ##print(newList) # ------------------- REVERSE LIST ------------------- # reverse() function is used to reverse a sequence list_1 = ['apple', 'banana', 'mango', 'grapes'] ##print(list_1) ## ##list_1.reverse() ##print(list_1) ##print(list_1[0]) #------------------------------------------------------ # reversed() function reverse a copy of original sequence # and returns a reverse object ##print(reversed(list_1)) ##print(list(reversed(list_1))) list_2 = list(reversed(list_1)) print(list_2) print(list_1) #--------------------- NESTED LISTS -------------------- ##alist = [2,4,6,8] ##blist = [1,3,5,7] ##resultList = [alist, blist] ##print(resultList) ## ##print(resultList[0]) ##print(resultList[0][0]) ##print(resultList[1][2])home.py##flowers = ['rose','marigold','daisy'] ##flowers.pop(0) ##print(flowers) ##flowers = ['rose','marigold','daisy','lavender','sunflower'] ##flowers.append('lily') ##print(flowers) ## ##flowers.insert(0, 'dandelion') ##print(flowers) intList = [2,3,6,8,4,1] ##print(max(intList)) ##print(min(intList)) ##print(sum(intList)) intList = [2,3,6,8,4,1] intList.sort(reverse= True) # changes the original list ##print(intList) # sorted(): creates a copy and doesn't change the original list. ##newList = sorted(intList) ##newList1 = sorted(intList, reverse = True) ##print('original List',intList) ##print('Sorted list', newList) ##print('Reversed list', newList1) list_1 = ['apple', 'banana', 'mango', 'grapes'] list_1.reverse() # changes the original list ##print(list_1) # reversed(): creates a copy and doesn't change the original list. reversedList = list(reversed(list_1)) ##print(list_1) ##print(reversedList) ## alist = [2,4,6,8] blist = [1,3,5,7] resultList = [alist, blist] print(resultList)(Edited 2 Aug)dictionary.py# Python Dictionary : my_dict = { 'name':'Ben', 'age':'11', 'city':'New york'} ##print(my_dict) ##print(type(my_dict)) ##print(len(my_dict)) #-------printing the value on the basis of it's key:------------ ##print(my_dict['name']) ##print(my_dict['city']) #------changing the values on the basis of their keys:----------- my_dict['name'] = 'Ana' my_dict['city'] = 'New Delhi' ##print(my_dict) #------adding new key and value in a dictionary:----------------- my_dict['gender'] = 'male' ##print(my_dict) #------checking whether a key is present in a dictionary:------- ##print('name' in my_dict) #if it gives 'True' it means the key ## # is present in my_dict ## ##print('country' in my_dict) ## ### using not in for the same purpose: ## ##print('country' not in my_dict) # giving 'True' coz the statement ## #is true. country IS NOT PRESENT ## #in my_dict. ##print('city' not in my_dict) #---------------------------------------------------------------- #----------------------------------------------------------------- ## COMMON DICTIONARY METHODS IN PYTHON: #---------- use of .values() --------------------------- #prints a list of values: ##print(my_dict.values()) #---------- use of .keys() ------------------------------ #prints a list of keys: ##print(my_dict.keys())home.pyintList.sort() ##print(intList) ##intList.sort(reverse = True) ##print(intList) ## ##flowers = ['rose','marigold','daisy','lavender','sunflower'] ##flowers2 = ['dandelion','jasmine','Hibiscus','Bougainvillea'] ## ##flowers.extend(flowers2) ##print('extended_list',flowers) #### ####flowers.append(flowers2) ####print('appended_list',flowers) ## ##alist = [2,4,6,8] ##blist = [1,3,5,7] ##resultList = [alist, blist] ####print(resultList) ## ##cList = [5,6,7] ##resultList.insert(1,cList) ##print(resultList) # Dictionary in Python: newDict = { "Name":"xyz", "age": 2, "city": "Bhopal"} ##print(newDict) ##print(type(newDict)) ##print(len(newDict)) ##newDict["Name"] = "Mariya" ##print(newDict) ## ##newDict["Country"] = "India" ##print(newDict) ##print('Name' in newDict) ##print("city" not in newDict) print('Values',newDict.values()) print("Keys", newDict.keys())Assignment_1.txt4 Aughttps://www.geeksforgeeks.org/python-if-else/?authuser=0https://realpython.com/python-list/?authuser=0https://www.geeksforgeeks.org/python-dictionary/?authuser=0(Edited 7 Aug)dictionary (2).py#---------- use of .items() ---------------------------- ## items() returns a list of tuples #where each tuple is a tuple of key-value pair. ##print(my_dict.items()) ## Getting key and value separately using .items() ##for k,v in my_dict.items(): ## print(k,v) #----------- use of .clear() --------------------------- #In Python, the .clear() method is used to remove all elements #from a mutable sequence, such as a list, set, or dictionary ##my_dict.clear() ##print(my_dict) #----------- use of .pop()------------------------------ #The dict.pop() method is used to remove a key and it's value # from a dictionary. ##my_dict.pop('age') ##print(my_dict) # --------------Deleting a dictionary :------------------------ ##del(my_dict) ##print(my_dict) # ------------- .copy() :------------------------- fruits = { 1:'apple', 2:'banana', 3:'pineapple', 4:'mango', 5:'papaya'} ##print(fruits) dict2 = fruits.copy() ##print(dict2) ------------------------- NESTED DICTIONARY ----------------------- #A nested dictionary in Python is simply a dictionary that contains another dictionary as #its value. This can be useful for storing more complex data structures. pets = { "pet1": {"name": "Buddy", "type": "dog", "age": 5}, "pet2": {"name": "Mittens", "type": "cat", "age": 3}, "pet3": {"name": "Tweety", "type": "bird", "age": 2} } ##print(pets) ##print(pets["pet1"]) ##print(pets["pet1"]["age"]) pets["pet2"]["age"] = 4 print(pets)home.pymy_dict = {'name':'Ben','age':'11','city':'New york'} ##print(my_dict) di = {} # creating an empty dictionary ##print(di) ## ##print(type(my_dict)) ##print(len(my_dict)) ##print(my_dict['name']) ## ##my_dict['name'] = "Pem" ##print(my_dict) my_dict["country"] = "America" # adding a new key & value. ##print(my_dict) ##print('Name' in my_dict) ##print('country' not in my_dict) ##print(my_dict.values()) ##print(my_dict.keys()) ##print(my_dict.items()) #returns a list of tuples my_dict = {'name':'Ben','age':'11','city':'New york'} ##my_dict.clear() ##print(my_dict) my_dict.pop('age') ##print(my_dict) ##del(my_dict) ##print(my_dict) fruits = { 1:'apple', 2:'banana', 3:'pineapple', 4:'mango', 5:'papaya'} ##print(fruits) dict2 = fruits.copy() ##print(dict2) ##li = ['a','b','c','d','e'] ##li2 = [1,2,3,4,5] ## ##li3 = list(zip(li, li2)) ##print(li3) li = ['a','b','c','d','e'] ##print(enumerate(li)) # returns object ##print(list(enumerate(li)))Zip_&_Enumerate.py#----------------------- ZIP FUNCTION --------------------------- #Zip is an inbuilt function in python, used to iterate over multiple iterables. #it takes corresponding elements from all the iterables passed to it and merges them into a tuple. #returns a zip objects that can be converted into a list for better reading. syntax : zip(iterable1, iterable2, iterable3 etc) li = ['a','b','c','d','e'] li2 = [1,2,3,4,5] li3 = list(zip(li, li2)) print(li3) #--------------------- ENUMERATE FUNCTION ----------------------- li = ['a','b','c','d','e'] print(enumerate(li)) # returns an object that needs to convered can be converted into a list print(list(enumerate(li))) # to iterate over a list using enumerate function ##newList = ['rose','sunflower','lily'] ##for index,element in enumerate(newList): ## print(index,element)(Edited 6 Aug)Slicing.py#-------Slicing------------------------------------- #List slicing in Python refers to the technique of extracting a #portion of a list. It allows you to create a new list that #consists of elements from a specified range of indices. #Syntax : [start:stop:step] alist = ['Hello',12,'15',True,5.5,3] print(alist) ##print(alist[0:1]) ##print(alist[1:4]) ##print(alist[2:3]) ##print(alist[1::2]) ##print(alist[:]) ##print(alist[5:]) ##print(alist[:4]) ##print(alist[0:6:2]) ##print(alist[0:4:3]) ##print(alist[-3:-1]) ##print(alist[0:-3]) ##print(alist[0:-1:2]) #----------- String Slicing -------------------------- # String slicing in Python is a way to extract a part of a string. aString = "Have a Beautiful day!" print(aString) ##print(aString[0:4]) ##print(aString[7:16]) ##print(aString[17:20]) print(aString[-4:-1]) print(aString[0::2])home.py##Q.1 Write a program that accepts the user's first and last name and prints them in reverse ## order with a space between them. (1 marks) ##x = input("enter first name: ") ##y = input("enter last name: ") ##print(y,x) ##Q.2 Write a program to print thene sum of two user inputted numbers. (1 marks) ##x = int(input("enter a number: ")) ##y = int(input("enter a number: ")) ##z = x + y ##print(z) ##Q.3 Write a program to count the occurrence of 9 from a given list - (2 marks) ##list_1 = [2,4,6,8,9,3,5,8,9,1,5,9,3,7,2,3,9] ## ##print(list_1.count(9)) ##Q.4 Write a program to extend an existing animal list with names ##camel, rabbit, lion and zebra. ## ##li = ['dog','cat'] ##li2 = ['camel', 'rabbit', 'lion', 'zebra'] ##li.extend(li2) ##print(li) ##.5 Write a program to find the index of 'car' from a given list - (2 marks) list_2 = ['truck', 'bicycle', 'rickshaw', 'car', 'motorbike'] ## ##print(list_2.index('car')) ##Q.6 Write a program to join a list of strings - (2 marks) li = ['H','A','P','P','I','N','E','S','S'] ##X = "".join(li) ##print(X) ##Q.7 Write a program to check whether a user inputted ##number is even or odd. (2 marks) ## ##num = int(input("enter a number: ")) ## ##if (num %2 == 0): ## print("even") ## ##else: ## print("odd") ##Q.8 Write a Python program that creates a dictionary with the names of 3 students and their ## corresponding scores. Then, update the score of one student and print the updated ## dictionary. (2 marks) ##variable = { ## "name_1":18, ## "name_2":20, ## "name_3":21 ## } ## ##variable["name_1"] = 25 ##print(variable) ##Q.9 Write a program to create a calculator that performs three mathematical operations ##- Subtraction, Multiplication and Division by user inputted numbers and operator and ##returns a message for invalid operator otherwise. (3 marks) ##x = input("enter a number:") ##y = input("enter a number:") ##operator = input("enter operator:") ## ##if operator == "+": ## print(int(x)+int(y)) ##Q.10 Write a Python program that takes a user input for their ##first name and last name, and then prints a formatted string that ##displays their full name and the length of their full name ##(excluding any spaces). (3 marks) ##x = input("enter your firstname: ") ##y = input("enter your lastname: ") ## ##var = (x + y) ##z = (len(var.replace(" ",""))) ##print(f"name is {var} len is {z}") alist = ['Hello',12,'15',True,5.5,3] ##print(alist[3:4]) ## ##print(alist[0:1]) ##print(alist[1:4]) ##print(alist[2:3]) ##print(alist[1::3]) ##print(alist[:]) ##print(alist[5:]) ##print(alist[:4]) print(alist[0:6:2]) print(alist[0:4:4])https://www.freecodecamp.org/news/slicing-and-indexing-in-python/?authuser=07 Aughome.pyalist = ['Hello',12,'15',True,5.5,3] ##print(alist[-5:]) ##print(alist[3:4]) ##print(alist[-5:-1]) ##print(alist[0:-3]) ##print(alist[0:-1:2]) ##print(alist[0:1]) ##print(alist[1:4]) ##print(alist[2:3]) ##print(alist[1::3]) ##print(alist[:]) ##print(alist[5:]) ##print(alist[:4]) ##print(alist[0:6:2]) ##print(alist[0:4:4]) ##aString = "Have a Beautiful day!" ## ##print(aString) ## ####print(aString[0:4]) ####print(aString[7:16]) ####print(aString[17:20]) ####print(aString[-4:-1]) ##print(aString[0::2]) Student_data = { "Student_1" : {"Name":"xyz", "age": 18}, "Student_2" : {"Name":"abc", "age": 78}, "Student_3" : {"Name":"something", "age":20} } ##print(len(Student_data)) ##print(Student_data["Student_1"]["age"]) Student_data["Student_2"]["Name"] = "Mariya" ##print(Student_data["Student_2"]) Student_data["Student_3"]["Address"] = "Koh e fiza" ##print(Student_data) ##print(Student_data["Student_3"]) ##del Student_data["Student_3"]["Address"] ##print(Student_data["Student_3"]) ## ##print(Student_data["Student_3"].pop("Address")) ##print(Student_data["Student_3"])9 Augrevision.py##print("Hello World", end = ", ") ##print("Have a Beautiful day") ## ##print('Hello World') ##print("it\"s raining") ##print("hello world,\\\\Have a Beautiful day") ##print(r'Hello \nWorld') ##print(r'hello\tWorld') ##print(r'"\"All\'s well that ends well\""') x = 5 y = 1 ##print(x) ##print(y) ## ##name = "Mariya" ##print(name) ##variable = True ##variable2 = False ## ##print(type(name)) ##print(type(x)) ##print(type(variable)) ##name = input("what is your name: ") ##print(type(name)) ##age = input("what's your age? ") ##"my name is xyz" ##print("the name is {} and the age is {}".format(name,age)) ## ##print(f"the name is {name} and the age is {age}") ##+ - * / % // ##x = 2 ##y = 10 ##print(x + y) ##print(y - x) ##print(x * y) ##print(y / x) ## ##print(y % x) # gives remainder ##print(y // x) # give quotient ##x = 10 ##y = 20 ##print(not x>=y) ##print(not x == y) ##print(x != y) ##print(x <= y) ##print(x >= y and x <= y) ##print(not x >= y or x == y) #type conversion : ##x = int(input("enter a number: ")) ##y = int(input("enter another number: ")) ## ##print(type(x)) ##print(type(y)) ##print(x + y) # --------------- STRING FUNCTIONS ------------------ ##newStr = 'have a beautiful day !' ##print(newStr.split()) ##variable = 'apple,mango,papaya' ##print(variable.split(",")) ## ##variable_2 = 'monkey#horse#cat#dog' ##print(variable_2.split("#")) ## ##alist = [ 'a', 'b', 'c', 'd', 'e' ] ##a = "".join(alist) ##print(a) ##print(type(a)) ####print(alist) ## ##alist = [ 'a', 'b', 'c', 'd', 'e' ] ##mySeparator = "HELLO" ## ##b = mySeparator.join(alist) ##print(b) string = "apple" ##print(string.upper()) string_1 = "APPLE" ##print(string.lower()) string_2 = "Hello" ##print(string_2.swapcase()) ##string_3 = " ava " ##print(string_3.strip()) ## ##string_4 = " ,,,!!!.... ava ....,,ttt" ##print(string_4.strip(" ,.!t")) (Edited 12 Aug)revision.py##print("Hello World", end = ", ") ##print("Have a Beautiful day") ## ##print('Hello World') ##print("it\"s raining") ##print("hello world,\\\\Have a Beautiful day") ##print(r'Hello \nWorld') ##print(r'hello\tWorld') ##print(r'"\"All\'s well that ends well\""') # -------------- Variables in Python : ------------------------------ x = 5 y = 1 ##print(x) ##print(y) ## ##name = "Mariya" ##print(name) ##variable = True ##variable2 = False ## ##print(type(name)) ##print(type(x)) ##print(type(variable)) # ------------------- input() function : ------------------------------- ##name = input("what is your name: ") ##print(type(name)) ##age = input("what's your age? ") ##"my name is xyz" # --------------------- format method -------------------------------- ##print("the name is {} and the age is {}".format(name,age)) # -------------------- Formatted string, also known as f-strings :----------- ## ##print(f"the name is {name} and the age is {age}") # -------------------- Arithmetic Operators in Python: ------------------------- ##+ - * / % // ##x = 2 ##y = 10 ##print(x + y) ##print(y - x) ##print(x * y) ##print(y / x) ## ##print(y % x) # gives remainder ##print(y // x) # give quotient ##x = 10 ##y = 20 # ----------------------- The Comparison Operators : -------------------------- ##print(not x>=y) ##print(not x == y) ##print(x != y) ##print(x <= y) ##print(x >= y and x <= y) ##print(not x >= y or x == y) # -------------------- type conversion : --------------------------------------- ##x = int(input("enter a number: ")) ##y = int(input("enter another number: ")) ## ##print(type(x)) ##print(type(y)) ##print(x + y) # --------------- STRING FUNCTIONS ------------------ ##newStr = 'have a beautiful day !' ##print(newStr.split()) ##variable = 'apple,mango,papaya' ##print(variable.split(",")) ## ##variable_2 = 'monkey#horse#cat#dog' ##print(variable_2.split("#")) ## ##alist = [ 'a', 'b', 'c', 'd', 'e' ] ##a = "".join(alist) ##print(a) ##print(type(a)) ####print(alist) ## ##alist = [ 'a', 'b', 'c', 'd', 'e' ] ##mySeparator = "HELLO" ## ##b = mySeparator.join(alist) ##print(b) string = "apple" ##print(string.upper()) string_1 = "APPLE" ##print(string.lower()) string_2 = "Hello" ##print(string_2.swapcase()) ##string_3 = " ava " ##variable = (string_3.strip()) ##print(string_3) ##print(variable) ##string_4 = " ,,,!!!.... ava ....,,ttt" ##print(string_4.strip(" ,.!t")) ##name= "Mariya Khan" ##print(name.replace(" ", "")) ##print(name) ##newStr = "papaya papaya banana papaya orange orange" ## ##print(newStr.count('papaya')) ##a = "apple" ##print(a[3]) ## ##string_1 = "Hello World!" ##print(string_1.startswith(' Hello')) ##print(string_1.endswith("!")) ##a = "hello world" ##b= a.title() ##print(b) ##print(a) # ----------------- Conditional Statements in Python ------------------- ##x = int(input("enter a value: ")) ## ##if x>10: ## print("x is greater than 10") ##else: ## print("x isn't greater than 10") # ------------------------------------------------------------------------ ##if x % 2 == 0: ## print(f"{x} is an even number") ##else: ## print(f"{x} is an odd number") ##x = int(input("enter a value: ")) # ------------------------------------------------------------------------ ##if x>0: ## print(f"{x} is a positive number") ##elif x<0: ## print(f"{x} is a negative number") ##else: ## print(f"{x} is zero") # ------------------------------------------------------------------------ ##x = int(input("enter a number: ")) ##y = int(input("enter another number: ")) ##operator = input("enter an operator: ") ##if operator == '+': ## print(x+ y) ##elif operator == "-": ## print(x - y) ##elif operator == "*": ## print(x * y) ##elif operator == "/": ## print(x / y) ##else: ## print("invalid operator") # -------------------------------------------------------------------------- x = input("enter a two digit number: ") a = int(x[0]) b = int(x[1]) #print(a) #print(b) print(a + b)(Edited 13 Aug)revision.py# List in Python ##li = [1,2,3,4,5] ##print(li[1]) ##print(len(li)) ##print(type(li)) ## ##alist = ['12',12,'apple',2.3,'60','fifteen',False] ##print(type(alist[2])) newList = list(range(5)) ##print(newList) alist = list(range(2,5)) ##print(alist) ##clist = list(range(1,21,3)) a = ['Hello',12,'15',True,5.5,3] b = [1,2,3,4,5,6,7] c = a + b ##print(c) ##animals = ['cat','dog','giraffe','peacock ','fish'] ##print(animals[0]*5) ##print(animals[3]*4) ##print(animals[4]*3) fruits = ['apple','apple','apple','orange','papaya','apple'] ##print(fruits.count('apple')) ##print(fruits.count('orange')) ##print(fruits.index('apple')) ##print(fruits.index('orange')) ## ##my_list = [10, 20, 30, 40, 50] ##print(30 in my_list) ##print(35 in my_list) ##print(60 not in my_list) ##print(10 not in my_list) flowers = ['rose','marigold','daisy', 'rose'] ##print(flowers) ##flowers[0] = 'lavender' ##print(flowers) ##flowers.remove('rose') ##print(flowers) flowers = ['rose','marigold','daisy', 'rose'] ##print(flowers.pop(1)) ##print(flowers) flowers = ['rose','marigold','daisy','lavender','sunflower'] ##del flowers[2] ##print(flowers) flowers.clear() ##print(flowers) ##flowers = ['rose','marigold','daisy','lavender','sunflower'] ##flowers.append('lily') ##print(flowers) ##flowers.insert(0,'lily') ##print(flowers) flowers = ['rose','marigold','daisy','lavender','sunflower'] flowers2 = ['dandelion','jasmine','Hibiscus','Bougainvillea'] flowers.extend(flowers2) ##print(flowers) intList = [2,3,6,8,4,1] ##print(min(intList)) ##intList.sort(reverse = True) ##print(intList) ##newList = sorted(intList, reverse = True) ##print(newList) ##print(intList) list_1 = ['apple', 'banana', 'mango', 'grapes'] ##print(list_1) ##list_1.reverse() ##print(list_1) ##print(list(reversed(list_1))) ##print(list_1) ##print(list(reversed(list_1))) ##list_2 = list(reversed(list_1)) ##print(list_2) # -------------- Nested list ------------- ##alist = [2,4,6,8] ##blist = [1,3,5,7] ##resultList = [alist, blist] ####print(resultList) ## ##newList = [[2, 4, 6, 8], [1, 3, 5, 7],9,'a',[8,0,9]] ## ##print(newList[4]) # ---------------------- Dictionary : ----------------------------------- di = {} print(type(di)) di_1 = { "name" : "xyz", "age" : 20, "address" : "jgkhk" } ##print(di_1) ##print(len(di_1)) di_1["age"] = 100 print(di_1) di_1["City"] = "Bhopal" print(di_1)https://realpython.com/python-list/?authuser=014 Augrevision.py# ---------------------- Dictionary in Python : ----------------------------------- di = {} ##print(type(di)) di_1 = { "name" : "xyz", "age" : 20, "address" : "jgkhk" } ##del di_1 ##print(di_1) ##di_1.pop('age') ##print(di_1) ##print(di_1.items()) # returns a list of tuples ##print(di_1.values()) # returns values ## ##print(di_1.keys()) # returns keys ## ##print('name' in di_1) # checks whether a key is present in a dictionary or not. ## ##print('Country' not in di_1) ##di_1.clear() # removes all the elements ##print(di_1) ##fruits = { ## 1:'apple', ## 2:'banana', ## 3:'pineapple', ## 4:'mango', ## 5:'papaya'} ## ####print(fruits) ## ##dict2 = fruits.copy() ##print(dict2) # ---------------- Nested Dictionary in Python : --------------------- student_data = { "student_1" : {"name": "hello", "age" : 22}, "student_2" : {"name": "abc", "age" : 45}, "student_3" : {"name" : "xyz", "age": 26} } ##print(len(student_data)) ##print(student_data["student_2"]["age"]) ##student_data["student_1"]["age"]= 100 ##print(student_data) ##student_data["student_3"]["city"] = 'Bhopal' ##print(student_data) ##student_data["student_4"] = {"name":"xyz", "age":78} ##print(student_data) # ------------------------------------------------------------------------------------------- Teams = { "Team_A" : ["subhana", "zainab"], "Team_B" : ["shahzaib", "saad"], "Team_C" : ["mizbah", "huzaifa"] } ##print(Teams["Team_C"]) Teams["Team_B"].append("saba") ##print(Teams) Teams["Team_B"].pop() print(Teams)https://www.geeksforgeeks.org/python-dictionary/?authuser=018 Augtask.pymy_dict = { "obj_1" : "i am a dictionary", "obj_2" : {"key_1":"i am a dictionary within a dictionary"}, "obj_3" : ["apple","banana","mangoes",["papaya","orange"]], "obj_4" : {"key_2": {"Greetings":"Hello World"}}, "obj_5" : {"key_3": [1,2,3]} } # Q.1, WAP to print Hello World from obj_4 # Q.2, WAP to print Orange from obj_3 # Q.3, WAP to add 4 as a last element in the list, present inside obj_5 # Q.4, WAP to add a new key and value in your dictionary "obj_6" containg boolean values # in a list as the key's valuse. example ; {"obj_6" : [True, False]} # Q.5, replace "mangoes" from obj_3 with "kiwi"home.py#Slicing : ##alist = ['Hello',12,'15',True,5.5,3] ##print(alist[0:1]) ##print(alist[1:4]) ##print(alist[2:3]) ##print(alist[1::3]) ##print(alist[:]) ##print(alist[5:]) ##print(alist[:4]) ##print(alist[3:4]) ##print(alist[0:6:2]) ##print(alist[0:4:4]) ##print(alist[-5:]) ##print(alist[-5:-1]) ##print(alist[0:-3]) ##print(alist[0:-1:2]) ##print(alist) ##print(alist[::-1]) ##print(alist[::-2]) #------------------------------------------------------- my_dict = { "obj_1" : "i am a dictionary", "obj_2" : {"key_1":"i am a dictionary within a dictionary"}, "obj_3" : ["apple","banana","mangoes",["papaya","orange"]], "obj_4" : {"key_2": {"Greetings":"Hello World"}}, "obj_5" : {"key_3": [1,2,3]} } # Q.1, WAP to print Hello World from obj_4 ##print(my_dict["obj_4"]["key_2"]["Greetings"]) # Q.2, WAP to print Orange from obj_3 ##print(my_dict["obj_3"][3][1]) # Q.3, WAP to add 4 as a last element in the list, present inside ##obj_5 ##my_dict["obj_5"]["key_3"].append(4) ##print(my_dict) # Q.4, WAP to add a new key and value in your dictionary "obj_6" containg boolean values # in a list as the key's valuse. example ; ##{"obj_6" : [True, False]} ##my_dict["obj_6"] = [True,False] ##print(my_dict) # Q.5, replace "mangoes" from obj_3 with "kiwi" ##print(my_dict["obj_3"][2]) ##my_dict["obj_3"][2] = "kiwi" ####print(my_dict) #Q.6 ##my_dict["obj_5"]["key_3"].pop() ##print(my_dict) #---------------------------------------------------------------------------------------------------- #-------------- tuples : ---------------------- my_tuple = (1, 2, 3, 'a', 'b', 'c') ##print(my_tuple) ##print(my_tuple[0]) ##print(my_tuple[3]) ##print(my_tuple[5]) ##print(my_tuple[1:2]) ## ##print(my_tuple.index('a')) ##print(my_tuple.index(1)) ##print(my_tuple.index('c')) ##new_tup = (1) ##print(new_tup) ##print(type(new_tup)) ## ##new_tup_1 = (1,) ##print(type(new_tup_1)) tup = (2,4,5,3,1,2,7,6,2,8,2) ##print(tup) ##print(len(tup)) ## ##print(tup.count(2)) ##print(tup.count(7)) ##my_tuple = (1, 2, 3, 'a', 'b', 'c') ##tup = (2,4,5,3,1,2,7,6,2,8,2) ## ##newTuple = my_tuple + tup ##print(newTuple) alist = ['red','purple','pink','orange','yellow'] ##print(alist) ## ##tup2 = tuple(alist) ##print(tup2) string = 'it\'s a brand new day!' print(string) tup3 = tuple(string) print(tup3) tuple.py#Tuples : #In Python, a tuple is another built-in data type like list and dictionaries. #tuples are immutable. #they are ordered(Indexed)and allow duplicate values. #Tuples can contain elements of different data types, such as #integers,floats,strings,or even other tuples. #one can access individual elements of a tuple using indexing, similar to the list. my_tuple = (1, 2, 3, 'a', 'b', 'c') ##print(my_tuple) ##print(my_tuple[0]) ##print(my_tuple[3]) ##print(my_tuple[5]) ##print(my_tuple[1:2]) ##print(my_tuple.index('a')) ##print(my_tuple.index(1)) ##print(my_tuple.index('c')) #--------------------------------------------- #new_tup = (1) #print(new_tup) #print(type(new_tup)) #new_tup_1 = (1,) #print(type(new_tup_1)) #-------count() in tuple-------------------- tup = (2,4,5,3,1,2,7,6,2,8,2) ##print(tup) print(len(tup)) ##print(tup.count(2)) ##print(tup.count(7)) #-------del in tuple------------------------ ##del(tup) ##print(tup) #-------joining tuples---------------------- newTup = my_tuple + tup ##print(newTup) ##print(len(newTup)) #-------converting a list into a tuple ---------- alist = ['red','purple','pink','orange','yellow'] print(alist) tup2 = tuple(alist) print(tup2) #--------converting a string into a tuple--------- string = 'it\'s a brand new day!' print(string) tup3 = tuple(string) print(tup3)https://www.w3schools.com/Python/python_tuples.asp?authuser=020 AugSets.py# ------------------- SETS IN PYTHON ------------------- # A collection of data which is unordered. # Sets are iterable, immutable and have no duplicate elements. colors = {'red','green','orange','purple'} print(len(colors)) print(type(colors)) print("grey" in colors) # returns False, as grey is not present in colors. print("grey" not in colors) # returns True, as the statement is true. for i in colors: print(i) #-------------------------------------------------------------- x = {'hello','world',2,'5',True} # adding element to set ##x.add(10) ##print(x) # Union And Intersection of Sets: set1 = {2,3,4,5,7,8,9} set2 = {4,5,6,7} print(set1) print(set2) ##union gives you all the elements of two or more sets without any duplicates. print('Union of sets:',set1 | set2) #The intersection of sets in Python is used to find the common elements between #two or more sets print('Intersection of sets:',set1 & set2) #---------------------------------------------------------- # Subtraction of Sets print('set1-set2', set1-set2) print('set2-set1', set2-set1) # clearing sets ##set1.clear() ##print(set1) #creating an empty set: emptySet = set() print(emptySet) print(type(emptySet))task_2.pynested_dict = { 'class': { 'student': { 'name': 'John', 'marks': { 'math': 90, 'science': 85 } } } } #---------------------------------------------------------------------------------------- stu_1 = { "name": "john", "classes": [ {"class_name": "1st", "marks": [{"english": 26}, {"math": 12}]}, {"class_name": "2nd", "marks":[{"hindi": 26}, {"urdu": 12}]}, ], } stu_2 = { "name": "mark", "classes": [ {"class_name": "3rd", "marks": [{"english": 26}, {"math": 12}]}, {"class_name": "4th", "marks": [{"hindi": 26}, {"urdu": 12}]}, ], } li = [stu_1, stu_2]shallow_&_deepCopy.py# Assignment operator : #In Python, the assignment operator (=) does not create a copy of the object. #Instead, it creates a new reference to the same object. a = [4,5,6,7,8] b = a b[0] = 3 ##print(b) ##print(a) #id() returns unique identification value of the object stored in memory. ##print(id(b)) ##print(id(a)) # ------------------------- Shallow copy: ---------------------------------- # A shallow copy created using .copy(), copies the outer list but not the nested objects. # .copy() crates a shallow copy in Python. ##li = [1,2,3,[4,5]] ##li_2 = li.copy() ##print(li) ##print(li_2) ##li_2[1] = 100 ##print(li) ##print(li_2) ## ##li_2[3][1] = 'a' ##print((li)) ##print(li_2) ## ##print(id(li)) ##print(id(li_2)) ##print(id(li[3])) ##print(id(li_2[3])) # ---------------------- Shallow Copy using module 'copy': -------------------------------- #import copy ##list_1 = [1,2,3,[4,5]] ##list_2 = copy.copy(list_1) ## ##list_2[0] = "apple" ##print(list_1) ## ##list_2[3][0]= "apple" ##print(list_1) # --------------- Deep copy in Python : ----------------------- #A deep copy created using copy.deepcopy(), copies both the outer list and all nested objects. # copy.deepcopy() is used to create a deep copy in python. import copy list_1 = [1,2,3,[4,5]] list_2 = copy.deepcopy(list_1) print(list_1) print(list_2) list_2[0] = "apple" print(list_1) list_2[3][0]= "apple" print(list_1) print(list_2) print(id(list_1)) print(id(list_2)) print(id(list_1[3])) print(id(list_2[3]))https://www.w3schools.com/python/python_sets.asp?authuser=0https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/?authuser=022 Augfor_loop.py# for loop : # for loop is used to iterate over an iterable (i.e., list, dictionary, tuple, set or string) # It helps you repeat a set of instructions for each item in a # collection, letting you do something with each # item without having to write the same code over and over again. ##for i in range(10): ## print("Hello world") #------------------------------------------------- alist = ["apple","banana","papaya","orange"] ##for i in alist: ## print(i) #-------------------------------------------------- num = 12 ##for i in range(num): ## print(i) #-------------------------------------------------- #Q. WAP to print the square of each element of a list. li = [1,2,3,4,5] ##for i in li: ## print(i*i) #Q, WAP to write a table of the user inputted number. ##number = int(input("enter a number: ")) ##for i in range(1, 11): ## print(i*number) #Q. Iterate over a list of numbers 1 to 10 # print only even numbers using for loop list1 = [1,2,3,4,5,6,7,8,9,10] ##for i in list1: ## if i %2 == 0: ## print(i)for_loop (2).py# Practice questions: ##Question 1: WAP to print all the odd numbers within ##the given range. #Sol : ##givenRange = 20 ##for i in range(1, givenRange): ## if i%2 != 0: ## print(i) #--------------------------------------------------------------------------- ##Question 2: WAP to calculate the sum of all the natural numbers till 10. #Sol : ##no = 10 ##x = 0 ##for i in range(1, no+1): ## x = x+i # x+=i ##print(x) #--------------------------------------------------------------------------- #Question 3: WAP to print the factorial of a number. #Sol : ##num = int(input("enter a number: ")) ##fac = 1 ## ##for i in range(1, num+1): ## fac *= i ## ##print(fac) # ------------------------------------------------------------------------ #--------------------------------------------------------------------------- #Question 4 : The Fizz-Buzz Question : ##for i in range(1,21): ## if i %3 == 0 and i%5 == 0: ## print("FizzBuzz") ## elif i%3 == 0: ## print("fizz") ## elif i% 5 == 0: ## print("Buzz") ## else: ## print(i) #--------------------------------------------------------------------------- # Question 5 : WAP program which converts all the elements of ##given list to the string representation of their respective ##datatypes ##Example: ## ##Input - [1, 2.0, 3, 'apple', 5, 'papaya'] ##Ouput - ['integer',' float', 'integer', 'string', 'integer', 'string'] #Sol : Input = [1, 2.0, 3, 'apple', 5, 'papaya'] Output = [] ##for i in Input: #### print(type(i)) ## if type(i) == int: ## Output.append('integer') ## if type(i) == float: ## Output.append('float') ## if type(i) == str: ## Output.append('string') ## ##print(Output) #----------------------------------------------------------------------------for_loop (3).py# ---------------- BREAK AND CONTINUE ---------------- # break statement is used to exit a loop when an external condition is met. ##for i in range(6): ## if i == 3: ## break ## print(i) # Continue statement stops the current iteration of the loop ##for i in range(10): ## if i == 5: ## continue ## print(i) #[Break statement stops the entire process of the loop. Continue #statement only skips the current iteration of the loop. ] #-------------------------------------------------------------------------------- #-------------------------------------------------------------------------------- #Question : WAP to print all the elements except 'WoElement' from alist. #sol: ##for i in alist: ## if i != 'WoElement': ## print(i) # using 'continue': #sol2: ##for i in alist: ## if i == 'WoElement': ## continue ## print(i)24 Aughome.py# Practice Questions: #Q. ##numbers = (1,2,3,4,5,6,7,8,9) ##evens = 0 ##odds = 0 ## ##for i in numbers: ## if i %2 == 0: ## evens = evens + 1 ## else: ## odds = odds + 1 ## ##print("evens", evens) ##print("odds", odds) # -------------------------------------------------------------------------------------------------- # Q. WAP to find out the index value of "pineapple" # print the statement once you've find out the element 'i have found Pineapple # on index _' fruits = ['apple', 'kiwi', 'orange', 'mango', 'papaya', 'pineapple','papaya'] ##num = 0 ##for i in fruits: ## if i=="pineapple": ## break ## num+=1 ##print("i have found pineapple on index", num) # ------------------------------------------------------------------------------------------ # ---------- Same Programme using enumerate() function : ----------------------- ##print(list(enumerate(fruits))) # ------------------------------------------------------------------------------------------ for index,element in enumerate(fruits): if element == "pineapple": print(f"i have found pineapple on index value {index}")https://www.geeksforgeeks.org/python-for-loops/?authuser=0Assignment_2.txt# Python Assignment 2 : [20 m.m] Q.1, Write a program to print 'pleasant day' from a string "What a pleasant day". (2 marks) Q.2, WAP to print the squares of each element of a list. (2 marks) alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Q.3, WAP to calculate x to the power y using loop (x and y must be user inputs). (2 marks) Q.4, WAP to create a new list of evens from a given tuple. (2 marks) tuple1 = (23, 44, 56, 12, 51, 19, 16, 22, 40) Q.5, WAP to print the factorial of a user inputted number (2 marks) Q.6, WAP that creates a new list containing all the elements of the given list, with each element converted to a string data type. (3 marks) blist = [1, 2, 3, 4,5, 0, 'hello', 9, True] Q.7, WAP to create a new list containing the cubes of even numbers from 1 to 10. (3 marks) Q.8, WAP to create a dictionary using elements of a list as keys and index numbers as the values of a dictionary without using index and enumerate functions. (4 marks) clist = ['a', 'b', 'c', 'd', 'e', 'f'] at the end, your dictionary should look like : {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5}26 Augfor_else.py# for else: ##for Loop: Repeats code for each item in a sequence. ##else Block: Runs after the for loop is finished executing, but only if the ##loop didn’t end early with a break. ##for i in range(1,5): ## print(i) ##else: ## print("Program terminated") #------------------------------------------------------------- ##for i in range(6): ## if i == 3: ## break ## print(i) ##else: ## print("successfully executed") #------------------------------------------------------------- ##for i in range(6): ## if i == 8: ## break ## print(i) ##else: ## print("successfully executed") #------------------------------------------------------------- numbers = [2,3,5,-1,0,33] ##for i in numbers: ## print(i) ## if i == 0: ## break ##else: ## print("Loop finished without a break") #------------------------------------------------------------- # Question. WAP to check whether a number is prime or not : ##num = 6 ##for i in range(2,num): ## if (num%i == 0): ## print("Not Prime") ## break ##else: ## print("Prime")home.py# for else: ##for i in range(1,5): ## print(i) ##else: ## print("Program terminated") ##for i in range(6): ## if i == 3: ## break ## print(i) ##else: ## print("successfully executed") ##for i in range(6): ## if i == 8: ## break ## print(i) ##else: ## print("successfully executed") # ------------------------ Practice questions : ------------------- ##numbers = [2,3,5,-1,0,33] ##for i in numbers: ## ## if i == 0: ## break ## print(i) ##else: ## print("Loop finished without a break") # --------------------------------------------------------------------------------------------- ##fruits = ['apple', 'kiwi', 'orange', 'papaya', 'pineapple','papaya','mango'] ## ## ##for i in fruits: ## if i == 'mango': ## print("i have found mango") ## break ##else: ## print("i have not found mango") ## ##print("i am out of loop") # ------------------------------------------------------------------------------------------------- ##num = 8 ## ##for i in range(2,7): ## if num % i == 0: ## print(f"{num} is not prime") ## break ## ##else: ## print(f"{num} is prime") 27 Augwhile.py# while loop in Python: # used to repeat a set of actions or as long as a certain condition is true. ##i = 0 # initialization ##while i<10: ## print(i) ## i += 1 # ----------------------------------------------------------------------------------- ##i = 5 ##while i >= 1: ## print(i) ## i -= 1 # ----------------------------------- INFINITE LOOP ------------------------------------------------ #A while loop becomes an infinite loop when the condition it checks never becomes false. ##while True: ## print("Hello World") #--------------------------------------------------------------------------- ##i = 0 ## ##while i < 5: ## print(i) #---------------------------------------------------------------------------- #---------------------------------------------------------------------------- #------------------- Practice Questions : -------------------------------- # print a table of a user inputted number using while loop. num = int(input("enter a number: ")) i = 1 while i <= 10: print(num*i) i += 1 # ---------------------------------------------------------------------------- # print all the elements of the list using while loop. ##fruits = ["apple", "kiwi", "orange", "grape"] ## ##i = 0 ## ##while i < len(fruits): ## print(fruits[i]) ## i +=1 # ---------------------------------------------------------------------------- # factorial using while loop : factorial = 1 i = 1 while i <= 5: factorial *= i i += 1 print(factorial) # ----------------------------------------------------------------------------- # Break & Continue # ----------------------------------------------------------------------------- count = 0 while count < 5: print(count) count += 1 if count == 3: break else: print("loop successfully finished") # -----------------------------------------------------------------------------home.py# for else: ##prime_list = [] ##num = int(input("enter a number: ")) ## ##for i in range(2, num+1): ## for j in range(2,i): ## if i%j == 0: ## break ## else: ## prime_list.append(i) ## ##print(prime_list) # -------------------------------------------------------------------------------------------- ##i = 10 # initialization ## ##while i>=1: ## print(i) ## i -= 1 ##i = 1 ##num = 5 ## ##while i <=10: ## print(num * i) ## i +=1 fruits = ["apple", "kiwi", "orange", "grape"] ##i = 0 ## ##while i<len(fruits): ## print(fruits[1]) ## i += 1 # --------------------------------------------------------- ##i = 0 ## ##while i<1: ## print(fruits[i]) ## i += 1 # --------------------------------------------------------- ##factorial = 1 ##i = 1 ##while i < 5: ## i += 1 ## factorial *= i ## ##print(factorial ) # ---------------------------------------------------------- ##i = 0 ## ##while i <5: ## if i == 3: ## i += 1 ## continue ## print(i) ## i += 1 # ------------------------------- ##i = 0 ##while i < 5: ## print(i) ## i += 1 ## if i == 9: ## break ##else: ## print("loop successfully finished") https://www.w3schools.com/python/python_while_loops.asp?authuser=029 Augwhile_practice.py# While loop practice questions : # printing a statement 10 times using while loop. ##i = 0 ## ##while i <=10: ## print("Hello World") ## i +=1 # ---------------------------------------------------------------------- # iterating over a list using while loop : ##alist = ["a", "b", "c", "d", "e"] #### ##i = 0 ##while i <=len(alist): ## ## ## print(i) ## i+=1 # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # print all the elements of a list using while loop: ##alist = ["a", "b", "c", "d", "e"] ####print(alist[0]) ##i = 0 ##while i <len(alist): ## print(alist[i]) ## i += 1 # ---------------------------------------------------------------------- # print a table of a user inputted number using while loop: ##num = int(input("enter a number: ")) ##i = 1 ## ##while i <=10: ## print(num *i) ## i +=1 # ---------------------------------------------------------------------- # factorial : ##num = int(input("enter a number: ")) ## ##factorial =1 ## ##i = 1 ## ##while i<= num: ## factorial *= i ## i+=1 ## ##print(factorial) # ---------------------------------------------------------------------- ## ##fruits = ["apple", "kiwi", "grape", "ffg"] ## ##index = 0 ##while index < len(fruits): ## ## if fruits[index] == "orange": ## print("i have found orange") ## break ## index += 1 ##else: ## print("not found") ## ##print("i am out of loop") # ------------------------- Even Number question ------------------------------ ##num = int(input("enter a number:")) ##li = [] ##i = 1 ## ##while i<= num: ## if i % 2 == 0: ## li.append(i) ## ## i+=1 ##print(li) # --------------------------------------------------------------------- # CONTINUE ##i = 0 ##while i <10: ## if i == 3: ## i+=1 ## continue ## print(i) ## i+=1 # ------------------------------------------------------------------ ##li = [] ##i = 0 ## ##while i <= 10: ## if i % 2 == 0: ## li.append(i) ## i+=1 ## ##print(li) ##home.py##def Greeting(): ## print("Hello World") ## print("xyz") ## ##print("Have a nice day!") ## ##Greeting() # -------------------------------------------------------------------------------------- ##def Addition(a,b): ## return a+b ## ##result = Addition(2,4) ##print(result) # -------------------------------------------------------------------------------------- ##Q.1, Write a program to print 'pleasant day' from a string ##"What a pleasant day". (2 marks) ##string = "What a pleasant day" ##print(string[7:]) ##Q.2, WAP to print the squares of each element of a list. (2 marks) alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ##for i in alist: ## print(i*i) ##Q.3, WAP to calculate x to the power y using loop (x and y must be user inputs) ##. (2 marks) ##x = int(input("enter a number: ")) ##y = int(input("enter a number: ")) ## ##z = 1 ## ##for i in range(1,y+1): ## z = z*x ##print(z) ####Q.4, WAP to create a new list of evens from a given tuple. (2 marks) ##tuple1 = (23, 44, 56, 12, 51, 19, 16, 22, 40) ## ##li = [] ## ##for i in tuple1: ## if i%2 == 0: ## ## li.append(i) ## ##print(li) ##Q.6, WAP that creates a new list containing all the elements of the given list, with each ## element converted to a string data type. (3 marks) ##blist = [1, 2, 3, 4,5, 0, 'hello', 9, True] ## ##li = [] ##for i in blist: ## li.append(str(i)) ## ##print(li) ##Q.7, WAP to create a new list containing the cubes of even numbers from 1 to ##10. (3 marks) ##li = [] ##for i in range(1,11): ## if i%2 == 0: ## li.append(i*i*i) ##print(li) ##Q.8, WAP to create a dictionary using elements of a list as keys and index numbers as ## the values of a dictionary without using index and enumerate functions. (4 marks) ## clist = ['a', 'b', 'c', 'd', 'e', 'f'] ## at the end, your dictionary should look like : ## {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5} ## ##clist = ['a', 'b', 'c', 'd', 'e', 'f'] ##di = {} ##value = 0 ## ##for i in clist: #### di.update({i:value}) ## di[i] = value ## value += 1 ## ##print(di)functions.py# ----------------------- Functions in Python : -------------------------- # In Python, a function is a block of reusable code that performs a specific # task when it's called. ##def Greeting(): ## print("Hello World") ## ##Greeting() # ------------------------------------------------------------ ##def Greeting(): ## print("Hello World") ## ##print("Have a nice day!") ##Greeting() # ------------------------------------------------------------ ##def Greeting_1(n): ## print("Hello", n) ## ##Greeting_1("Mariya") ##Greeting_1("Ibrahim") # ------------------------------------------------------------ ##def Addition(a,b): ## print(a + b) ## ##Addition(3,4) # ---------------------- return keyword :--------------------- ##def Subtraction(a,b): ## return a-b ## ##result = Subtraction(8,2) ##print(result) ## ##result_2 = Subtraction(10,2) ##print(result_2) # ------------------------------------------------------------ # ------------------------------------------------------------https://www.w3schools.com/python/python_functions.asp?authuser=0(Edited 29 Aug)functions (2).py# -------------- DEFAULT ARGUEMENTS: ------------------ def Add(a,b,c =2): return a + b + c ##result = Add(3,3,3) ##print(result) ## ##result_2 = Add(3,3) ##print(result_2) # ---------------------------------------------------------------- def Greeting(name = "User"): return f"Hello {name}" ##x = Greeting("Mariya") ##print(x) ## ##y = Greeting() ##print(y) # --------------------------------------------------------------- # ------------------ KEYWORD ARGUMENTS : ----------------------- def my_function(fruit_1, fruit_2, fruit_3): return f"my favourite fruit is {fruit_3}" ##a = my_function("apple","banana","orange") ##print(a) ##b = my_function(fruit_1 = "Orange", fruit_2 = "banana", fruit_3 = "apple") ##print(b) # --------------------------------------------------------------- # ----------- Arbitrary Positional Arguments (*args): ------------- # *args allows a function to accept any number of positional arguments. def print_numbers(*args): for i in args: print(i) ##print_numbers(1, 2, 3, 4, 5) # --------------------------------------------------------- def add(*args): result = 0 for i in args: result += i return result a = add(1,2) print(a) b = add(12,34,55) print(b) c= add(8,7,6,7,8,9,0) print(c) # ------------ Arbitrary Keyword Arguments (**kwargs) : ------------ # *kwargs allows a function to accept any number of keyword arguments. def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") ##print_info(name="Alice", age=30, city="New York")home.pyimport random ##print(dir(random)) ##print(random.random()) ##print(random.randint(1,10)) ##print(random.randrange(1,10)) ## li = [10,20,30,40,50,60] #### ##print(random.choice(li)) ##print(random.uniform(1,10)) ## ##random.shuffle(li) ##print(li) # -------------------------- Shallow copy, deep copy :--------------------------------------- ##a = [4,5,6,7,8] ## ##b = a ##b[0] = 3 ## ##print(id(b)) ##print(id(a)) # ---------------------------------------------------------------------------------- li = [1,2,3,[4,5]] li_2 = li.copy() ##print(li) ##print(li_2) li[0] = 0 ##print(li) ##print(li_2) ##print(id(li)) ##print(id(li_2)) ##print(id(li[3])) ##print(id(li_2[3])) ## ##li_2[3][1] = 'a' ##print((li)) ##print(li_2) # ---------------------------------------------------------------------------------- ##import copy ## ##list_1 = [1,2,3,[4,5]] ##list_2 = copy.deepcopy(list_1) ## ##print(id(list_1)) ##print(id(list_2)) ## ##print(id(list_1[3])) ##print(id(list_2[3])) ##list_2[0] = "apple" ##print(list_2) ##print(list_1) ##list_2[3][0]= "apple" ##print(list_1) ##print(id(list_1)) ##print(id(list_2)) ## ##print(id(list_1[3])) ##print(id(list_2[3])) # ----------------------------------------------------------------------------- # ------------------------------ functions : --------------------------------- ##def Greeting(): ## print("Hello World") ## ## ##print("Have a nice day") ##Greeting() ##a = 2 ##b = 5 ##result = a+ b ##print(result) ##def Addition(x,y): ## return x + y ## ##result = Addition(4,9) ##print(result) # ----------------------- default arguements in functions ------------------------- ##def Add(a,b,c =2): ## return a + b + c ## ##result = Add(3,3) ##print(result) ## ##def greeting(name = "User"): ## return f"Hello {name}" ## ##x = greeting("Mariya") ##print(x) ## ##y = greeting() ##print(y) # ---------------------------------- *args --------------------------------------- ##def print_numbers(*args): ## for i in args: ## print(i) ## ##print_numbers(1, 2, 3, 4, 5) #### # --------------------------------------------------------------------------------- ####def Add(*args): #### a = 0 #### for i in args: #### a += i #### return a #### ####result_1 = Add(4,5,9,7) ####result_2 = Add(6,6) #### ####print("result_1 = ", result_1) ####print("result_2 = ", result_2) # ---------------------------------- *kwargs --------------------------------------- ##def print_info(**kwargs): ## for key, value in kwargs.items(): ## print(f"{key}: {value}") ## ##print_info(name="Alice", age=30, city="New York") # ---------------------------------- zip() function --------------------------------- ##li2 = [1,2,3,4,5] ##tuple_1 = (100, 200,300) ## ##li3 = list(zip(li, li2, tuple_1)) ##print(li3) # ---------------------------- enumerate() function ------------------------------ li = ['a','b','c','d','e'] print(list(enumerate(li))) for i,e in enumerate(li): print(i,e) shallow_&_deepCopy.py# Assignment operator : #In Python, the assignment operator (=) does not create a copy of the object. #Instead, it creates a new reference to the same object. a = [4,5,6,7,8] b = a b[0] = 3 ##print(b) ##print(a) #id() returns unique identification value of the object stored in memory. ##print(id(b)) ##print(id(a)) # ------------------------- Shallow copy: ---------------------------------- # A shallow copy created using .copy(), copies the outer list but not the nested objects. # .copy() crates a shallow copy in Python. ##li = [1,2,3,[4,5]] ##li_2 = li.copy() ##print(li) ##print(li_2) ##li_2[1] = 100 ##print(li) ##print(li_2) ## ##li_2[3][1] = 'a' ##print((li)) ##print(li_2) ## ##print(id(li)) ##print(id(li_2)) ##print(id(li[3])) ##print(id(li_2[3])) # ---------------------- Shallow Copy using module 'copy': -------------------------------- #import copy ##list_1 = [1,2,3,[4,5]] ##list_2 = copy.copy(list_1) ## ##list_2[0] = "apple" ##print(list_1) ## ##list_2[3][0]= "apple" ##print(list_1) # --------------- Deep copy in Python : ----------------------- #A deep copy created using copy.deepcopy(), copies both the outer list and all nested objects. # copy.deepcopy() is used to create a deep copy in python. import copy list_1 = [1,2,3,[4,5]] list_2 = copy.deepcopy(list_1) print(list_1) print(list_2) list_2[0] = "apple" print(list_1) list_2[3][0]= "apple" print(list_1) print(list_2) print(id(list_1)) print(id(list_2)) print(id(list_1[3])) print(id(list_2[3]))Zip_&_Enumerate.py#----------------------- ZIP FUNCTION --------------------------- #Zip is an inbuilt function in python, used to iterate over multiple iterables. #it takes corresponding elements from all the iterables passed to it and merges them into a tuple. #returns a zip objects that can be converted into a list for better reading. syntax : zip(iterable1, iterable2, iterable3 etc) li = ['a','b','c','d','e'] li2 = [1,2,3,4,5] li3 = list(zip(li, li2)) print(li3) #--------------------- ENUMERATE FUNCTION ----------------------- li = ['a','b','c','d','e'] print(enumerate(li)) print(list(enumerate(li))) # to iterate over a list using enumerate function ##newList = ['rose','sunflower','lily'] ##for index,element in enumerate(newList):## print(index,element)https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/?authuser=0https://www.w3schools.com/python/module_random.asp?authuser=030 AugLocal_&_Global_variables.py# Local & Global variables in Python: ##a = 10 #global variable ## ##def display(): ## print(a) ## ##display() # -------------------------------------------------------------- ##def display(): ## a = 15 #local variable #### print(a) ## ##display() ##print(a) # -------------------------------------------------------------- ##a = 20 ## ##def display_1(): ## a = 21 ## print(a) ## ##display_1() ##print(a) # ---------------- global keyword in python: ------------------ ##a = 20 ## ##def display_1(): ## global a ## a = 21 ## print(a) ## ##display_1() ##print(a) # ------------------------------------------------------------------home.py# keyword arguments: ##def my_function(fruit_1, fruit_2, fruit_3): ## return f"my favourite fruit is {fruit_3}" ## ####a = my_function("apple","banana","orange") ####print(a) ## ####b = my_function(fruit_3 = "apple", fruit_1 = "Orange", fruit_2 = "banana" ) ##print(b) # -------------------------------------------------------------------------------------------------- # *args: ##def print_numbers(*args): ## for i in args: ## print(i) ##print_numbers(1, 2, 3, 4, 5) # -------------------------------------------------------------------------------------------------- ##def add(*args): ## result = 0 ## for i in args: ## result += i ## return result ## ####a = add(1,2) ####print(a) ## ##b = add(12,34,55) ##print(b) ##c= add(8,7,6,7,8,9,0) ##print(c) # ------------------------------------------------------------------------------------------------------ # **kwargs: ##def print_info(**kwargs): ## for key, value in kwargs.items(): ## print(f"{key}: {value}") ## ##print_info(name="Alice", age=30, city="New York") # ---------------------------------------------------------------------------------------------------- # dictionary: ##my_dict = { ## 'Name':'Ben', ## 'age':'11', ## 'city':'New york'} ## ####print(my_dict.pop('age')) ####print(my_dict) ## ##del (my_dict) ##print(my_dict) ##my_dict.clear() ##print(my_dict) ##print(my_dict.values()) ##print(my_dict.keys()) # --------------------------- .items() ---------------------------- ##print(my_dict.items()) ##for k,v in my_dict.items(): ## print(k,v) ## ##print('name' in my_dict) ## ##print(my_dict["age"]) ## ##print(len(my_dict)) ##my_dict["name"] = "tom" ## ## ##my_dict["country"] = "america" ##print(my_dict) # -------------------- enumerate() ---------------------------- ##li = ['a','b','c','d','e'] ##print(list(enumerate(li))) ## ##for index,element in enumerate(li): ## print(element) # -------------------- zip () ---------------------------------- ##li = ['a','b','c','d','e'] ##li2 = [1,2,3,4,5] ##tuple_1 = ('hello','world') ##my_dict = {"name":"xyz", "name_2":"abc"} ## ##li3 = list(zip(li,li2, tuple_1, my_dict)) ##print(li3) # -------------------------------------------------------------------------------------------------- ##pets = { ## "pet1": {"name": "Buddy", "type": "dog", "age": 5}, ## "pet2": {"name": "Mittens", "type": "cat", "age": 3}, ## "pet3": {"name": "Tweety", "type": "bird", "age": 2} ##} ## ##pets["pet4"] = [1,2,3] ## ##print(pets) # ------------------------------------------------------------------- ##a = 10 #global variable ## ##def display(): ## return a ## ####x = display() ##print(display()) ##a = 17 ## ##def display(): ## global a ## a = 15 ## print(a) ## ##display() ##print(a) https://www.geeksforgeeks.org/global-local-variables-python/?authuser=04 Septlambda.py# ------------------ LAMBDA FUNCTION ------------------ # Lambda, also called as "Anonymous" Function in Python. # It is a one liner function # This function can have any number of arguments # but only one expression. ##def add(x): ## return x + 5 ## ##print(add(5)) ##a = lambda x:x+5 ##print(a(5)) # ----------------------------------------------------------------------------------- my_func = lambda x:x*2 print(my_func(5)) # ---------------------------------------------------------------------------------- square = lambda x: x*x print(square(5)) # ---------------------------------------------------------------------------------- string = "HAPPY" function = lambda x: x.lower() print(function(string)) # ---------------------------------------------------------------------------------- # Even Number Using Lambda ##z = lambda y:y%2 == 0 ##print(z(8)) #return true # Odd Number Using Lambda ##z = lambda x:x%2 != 0 ##print(z(13)) # ---------------------------------------------------------------------------------- # Passing multiple arguments in lambda # Adding two numbers ##z = lambda x,y:x+y ##print(z(2,3)) # Adding 3 numbers ##z = lambda a,b,c:a+b+c ##print("2 + 3 + 4 =",z(2,3,4)) # ---------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------- new_func = lambda x: 'even' if x %2 == 0 else 'not even' print(new_func(8)) # ----------------------------------------------------------------------------------https://www.w3schools.com/python/python_lambda.asp?authuser=0(Edited 9 Sept)lambda.py# ------------------ LAMBDA FUNCTION ------------------ # Lambda, also called as "Anonymous" Function in Python. # It is a one liner function # This function can have any number of arguments # but only one expression. ##def add(x): ## return x + 5 ## ##print(add(5)) ##a = lambda x:x+5 ##print(a(5)) # ----------------------------------------------------------------------------------- my_func = lambda x:x*2 print(my_func(5)) # ---------------------------------------------------------------------------------- square = lambda x: x*x print(square(5)) # ---------------------------------------------------------------------------------- string = "HAPPY" function = lambda x: x.lower() print(function(string)) # ---------------------------------------------------------------------------------- # Even Number Using Lambda ##z = lambda y:y%2 == 0 ##print(z(8)) #return true # Odd Number Using Lambda ##z = lambda x:x%2 != 0 ##print(z(13)) # ---------------------------------------------------------------------------------- # Passing multiple arguments in lambda # Adding two numbers ##z = lambda x,y:x+y ##print(z(2,3)) # Adding 3 numbers ##z = lambda a,b,c:a+b+c ##print("2 + 3 + 4 =",z(2,3,4)) # ---------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------- new_func = lambda x: 'even' if x %2 == 0 else 'not even' print(new_func(8)) # ----------------------------------------------------------------------------------map.py# ----------------------------- MAP FUNCTION ------------------------------- # Map function returns a map object. # It takes two arguments, a function and an iterable. # It appplies a given function to each item of that given iterable. # Returning a cube list using map li = [1,2,3,4,5] def cube(n): return n**3 cube_list = list(map(cube,li)) print(cube_list) # ---------------------------------------------------------------------------------------- list_of_strings = ['scissors', 'pen', 'bicycle', 'bottle'] number_li = [] def count_the_len(a): for i in a: number_li.append(len(i)) count_the_len(list_of_strings) print(number_li) # ---------------------------------------------------------------------------------------- # Length of each string using map function ##list_of_strings = ['scissors', 'pen', 'bicycle', 'bottle'] ## ##lengthOfString = list(map(len, list_of_strings)) ##print(lengthOfString) # ---------------------------------------------------------------------------------------- # Converting list of ints into list of string ##int_list = [2,4,5,6,3,8] ## ##string_list = list(map(str, int_list)) ##print("List Of Strings:",string_list) # ---------------------------------------------------------------------------------------- numbers = [1, 2, 3, 4, 5] doubled_numbers = map(lambda x: x * 2, numbers) # --------------------------------------------------------------------------------------- # Adding two lists using map ##alist = [1,2,3,4,5] ##blist = [6,7,8,9,10] ## ##add = list(map(lambda x,y:x+y, alist,blist))##print(add)home.py# Guess the number (GAME): ##while True: ## wanna_play = int(input("press 0 to play, 1 to exit")) ## ## if wanna_play == 1: ## print("you have exited") ## break ## ## winning_num = random.randint(1,10) ## li= [] ## ## for i in range(5): ## guess = int(input("guess a number between 1 to 10")) ## ## if guess == winning_num: ## print("you won!") ## break ## ## elif guess > winning_num: ## print(f"winning num is smaler than {guess}") ## ## else: ## print(f"winning num is greater tham {guess}") ## ## li.append(guess) ## print("previous guesses", li) # ----------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------- # Anonymous function in python (lambda): ##z = lambda a,b,c:a+b+c ##print(z(2,3,4)) ##li = [2,5,9,1,4,3,100,7] ##sorted_list = lambda x : sorted(x, reverse = True) ##print(sorted_list(li)) ##new_func = lambda x: 'even' if x %2 == 0 else 'not even' ##print(new_func(3)) # ----------------------------------------------------------------------------------------------- # map function in python: ##li = [1,2,3,4,5] ## ##def cube(n): ## return n**3 ## ##cube_list = list(map(cube,li)) ##print(cube_list) # --------------------------------------------------------- ##list_of_strings = ['scissors', 'pen', 'bicycle', 'bottle'] ##def new_func(a): ## return len(a) ## ##print(list(map(new_func,list_of_strings))) # --------------------------------------------------------- ##x = list(map(len,list_of_strings)) ##print(x) # --------------------------------------------------------- li = [1,2,'Hello', True, 7] ##def new_func(value): ## return str(value) ## ##string_list = list(map(new_func, li)) ##print(string_list) # --------------------------------------------------------- ##string_list = list(map(str, li)) ##print(string_list) # --------------------------------------------------------- ##numbers = [2, 4, 5, 10, 3] ##def function(x): ## return x*2 ## ##print(list(map(function, numbers))) # --------------------------------------------------------- ##result = list(map(lambda x: x*2, numbers)) ##print(result) # --------------------------------------------------------- ##alist = [1,2,3,4,5] ##blist = [6,7,8,9,10] ## ## ##print(list(map(lambda a,b: a+b, alist,blist))) # --------------------------------------------------------- num = int(input("enter a number: ")) a = list(map(lambda x: x**3, range(1,num+1))) print(a) https://www.w3schools.com/python/python_lambda.asp?authuser=0https://www.geeksforgeeks.org/python-map-function/?authuser=011 Septfilter_reduce.py# ------------------- FILTER FUNCTION ------------------- # Filter function filters out a given sequence by passing it # into a function returning true values li = [1,2,3,4,5,6,7,8,9] def evens (a): if a %2 == 0: return a evensList = list(filter(evens,li)) ##print(evensList) # ------------------------------------------------------------------------------------ li = [1,2,3,4,5,6,7] z = lambda x: x%2==0 for i in li: print(z(i)) newEvenList = list(filter(lambda x: x%2==0,li)) ##print(newEvenList) ##odds = list(filter(lambda x:x%2 != 0, alist)) #filter odds from a list ##print("List of Odd:",odds) # ------------------------------------------------------------------------------------ a = [1,2,3,4,5] b = [2,3,4,6,7] n = list(filter((lambda x: x in a),b)) ##print(n) # ------------------------------------------------------------------------------------ #numbers divisible by 5 ##alist = [2,3,5,6,8,10,11,15,17,25,34,35,40,7,8,12,55] ##y = list(filter(lambda x: x%5 == 0, alist)) ##print(y) # -------------------- REDUCE FUNCTION-------------------- # Reduce function passes a given sequence to a function and # reduces it to a single value from functools import reduce alist = [2,3,5,5,6] sumlist = reduce(lambda x,y:x+y, alist) ##print (sumlist) # ------------------------------------------------------------------ # factorial using reduce num = int(input("Enter a number: ")) newlist = list(range(1,num+1)) ##print(newlist) ##print(reduce(lambda x,y:x*y, newlist)) # ------------------------------------------------------------------ ##print(reduce(lambda x,y:x*y,(range(1,num+1)))) # ------------------------------------------------------------------ numbers = [5,8,7,3,2,10,1,9] print(reduce(lambda a,b: a+b, numbers)) # ------------------------------------------------------------------ # question : products = [{"name":"mobile","price":499}, {"name":"shirt","price":899}, {"name":"book","price":399}, {"name":"mugs","price":999}] ##2 - Write a Python program which selects and prints (as a list) ## all the strings of length greater than 4 from a list of ## strings using filter function and lambda(2 marks) #solution: strings = ['alexander','joe','tiffany','ana','max','george'] home.py# filter: li = [1,2,3,4,5,6,7,8,9] ##def evens (a): ## if a %2 == 0: ## return a ##evensList = list(filter(lambda x: x%2==0,li)) ##print(evensList) # --------------------------------------------------------------------- ##a = [1,2,3,4,5] ##b = [2,3,4,6,7] ##n = list(filter((lambda x: x in a),b)) ##print(n) ## ##li = [3,4,5,6,7,8,9,12,15,28,18] # --------------------------------------------------------------------- # reduce: from functools import reduce ##alist = [2,3,5,5,6] ##sumlist = reduce(lambda x,y:x+y, alist) ##print (sumlist) # --------------------------------------------------------------------- ##num = int(input("enter a number: ")) ## ##factorial = reduce(lambda x,y: x*y, range(1,num+1)) ##print(factorial) # --------------------------------------------------------------------- # ---------------------- Practice Questions: ----------------------- ##products = [{"name":"mobile","price":499}, ## {"name":"shirt","price":899}, ## {"name":"book","price":399}, ## {"name":"mugs","price":999} ## ] ## ##print(list(filter(lambda x:x["price"]<=500, products))) # --------------------------------------------------------------------- ##strings = ['alexander','joe','tiffany','ana','max','george'] ## ##print(list(filter(lambda x: len(x)<=4, strings))) # --------------------------------------------------------------------- # ---------------------- List Comprehension: ----------------------- ##li = [i for i in range(1,20) if i%2 ==0] ##print(li) ##square_list = [i*i for i in range(1,21)] ##print(square_list) 11 Septlist_comprehension.py# ---------- LIST COMPREHENSIONS ---------- # You can construct lists in interesting ways using # list comprehensions print([i for i in range(1,11)) # Create a list of odd values ##oddList = [i for i in range(1,21) if i%2 != 0] ##print('Odd List:',oddList) # A list with table of two ##Table_of_two = [i*2 for i in range(1,11)] ##print("Table of 2:",Table_of_two) cities = ["Madrid", "London", "New York", "Berlin", "Tokyo"] filtered_cities = [i for i in cities if "o" in i] print(filtered_cities) # -------------- NESTED LISTS -------------- a =[[i] for i in range(4)] print(a) nested_list = [[i for i in range(1,4)]for i in range(4)] print(nested_list)home.pyli =['hello', 'world'] Output: ['HELLO', 'WORLD'] ##print(list(map(lambda x:x.upper(),li))) # ---------------------------------------------------------- di = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}] ##names = list(map(lambda x: x["name"], di)) ##print(names) # ---------------------------------------------------------- ##alist = ['Apple', 'Banana', 'Avocado'] ##print(list(filter(lambda x:x.startswith('A'), alist))) # ---------------------------------------------------------- ##print([i for i in range(1,11)]) ##blist = [i**2 for i in range(1,11)] ##print(blist) ##oddList = [i for i in range(1,21) if i%2 != 0] ##print(oddList) # ---------------------------------------------------------- ##cities = ["Madrid", "London", "New York", "Berlin", "Tokyo"] ## ##new_list= [city for city in cities if "o" in city] ##print(new_list) # ---------------------------------------------------------- ##li = [list(range(1,4)) for i in range(3)] ##print(li) # ---------------------------------------------------------- nested_list =[[i for i in range(1,4)] for i in range(3)]print(nested_list)12 Septdictionary_comprehension.py# ---------------DICTIONARY COMPREHENSIONS------------------- # Like list comprehensions, Python supports dict comprehensions, # which allow you to express the creation of dictionaries at # runtime using a similarly concise syntax. # This one maps the numbers in a specific range to their cubes: ##CubeDict = {x:x**3 for x in range(10)} ##print(CubeDict) # A dictionary from a list with months as values and their # lengths as keys ##month_list = ['January', 'Februaury', 'March', 'May', 'July' new_dict = {len(i):i for i in month_list} print(len(new_dict)) # -------------------------------------------------------------------------------- # Making changes to an original dictionary ##price_dict = {'milk':40, 'meat':250, 'rice':80, 'wheat':100} ## ### increasedPrice = Rs. 30 per item ##newPrice_dict = {k:v+30 for k,v in price_dict.items()} ##print(newPrice_dict) # -------------- NESTED DICTIONARY -------------- # Dictionary with tables of 2,3,4 ##Tbl = {i:{j:i*j for j in range(1,11)}for i in range(2,5)} ##print(Tbl)key_sorting.py# ------------------ KEY SORTING ------------------ # Key sorting means to sort an iterable on the basis of any # property of items within that iterable ##The sorted() function and the .sort() method are commonly used for this ##purpose in Python. Both can take a key parameter, which is a function that ##specifies how the elements in the collection should be compared. ##sorted(): Returns a new sorted list from the elements of any iterable. ##.sort(): Sorts the list in place and returns None. aList = [9,4,2,5,6,7,8] # normal sorting bList = sorted(aList) print(bList) li = [9,4,2,5,6,7,8] # sorting in descending order new_li = sorted(li ,reverse=True ) print(new_li) fruits = ["Apple", "Pineapple", "Pear", "Banana"] print(sorted(fruits)) print(sorted(fruits, reverse=True)) #--------------------------------------------------------------------------------- list_of_tuples = [('a', 4),('z',1),('b',3),('n',7),('c',8)] ##sorted_list = sorted(list_of_tuples) ##print(sorted_list) ##print(list_of_tuples[2][1]) my_func = lambda x: x[1] sorted_li = sorted(list_of_tuples, key = my_func) print(sorted_li) # --------------------------------------------------------- fruits = ["Apple", "Pineapple", "Pear", "Banana"] def func(elem): return len(elem) ##print(sorted(fruits)) ##print(sorted(fruits, key = func)) ##print(sorted(fruits, key = func, reverse = True)) print(sorted(fruits, key = lambda elem : len(elem))) print(sorted(fruits, key = lambda elem : len(elem), reverse = True)) ##-------- #Sort by a specific key in each dictionary. data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}] sorted_data = sorted(data, key=lambda x: x['age']) ##print(sorted_data) #------------------------ .sort() -------------------------------------- my_list = [3, 1, 4, 1, 5, 9, 2] my_list.sort() my_list.sort(reverse=True) print(my_list) # ---------------------------------------------------------------------------------- words = ['banana', 'kiwi', 'Raspberry', 'apple'] words.sort(key=len) print(words) words.sort(key=len, reverse = True) print(words) home.pyli =['hello', 'world'] Output: ['HELLO', 'WORLD'] ##print(list(map(lambda x:x.upper(),li))) # ---------------------------------------------------------- di = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}] ##names = list(map(lambda x: x["name"], di)) ##print(names) # ---------------------------------------------------------- ##alist = ['Apple', 'Banana', 'Avocado'] ##print(list(filter(lambda x:x.startswith('A'), alist))) # ---------------------------------------------------------- ##print([i for i in range(1,11)]) ##blist = [i**2 for i in range(1,11)] ##print(blist) ##oddList = [i for i in range(1,21) if i%2 != 0] ##print(oddList) # ---------------------------------------------------------- ##cities = ["Madrid", "London", "New York", "Berlin", "Tokyo"] ## ##new_list= [city for city in cities if "o" in city] ##print(new_list) # ---------------------------------------------------------- ##li = [list(range(1,4)) for i in range(3)] ##print(li) # ---------------------------------------------------------- ##nested_list =[[i for i in range(1,4)] for i in range(3)] ##print(nested_list) ##numbers = [-10, 0, 5, 8, -3] ##print(list(filter(lambda x:x>0, numbers))) # ---------------------------------------------------------- ##list_of_strings = ['Hello', ' ', 'world', '!'] ####Hello world! ##from functools import reduce ## ##print(reduce(lambda x,y:x+y, list_of_strings)) # ---------------------------------------------------------- ##print([[i] for i in range(1,11)]) # ---------------------------------------------------------- li = [[1,2,3],[1,2,3],[1,2,3],[1,2,3]] ##print([[i for i in range(1,4)]for i in range(4)]) # ---------------------------------------------------------- li_2 = [[10, 20, 30], [10, 20, 30], [10, 20, 30], [10, 20, 30]] ##print([[i for i in range(10,31) if i%10== 0]for i in range(4)]) # ---------------------------------------------------------- ##flowers = ["rose", "tulip", "sunflower", "lily", "daisy"] ## ##print([i for i in flowers if i != "daisy"]) # ---------------------------------------------------------- ##di = {i:i**3 for i in range(1,11)} ##print(di) # ---------------------------------------------------------- ##month_list = ['January', 'Februaury', 'March', 'May', 'July'] ##print({len(i):i for i in month_list}) price_dict = {'milk':40, 'meat':250, 'rice':80, 'wheat':100} ### increasedPrice = Rs. 30 per item ##di = {k:v+30 for k,v in price_dict.items()} ##print(di) # ---------------------------------------------------------- ##Tbl = {i:{j:i*j for j in range(1,11)}for i in range(2,5)} ##print(Tbl) # ---------------------------------------------------------- ##fruits = ["Apple", "Pineapple", "Pear", "Banana"] ## ##print(sorted(fruits)) ##print(sorted(fruits, reverse=True)) # ---------------------------------------------------------- list_of_tuples = [('m', 4),('z',1),('b',3),('n',7),('c',8),('a',10)] ##sorted_list = sorted(list_of_tuples) ##print(sorted_list) ####print(list_of_tuples[2][1]) ## ##z = lambda x: x[1] ##sorted_list = sorted(list_of_tuples, key = z) ##print(sorted_list) # ---------------------------------------------------------- ##fruits = ["Apple", "Pineapple", "Pear", "Banana"] ##new_li = sorted(fruits, key = len) ##print(new_li) # ---------------------------------------------------------- ##data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}] ##li = sorted(data, key = lambda x:x['age'] ) ##print(li) # ---------------------------------------------------------- ## ##words = ['banana', 'kiwi', 'Raspberry', 'apple'] ##words.sort(key = len, reverse = True) ##print(words) https://www.geeksforgeeks.org/python-dictionary-comprehension/?authuser=0https://docs.python.org/3/howto/sorting.html?authuser=0https://www.geeksforgeeks.org/filter-in-python/?authuser=0https://www.geeksforgeeks.org/reduce-in-python/?authuser=013 Septhome.py#Q. Sort the people list by the length of each # person's name in descending order.(use sort function ) people = [ {'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Ana', 'age': 25, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}, {'name': 'Diana', 'age': 28, 'city': 'Miami'} ] ##people.sort(key = lambda person: len(person["name"])) ##print(people) # -------------------------------------------------------------------- #Q. sort the given list of items on the basis of their prices in ## descending order. ##items = [{'product': 'Book', 'price': 15.99}, ## {'product': 'Laptop', 'price': 999.99}, ## {'product': 'Pen', 'price': 1.99}] ## ##z = lambda x: x["price"] ##items.sort(key = z, reverse = True) ##print(items) OS.py##import os ##print(dir(os)) ##print(os.listdir()) ##print(os.getcwd()) ##print(os.chdir()) ##os.mkdir("hello") ##os.rename("hello.txt", "hi.txt") ##os.remove("hi.txt") # ---------------------------- import os ## ##print(os.getcwd()) os.chdir(r"C:\Users\hm\Desktop\\") print(os.getcwd()) print(os.listdir()) ##os.mkdir("hello1") ##os.rename("friday.txt", "saturday.txt") ##os.remove("saturday.txt")file_handling.py##variable = open('text.txt','r') ##print(variable.read()) ##variable.close() ##var = open('text.txt', 'a') ##var.write("hello") ##var.close() ## ##var_1 = open('text.txt', 'r') ##print(var_1.read()) ##var_1.close() ##var3 = open('text.txt', 'w') ##var3.write('ello') ##var3.close() ##var4 = open('text.txt', 'r') ##print(var4.read()) ##var4.close() ##var6 = open('text.txt', 'w') ##var6.write('new text') ##var6.close() ## ##var4 = open('text.txt', 'r') ##print(var4.read()) ##var4.close() # ------------------------------------------------------------- ##with open('text.txt','r') as variable: ## print(variable.read()) ##with open('text.txt','a') as variable: ## print('\n') ## variable.write('\n') ## variable.write('baby') ## print('\n') ## ##with open('text.txt','r') as variable: ## print(variable.read()) # ------------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------------ ##read(): Reads the whole file as a single string. ##use read() if you want the entire file content in one go. ##readline(): Reads one line at a time from the file. ##Useful when you want to process each line individually and maintain the line structure. ##readlines(): Reads all lines from the file and returns them as a list of strings. ##Useful when you want to process each line individually and maintain the line structure. # ---------------------------------------------------------------------------------------- ##with open('text.txt', 'r') as a: ## print(a.read()) with open('text.txt', 'r') as a: lines = a.readlines() cleaned_list = [line.strip() for line in lines] print(cleaned_list) https://www.w3schools.com/python/module_os.asp?ref=escape.tech&authuser=0https://www.geeksforgeeks.org/file-handling-python/?authuser=0Assignment_3.txt# Python Assignment 3 [20 m.m] #Q.1, Write a python prgram to list of cubes till a given number # using map function. (2 marks) #Q.2, Write a Python program which selects and prints (as a list) ## all the strings of length greater than 4 from a list of ## strings using filter function and lambda. (2 marks) strings = ['alexander','joe','tiffany','ana','max','george'] #Q.3, Write a Python print the factorial of a given number by using # reduce function. (2 marks) #Q.4, Write a Python program which converts all the elements of ## given list into string datatype using map function. (2 marks) alist = [1,2,3,4,5,6,7,8,9,10] #Q.5 Write a Python code to filter out the numbers from the given list that are greater # than 20. (2 marks) numbers = [12, 35, 7, 64, 22, 17] #Q.6, Write a Python program which converts a list of integers into ## dictionary such that keys of the dictionary are the elements ## of the list and the values are square of these elements but ## this is done only for those elements which are even. ## Use dictionary comprehension. (2 marks) blist = [1,2,3,4,5,6,7,8,9,10] Q.7, Write a Python program which multiplies the corresponding # elements of two lists and forms a list of these products . # Use map function. (2 marks) Clist = [1,2,3,4,5] Dlist = [1,2,3,4,5] #Q.8, Write a program to filter out all the numbers from the given list and ## the calculate the sum of all these numbers. (Use filter and reduce) (3 marks) li = ['Hello', 12, True, '92', ' ', 'Morning', 45, '@'] #Q.9, Write a Python Program to check which of the numbers in a # given list are Prime Numbers, use filter function (3 marks) givenList = [2,3,4,5,6,7,8,9]16 SeptExceptionHandling.py# -------------- Exception Handling -------------- # An exception in Python is an incident that happens while # executing a program. When a Python program meets an error, it # stops the execution of the rest of the program. When a Python # code comes across a condition it can't handle, it raises # an exception. # In Python, we catch exceptions and handle them using try and # except code blocks. The try clause contains the code that # can raise an exception, while the except clause contains the # code lines that handle the exception. # There is another block finally that is optional and is used # for code that must be executed regardless of whether an # exception occurred or not. # ---------------------------------------------------- # any number divisible by zero raise a zero division error # and the error can be handled by raising an exception ##num1 = int(input("Enter a number: ")) ##num2 = int(input("Enter another number: ")) ## ##try: ## print(num1/num2) ## ##except Exception as e: ## print("This operation is incorrect :", e) # ------------------------------------------------------- ##n1 = int(input("enter a number: ")) ##n2 = int(input("enter a number: ")) ## ##try: ## print(n1/n2) ## ##except ZeroDivisionError as error: ## print("incorrect programme", error) ## ##print("Programme terminated") # ------------------------------------------------------- ##num1 = input("enter 1st num: ") ##num2 = input("enter 2nd num: ") ## ##try: ## print("Start of a program") ## print(int(num1)/int(num2)) ## ##except Exception as e: ## print("This is invalid :", e) ## ##finally: ## print("End of Program") ##print("Program Terminated") # ---------------------------------------------------------- ##def weight(n): ## try: ## return int(n) ## except Exception as ex: ## print(ex) ## ##w = weight('ten pounds') ##print(w) # ---------------------------------------------------------- def weight(n): try: return int(n) except ValueError as ex: print('value error',ex) w = weight('10') print(w)ExceptionHandling (2).py##----------Exceptional handling------------------------- # Different types of exceptions in python: # SyntaxError, TypeError, NameError, IndexError, KeyError, ValueError, AttributeError, #IOError, ZeroDivisionError, ImportError, RuntimeError, OSError and more. # Q.1 - Write a Python function that divides two numbers and handles the division by #zero exception. def divide(num1, num2): try: result = num1 / num2 except ZeroDivisionError: return "Error: Division by zero is not allowed." except Exception as e: return f"An unexpected error occurred: {e}" else: return result print(divide(10, 2)) print(divide(10, 0)) # --------------------------------------------------------------------------------------------- # Q.2 - Write a Python function that reads from a file and handles the file not found exception. def find_file(file_path): try: with open(file_path, 'r') as file: content = file.read() except FileNotFoundError: return "Error: File not found." except Exception as e: return f"An unexpected error occurred: {e}" else: return content print(find_file('dummy.txt') ) print(find_file('hello.txt')) # --------------------------------------------------------------------------------------------- # Q.3 - Write a Python function that takes a string and converts it to an integer. # Handle the case where the conversion fails due to invalid input. num = ('123') num = ('abc') try: print(int(num)) except ValueError: print( "Error: Invalid input. Cannot convert to integer.") except Exception as e: print( f"An unexpected error occurred: {e}") # --------------------------------------------------------------------------------------------- # Q.4 - Write a Python function that retrieves an element from a list by its index. Handle the case where the index is out of range. def get_element(lst, index): try: print( lst[index]) except IndexError: print( "Error: Index is out of range.") except Exception as e: print( f"An unexpected error occurred: {e}") my_list = [1, 2, 3, 4] get_element(my_list, 2) get_element(my_list, 10) # --------------------------------------------------------------------------------------------- # Q.5 - Write a Python function that performs multiple operations: division, file reading, and string conversion. Handle multiple types of exceptions that may arise. def multiple_error(num1, num2, file_path, s): try: division_result = num1 / num2 with open(file_path, 'r') as file: file_content = file.read() integer_value = int(s) except ZeroDivisionError: print( "Error: Division by zero is not allowed.") except FileNotFoundError: print( "Error: The file was not found.") except ValueError: print( "Error: Invalid input for integer conversion.") except Exception as e: print( f"An unexpected error occurred: {e}") else: print( { "division_result": division_result, "file_content": file_content, "integer_value": integer_value }) multiple_error(10, 2, 'existing_file.txt', '123') multiple_error(10, 0, 'non_existent_file.txt', 'abc')home.py##num1 = int(input("enter a number: ")) ##num2 = int(input("enter a number: ")) ## ##try: ## print(num1/num2) ## ##except Exception as e: ## print("incorrect programme",e) ## ##finally: ## print("End of Program") ## ##print("hello world") # ---------------------------------------------------- ##def weight(n): ## try: ## return int(n) ## except ValueError as ex: ## return(ex) ## ##w = weight('10') ##print(w) ## # ---------------------------------------------------- ##def divide(num1, num2): ## try: ## result = num1 / num2 ## except ZeroDivisionError: ## return "Error: Division by zero is not allowed." ## except Exception as e: ## return f"An unexpected error occurred: {e}" ## else: ## return result ####print(divide(10, 2)) ##print(divide(10, 'a')) # ---------------------------------------------------- ## ##import math ## ####print(dir(math)) ## ##print(math.factorial(5)) ## ##result = math.sqrt(16) ##print(result) ## ## ##print(math.pi) ## ##a, b = 60, 48 ##result = math.gcd(a,b) ##print(f"GCD of {a} and {b} is {result}") # ---------------------------------------------------- ##li = [2,3,4,5,6] ## ##it = iter(li) ##print(it) ## ##print(it.__next__()) ## ##print(it.__next__()) ##print(next(it)) ## ##for i in it: ## print(i) ## ##print(next(it))https://www.w3schools.com/python/python_try_except.asp?authuser=017 Septiterators_generators.py# ----------------- Iterables ------------------ # An Iterable is basically an object that any user can # iterate over. ex- a list or a tuple ##alist = [2,4,6,8,10] ##print(alist) ##print(alist[2]) ##print(alist[4]) ##for i in alist: ## print(i) # ----------------- Iterators ------------------ # An Iterator is an object that helps a user in iterating over another object. #An iterator is generated when we pass an # iterable to iter() method. It gives one value at a time. # iter( ) converts an iterable into an iterator. ##x = iter(alist) ##print(x) # returns an iterator object # for accessing values from an iterator we use __next__() # __next__() method is used for iterating. It returns the next # item available for iteration. ##print(x.__next__()) # "next()" is same as "__next__()" ##print(list(x)) ##print(next(x)) ##print(next(x)) ##print(next(x)) ##print(next(x)) ##print(next(x)) #this will raise a stop iteration error # for loop can be used to access it ##for i in x: # iterator prints a value only once ## print(i) # loop will start from second value ## ##print(next(x)) # -------------------- GENERATOR -------------------- # A generator is a special type of iterator that is defined using a function with yield # statements. Generators simplify iterator creation by handling the iterator protocol # Generator creates iterator ##def func(): ## yield "Hello" ## ## ##string = func() ####print(string) #this will return a generator object ## ##print(string.__next__()) ### or ##print(next(string)) # this returns the actual value #------------------------------------------------------------- def num(): yield 1 # we can use multiple yield in generator yield 2 yield 3 var = num() print(var.__next__()) print(var.__next__()) for i in var: print(i) # ------------------------------------------------------------- def square(n): sq = n*n yield sq SQUARE = (square(2)) print(SQUARE) print(SQUARE.__next__()) #-------------------------------------------------------------- ##def squares(): ## ## for i in range(2,10): ## sq = i*i ## yield sq ## ## ##square = squares() ##print(square) #print(square.__next__()) #print(square.__next__()) ##squareList =[] ##for i in square: ## squareList.append(i) ## ##print(squareList)functions(3).py# Callback Function: #A callback function in Python is a function that is passed as an argument to another #function and is executed inside that function. def function_1(n): return "i am function 1 " + n() def function_2(): return "i am function 2" result = function_1(function_2) print(result) # ------------------------------------------------------------------------------- ##def greet(name, callback): ## message = f"Hello, {name}!" ## return callback(message) ## ##def print_message(msg): ## print(msg) ## ##greet("Alice", print_message) # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- #Nested Function: # A nested function is a function defined inside another function. ##def outer(): ## x = 12 ## def inner(): ## print(x) ## ## inner() ## ##outer() # ------------------------------------------------------------------------------- ##def greet(name): ## def say_hello(): ## print(f"Hello, {name}!") ## ## say_hello() ## ##greet("Alice") # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- # Closure: #A closure is a function that retains access to the variables from its enclosing scope, even #after the enclosing function has finished executing. #For innerFunction to be a closure, it needs to be returned from outerFunction and then #called after outerFunction has finished executing. ##def outer_function(x): ## def inner_function(y): ## return x + y ## return inner_function ## ##result = outer_function(10) ##print(result(5)) # ------------------------------------------------------------------------------- ##def my_func(value): ## def multiply(number): ## return number * value ## return multiply ## ## ##result = my_func(3) ## ##print(result(5)) ##print(result(10))home.py##num1 = int(input("enter a number: ")) ##num2 = int(input("enter a number: ")) ## ##try: ## print(num1/num2) ## ##except Exception as e: ## print("incorrect programme",e) ## ##finally: ## print("End of Program") ## ##print("hello world") # ---------------------------------------------------- ##def weight(n): ## try: ## return int(n) ## except ValueError as ex: ## return(ex) ## ##w = weight('ten') ##print(w) ## # ---------------------------------------------------- def divide(num1, num2): try: result = num1 / num2 except ZeroDivisionError: return "Error: Division by zero is not allowed." except Exception as e: return f"An unexpected error occurred: {e}" else: return result ##print(divide(10, 2)) ##print(divide(10, 'a')) # ---------------------------------------------------- # ---------------------------------------------------- ##li = [2,3,4,5,6] #### ##it = iter(li) ####print(it) #### ##print(it.__next__()) #### ##print(it.__next__()) ##print(next(it)) #### ##for i in it: ## print(i) #### ##print(next(it)) # ---------------------------------------------------- ##def func(): ## yield "Hello" ## yield "words" ## ## ##string = func() ##print(string) #this will return a generator object ## ##print(string.__next__()) ## ##print(next(string)) # ---------------------------------------------------- ##def my_func(n): ## return("i am a function", n()) ## ##def my_func_1(): ## return("i am a function 2") ## ##print(my_func(my_func_1)) # ---------------------------------------------------- ##def greet(name, callback): ## message = f"Hello, {name}!" ## return callback(message) ## ##def print_message(msg): ## print(msg) ## ##greet("Alice", print_message) # ---------------------------------------------------- ##def outer(): ## x = 12 ## def inner(): ## print(x) ## ## inner() ## ##outer() ####inner() # ---------------------------------------------------- ##def greet(name): ## def say_hello(): ## print(f"Hello, {name}!") ## ## say_hello() ## ##greet("Alice") # ---------------------------------------------------- ##def outer_function(x): ## def inner_function(y): ## return x + y ## return inner_function ## ##result = outer_function(10) ##print(result(5)) # ---------------------------------------------------- ##def Greet(n): ## def Greet_2(): ## return f"Hello {n}" ## return Greet_2 ## ##var = Greet("Ana") ##print(var())24 Septclasses_&_objects.pyclass Human: name = 'Ben' age = 20 address = 'Bhopal' def Breath(): return 'A Human breathes' obj = Human() print(Human.age) print(Human.Breath()) # -------------------------------------------------------------------- class Human: def __init__(self, name, age, ad): self.name = name self.age = age self.address = ad obj1 = Human('Emma', 32, 'Bhopal') print(obj1.name) obj2 = Human('Tom') print(obj2.name) # -------------------------------------------------------------------------- class Human: def __init__(self, name, age, address): self.name = name self.age = age self.address = address def __str__(self): return f"I am a Human {self.name}, I am {self.age} years old, and i live in {self.address}" obj = Human("Emma", 13, "Bhopal") print(obj) ##print(Human.Breath()) # -------------------------------------------------------------------------- ##class place: ## ## def __init__(self, name, famous): ## self.n = name ## self.f = famous ## ## def __str__(self): ## return f"{self.n} is famous for {self.f}" ## ##p1 = place('Bhopal','Lakes') ##print(p1) # -------------------------------------------------------------------------- # Practice Question: # Q. Create a Car class with attributes brand, model, and year. Add a method to display the car's full description.Inheritance.py# ----------------- INHERITANCE ----------------- # It is a property of a class to inherit all the properties of # another class # here we are defining a class A as parent class ## ##class A: ## ## def method1(self): ## print("This is method1") ## ## def method2(self): ## print("This is method2") # class B is the sub class/child class of class A # This is called multilevel inheritance ##class B(A): ## ## def method3(self): ## print("This is method3") ##obj1 = A() ##obj1.method1() ##obj1.method2() ##obj3 = B() ##obj3.method1() #this will raise an error unless you inherit ## #class A to B ##obj3.method3() ##o = A() #this will raise and error ##o.method3() # it can be concluded that child class can inherit all the # properties of parent/super class but a parent cannot inherit # all the properties of child classoperatorOverloading.py# --------------- OPERATOR OVERLOADING --------------- # Operator overloading is used to change the behavior of an # existing operator by redefining a special function that # is invoked when the operator is used with the objects. class X: def __init__(self, name, age, place): self.name = name self.age = age self.place = place def __add__(self,other): print(self.name + other.name) print(self.age + other.age) print(self.place + other.place) o1 = X('Sam', 25, 'Japan') o2 = X('Pam', 29, 'Germany') o3 = o1 + o2 #this will raise an error # to overcome this we can use __add__() for operator overloading # When we use + operator, the magic method __add__ is # automatically invokedmethodOverloading.py## ------------- METHOD OVERLOADING/OVERRIDING ------------------- class xyz(): def add(self,a,b): return a + b ## def add(self,a,b,c): ## return a + b + c obj = xyz() ##print(obj.add(1,2)) ##print(obj.add(1,2,3)) #------------------------------------------------------ ##class wxyz(): ## def add(self,*args): #Arbitrary Number of Arguments ## total = 0 ## for i in args: ## total = total + i ## return total ## ##obj1 = wxyz() ##print(obj1.add(1,2,3,4,5)) ##print(obj1.add(55,56,78,74,100)) #--------------------------------------------------------- # Method Overriding : class father: def eat(self): print("i eat healthy food") def work(self): print("i go to office") class Son(father): def eat(self): print("i eat junk food") super().eat() objSon = Son() objSon.eat() # ---------------------------------------------------------------------- class Parent: def display(self): print("Hello1") def display(self,astring): print("Hi!!",astring) class Child(Parent): def display(self): print("Hello2") p = Parent() ##p.display() ##p.display("There") ##c = Child() ##c.display()duck_typing.py# Duck Typing: # In Python,where the type of an object is determined by its behavior (methods and properties) # rather than its explicit type. # "If it looks like a duck and quacks like a duck, it must be a duck." class Bird: def fly(self): return "a bird flies in the sky" class AirPlane: def fly(self): return "AirPlane flies in the sky" def make_it_fly(flyable_object): return flyable_object.fly() sparrow = Bird() jet = AirPlane() make_it_fly(sparrow) make_it_fly(jet) #Here, both Bird and Airplane have a fly() method, and the make_it_fly() function #works with any object that has a fly() method, regardless of the object's actual class.abstractClass.py# Abstract Class - An abstract class is a class that cannot be # instantiated directly but it can be inherited. # Abstract methods, on the other hand, are methods declared # within an abstract class but without any implementation. class Vehicle: def drive(self): pass obj = Vehicle() ##print(obj) # this is working normally as Vahicle isn't an abstract class yet #-------------------------- from abc import ABC, abstractmethod #abstract base classes class Vehicle(ABC): @abstractmethod def drive(self): pass ##obj = Vehicle() ##print(obj) class Car(Vehicle): def drive(self): return "Car is being driven on the road." class Airplane(Vehicle): def drive(self): return "The Airplane is flying in the sky." objCar = Car() print(objCar.drive()) objAirplane = Airplane() print(objAirplane.drive())home .py# callbacks : ##def function_1(n): ## return "i am function 1 " + n() ## ##def function_2(): ## return "i am function 2" ## ##result = function_1(function_2) ##print(result) # nested functions: ##def outer(): ## x = 12 ## def inner(): ## print(x) ## ## inner() ## ##outer() ##def greet(name): ## def say_hello(): ## print(f"Hello, {name}!") ## ## say_hello() ## ##greet("Alice") # closures: ##def outer_function(x): ## def inner_function(y): ## return y**x ## return inner_function ## ##result = outer_function(3) ##print(result(5)) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ ##def decorator(func): ## def wrapper(): ## ## print("Hello World") ## ## func() ## ## print("thanks for using decorator") ## return wrapper ## ##@decorator ##def greet(): ## print("have a nice day!") ## ##greet() # ----------------------------------------------------------------- ## ##def add_sprinkle(cake): ## def wrapper(): ## print("sprinkles sprinkled!!") ## ## cake() ## ## return wrapper ## ##@add_sprinkle ##def cake1(): ## print("here's your chocolate cake") ## ## ##@add_sprinkle ##def cake2(): ## print("here's your vanilla cake") ## ##cake1() ##print() ##cake2() # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # OOP: ##class Human: ## def __init__(self, name, age, ad = "India"): ## self.name = name ## self.age = age ## self.address = ad ## ## def __str__(self): ## return f"the name of the human is {self.name}, the age is {self.age}, the adress is {self.address}" ## ##obj = Human("Ron", 80, "bhopal") ##print(obj) ##print(obj.age) ## ##obj2 = Human("Emily", 76,"delhi") ##print(obj2.name) ## ##obj3 = Human("ana", 20) ##print(obj3.adress) # --------------------------------------------------------------------------------- # Inheritance: ##class Parent: ## ## def method_1(self): ## print("i am a method 1") ## ## def method_2(self): ## print("i am a method 2") ## ##class Child(Parent): ## ## def method_3(self): ## print("i am a method 3") ## ##obj = Child() ##obj.method_1() ## ##obj_Parent = Parent() ##obj_Parent.method_3() # ------------------------------------------------------------------------------- # Magic Methods: # __add__() # __sub__() # __mul__() ##a = 4 ##b = 2 ##print(a + b) ## __add__() ##print(int.__add__(2,3)) ####__sub__() ####__mul__() ## ##a = 'hello' ##b = 'world' ## ##print(str.__add__(a,b)) # ----------------------------------------------------------------------- # Operator Overloading: ##class X: ## def __init__(self, a,b): ## self.num1 = a ## self.num2 = b ## ## def __add__(self,other): ## print(self.num1 + other.num1) ## print(self.num2 + other.num2) ## ##obj1 = X(2,3) ##obj2 = X(5,5) ##obj3 = obj1 + obj2 # ------------------------------------------------------------------------------------ ##class X: ## ## def __init__(self, name, age, place): ## self.name = name ## self.age = age ## self.place = place ## ## def __add__(self,other): ## print(self.name + other.name) ## print(self.age + other.age) ## print(self.place + other.place) ## ##o1 = X('Sam', 25, 'Japan') ##o2 = X('Pam', 29, 'Germany') ##o3 = o1 + o2 # ------------------------------------------------------------- # method overloading: ##class X: ## def add(self, a, b): ## return a + b ## ## def add(self, a, b, c= 0): ## return a + b + c ## ##obj = X() ##print(obj.add(2,4)) ##class X: ## def add(self, *args): ## total = 0 ## for i in args: ## total += i ## return total ## ##obj = X() ##print(obj.add(2,3,4,5,6)) # ------------------------------------------------------------- # ------------------------------------------------------------- # method overriding: ##class father: ## def eat(self): ## print("i eat healthy food") ## ## def work(self): ## print("i go to office") ## ##class Son(father): ## def eat(self): ## print("i eat junk food") ## super().eat() ## ## ## ##objSon = Son() ##objSon.eat() # ---------------------------------------------------------------- ##class father: ## def __init__(self, name, house): ## self.name = name ## self.house = house ## ##class Son(father): ## pass ## ##objDad = father("hanry","1 house") ##print(objDad.name) ## ##obj = Son("jerry", "a house") ##print(obj.name) # ---------------------------------------------------------- ##class Parent: ## ## def display(self): ## print("Hello1") ## ## def display(self,a): ## print("Hi!!",a) ## ##class Child(Parent): ## def display(self): ## print("Hello2") ##p = Parent() ####p.display() ##p.display("There") ##c = Child() ##c.display() ####c.display("there") # ------------------------------------------------------------------- # Practice Question: #Q. Define a class named Book with three attributes: title, author & pages. # Implement a method called description() that returns a string representation # of the class. ##class Book: ## def __init__(self, title, author,pages): ## self.title = title ## self.author = author ## self.pages = pages ## ## def description(self): ## return f"the book is {self.title}, author is {self.author}& pages are {self.pages}" ## ##obj = Book("Atomic Habits","James Clear",300) ##print(obj.description()) # ----------------------------------------------------------- ##class Parent: ## ## def display(self): ## print("Hello1") ## ## def display(self,a): ## print("Hi!!",a) ## ##class Child(Parent): ## def display(self,a = None): ## print("Hello2") ## super().display(a) ## ## ##c = Child() ##c.display() ##c.display("there") # -------------------------------------------------------------------------------------------- # Q. Define a class named Student with three attributes: name, student_id, # and grade. # Implement a method called get_info() that returns a string representation # of the class. # Then, define a subclass named Undergraduate that inherits from Student # and includes two additional attributes: major and year. # Implement a method called get_details() that returns a string # representation of the Undergraduate class, including all attributes. ##class Student: ## def __init__(self, name, st_id, grade): ## self.name = name ## self.student_id = st_id ## self.grade = grade ## ## def get_info(): ## return "hgjhgjhg" ## ##class Undergraduate(Student): ## def __init__(self,name, st_id, grade, major,year): ## super().__init__(name, st_id, grade) ## self.major = major ## self.year = year ## ## def get_details(self): ## return f"name is {self.name}, id is {self.student_id}, grade is {self.grade}, the major is {self.major} & year is {self.year}" ## ## ##Ug = Undergraduate("Emily", 23, "A", "CS", 2022) ##print(Ug.get_details()) # ---------------------------------------------------------------------- # duck typing: ##class Bird: ## def fly(self): ## return "a bird flies in the sky" ## ##class AirPlane: ## def fly(self): ## return "AirPlane flies in the sky" ## ##class Glass: ## def useful_vessel(self): ## return "glasses contain water" ## ##def make_it_fly(obj): ## return obj.fly() ## ##sparrow = Bird() ##jet = AirPlane() ##objGlass = Glass() ##print(make_it_fly(sparrow)) ##print(make_it_fly(jet)) ##print(make_it_fly(objGlass)) # ---------------------------------------------------------------------------------- #abstract class: from abc import ABC, abstractmethod #abstract base classes class Vehicle(ABC): @abstractmethod def drive(self): pass class Car(Vehicle): def drive(self): print("Cars are being driven on road") C = Car() C.drive() ##obj = Vehicle() ##print(obj)https://www.geeksforgeeks.org/python-oops-concepts/?authuser=025 Septaccess modifiers.py# ------------------- Access Modifiers ------------------- #Access Modifiers in Python are used to control the visibility and accessibility of class #attributes and methods. #There are three access modifiers: public, private & protected. #they help encapsulate data and maintain control over how attributes and methods #are accessed and modified. # To make an instance variable protected, use prefix _ # (single underscore) to it. # To make an instance variable private, use prefix __ # (double underscore) to it. class Animal: def __init__(self, name): self._name = name class Cat(Animal): def meow(self): return f"{self._name} says Meow!" my_cat = Cat("Kitty") ##print(my_cat.meow()) ## ##print(my_cat._name) # possible but not recommended ## ##Animal = Animal("hola") ##print(Animal._name) ##my_cat._name = "snowie" ##print(my_cat.meow()) # again, not a good practice # -------------------------------------------------------------------- class BankAccount: def __init__(self, balance): self.__balance = balance # Private attribute def get_balance(self): #Public method to access private attribute return self.__balance account = BankAccount(1000) print(account.get_balance()) ##print(account.__balance) # not possible to access a private attribute directly account.__balance = 2000 #not possible print(account.get_balance()) # -------------------------------------------------------------------- class Employee: def __init__(self, name, age, salary): self._name = name # protected instance attribute self.__age = age # private instance attribute self.salary = salary @property def ageMethod(self): return self.__age emp = Employee("Ana", 30, 40000) ##print(emp.__age) #gives an error print(emp.ageMethod) # accessing age using getter ##emp.ageMethod = 21 ##print(emp.ageMethod)home .py# OOP: ##class Human: ## def __init__(self, name, age, ad = "India"): ## self.name = name ## self.age = age ## self.address = ad ## ## def __str__(self): ## return f"the name of the human is {self.name}, the age is {self.age}, the adress is {self.address}" ## ##obj = Human("Ron", 80, "bhopal") ##print(obj) ##print(obj.age) ## ##obj2 = Human("Emily", 76,"delhi") ##print(obj2.name) ## ##obj3 = Human("ana", 20) ##print(obj3.adress) # --------------------------------------------------------------------------------- # Inheritance: ##class Parent: ## ## def method_1(self): ## print("i am a method 1") ## ## def method_2(self): ## print("i am a method 2") ## ##class Child(Parent): ## ## def method_3(self): ## print("i am a method 3") ## ##obj = Child() ##obj.method_1() ## ##obj_Parent = Parent() ##obj_Parent.method_3() # ------------------------------------------------------------------------------- # Magic Methods: # __add__() # __sub__() # __mul__() ##a = 4 ##b = 2 ##print(a + b) ## __add__() ##print(int.__add__(2,3)) ####__sub__() ####__mul__() ## ##a = 'hello' ##b = 'world' ## ##print(str.__add__(a,b)) # ----------------------------------------------------------------------- # Operator Overloading: ##class X: ## def __init__(self, a,b): ## self.num1 = a ## self.num2 = b ## ## def __add__(self,other): ## print(self.num1 + other.num1) ## print(self.num2 + other.num2) ## ##obj1 = X(2,3) ##obj2 = X(5,5) ##obj3 = obj1 + obj2 # ------------------------------------------------------------------------------------ ##class X: ## ## def __init__(self, name, age, place): ## self.name = name ## self.age = age ## self.place = place ## ## def __add__(self,other): ## print(self.name + other.name) ## print(self.age + other.age) ## print(self.place + other.place) ## ##o1 = X('Sam', 25, 'Japan') ##o2 = X('Pam', 29, 'Germany') ##o3 = o1 + o2 # ------------------------------------------------------------- # method overloading: ##class X: ## def add(self, a, b): ## return a + b ## ## def add(self, a, b, c= 0): ## return a + b + c ## ##obj = X() ##print(obj.add(2,4)) ##class X: ## def add(self, *args): ## total = 0 ## for i in args: ## total += i ## return total ## ##obj = X() ##print(obj.add(2,3,4,5,6)) # ------------------------------------------------------------- # ------------------------------------------------------------- # method overriding: ##class father: ## def eat(self): ## print("i eat healthy food") ## ## def work(self): ## print("i go to office") ## ##class Son(father): ## def eat(self): ## print("i eat junk food") ## super().eat() ## ## ## ##objSon = Son() ##objSon.eat() # ---------------------------------------------------------------- ##class father: ## def __init__(self, name, house): ## self.name = name ## self.house = house ## ##class Son(father): ## pass ## ##objDad = father("hanry","1 house") ##print(objDad.name) ## ##obj = Son("jerry", "a house") ##print(obj.name) # ---------------------------------------------------------- ##class Parent: ## ## def display(self): ## print("Hello1") ## ## def display(self,a): ## print("Hi!!",a) ## ##class Child(Parent): ## def display(self): ## print("Hello2") ##p = Parent() ####p.display() ##p.display("There") ##c = Child() ##c.display() ####c.display("there") # ------------------------------------------------------------------- # Practice Question: #Q. Define a class named Book with three attributes: title, author & pages. # Implement a method called description() that returns a string representation # of the class. ##class Book: ## def __init__(self, title, author,pages): ## self.title = title ## self.author = author ## self.pages = pages ## ## def description(self): ## return f"the book is {self.title}, author is {self.author}& pages are {self.pages}" ## ##obj = Book("Atomic Habits","James Clear",300) ##print(obj.description()) # ----------------------------------------------------------- ##class Parent: ## ## def display(self): ## print("Hello1") ## ## def display(self,a): ## print("Hi!!",a) ## ##class Child(Parent): ## def display(self,a = None): ## print("Hello2") ## super().display(a) ## ## ##c = Child() ##c.display() ##c.display("there") # -------------------------------------------------------------------------------------------- # Q. Define a class named Student with three attributes: name, student_id, # and grade. # Implement a method called get_info() that returns a string representation # of the class. # Then, define a subclass named Undergraduate that inherits from Student # and includes two additional attributes: major and year. # Implement a method called get_details() that returns a string # representation of the Undergraduate class, including all attributes. ##class Student: ## def __init__(self, name, st_id, grade): ## self.name = name ## self.student_id = st_id ## self.grade = grade ## ## def get_info(): ## return "hgjhgjhg" ## ##class Undergraduate(Student): ## def __init__(self,name, st_id, grade, major,year): ## super().__init__(name, st_id, grade) ## self.major = major ## self.year = year ## ## def get_details(self): ## return f"name is {self.name}, id is {self.student_id}, grade is {self.grade}, the major is {self.major} & year is {self.year}" ## ## ##Ug = Undergraduate("Emily", 23, "A", "CS", 2022) ##print(Ug.get_details()) # ---------------------------------------------------------------------- # duck typing: ##class Bird: ## def fly(self): ## return "a bird flies in the sky" ## ##class AirPlane: ## def fly(self): ## return "AirPlane flies in the sky" #### ##class Glass: ## def useful_vessel(self): ## return "glasses contain water" #### ##def make_it_fly(obj): ## return obj.fly() #### ##sparrow = Bird() ##jet = AirPlane() ##objGlass = Glass() ##print(make_it_fly(sparrow)) ##print(make_it_fly(jet)) ##print(make_it_fly(objGlass)) # ---------------------------------------------------------------------------------- #abstract class: ##from abc import ABC, abstractmethod #abstract base classes ## ##class Vehicle(ABC): ## @abstractmethod ## def drive(self): ## pass ## ##class Car(Vehicle): ## ## def my_func(self): ## print("hdsj") ## ## def drive(self): ## print("Cars are being driven on road") ## ##C = Car() ##C.my_func() ##C.drive() ##obj = Vehicle() ##print(obj) # ------------------------------------------------------------------------------ # Practice Questions: # Q. Define a class Vehicle with an a perameter : name. and a method called description() # This method should return a string: "This is a vehicle." # # Then, create a class named Car that inherits from Vehicle, and implements the description() # method and returns a string: "This is a car." # #Also, create a class named Motorcycle that also inherits from Vehicle, and implements a #the description() method, returning a string: "This is a motorcycle." # # Finally, create instances of Car and Motorcycle, and call their description() methods # to demonstrate method overriding. ##class Vehicle: ## def __init__(self, name): ## self.name = name ## ## def description(self): ## return "This is a vehicle." ## ##class Car(Vehicle): ## def description(self): ## return "This is a car." ## ##class Motorcycle(Vehicle): ## def description(self): ## return "This is a bike" ## ##V= Vehicle("hgh") ##print(V.description()) ##objCar = Car("hjh") ##print(objCar.description()) # Q. Define an abstract class named Vehicle with two methods: move() & fuel_type() # Then, create a class named Car that inherits from Vehicle, and has three attribute: # Brand, model, and fuel. # Implement the move() method that returns "The car drives on the road." # Implement the fuel_type() method that returns the fuel type. # Also, create a class named Bicycle that also inherits from Vehicle, and has a #attribue: brand # Implement the move() method that returns "The bicycle pedals on the road." # Implement the fuel_type() method that returns "human power." # # Finally, create instances of Car and Bicycle, and call their methods. ##from abc import ABC, abstractmethod ##class Vehicle(ABC): ## @abstractmethod ## def move(self): ## pass ## @abstractmethod ## def fuel_type(self): ## pass ## ##class Car(Vehicle): ## def __init__(self,Brand, model,fuel): ## self.Brand = Brand ## self.model = model ## self.fuel = fuel ## def move(self): ## return "This is a car" ## def fuel_type(self): ## return f"{self.fuel}" ## ##C = Car("Audi","gdg","Petrol") ##print(C.move()) ##print(C.fuel_type()) # ---------------------------------------------------------- # Encapsulation: # access modifiers: # protected attributes: ##class Animal: ## def __init__(self, name): ## self._name = name #protected attribute ## ##class Cat(Animal): ## def meow(self): ## return f"{self._name} says Meow!" ## ##my_cat = Cat("Kitty") ##print(my_cat.meow()) ####print(my_cat._name) # possible but not recommended ## ##Animal = Animal("hola") ##print(Animal._name) ##my_cat._name = "snowie" ##print(my_cat.meow()) # again, not a good practice # --------------------------------------------------- # private attributes: ##class BankAccount: ## def __init__(self, balance): ## self.__balance = balance # Private attribute ## ## def get_balance(self): #Public method to access private attribute ## return self.__balance ##account = BankAccount(1000) ##print(account.__balance) # not possible to access a private attribute directly ####print(account.get_balance()) ## print(account._BankAccount__balance) # name mangling account._BankAccount__balance = 8000 print(account._BankAccount__balance)26 Septgetter_setter.py# ------------------ GETTER / SETTER ------------------ # Getter and Setter methods in python are used to provide read class Employee: def __init__(self, name = 'abc', age = 50, salary = 500): self.name = name self.__age = age self.__salary = salary @property def age(self): return self.__age @age.setter def age(self,value): self.__age = value @property def salary(self): return self.__salary @salary.setter def salary(self, value): self.__salary = value obj = Employee() print(obj.age) obj.age = '10' # this is raising an error as we haven't defined a setter yet print(obj.age) ##print(obj.__salary) print(obj.salary) print("Previous Salary:", obj.salary) obj.salary = 10 # now the salary can be updated, with the help of setter method. print("Updated Salary :",obj.salaryhome .py# RECURSION: ##def Greeting(): ## print("Hello World") ## ## Greeting() ## ##Greeting() ##def factorial(n): ## if n == 0 or n==1: ## return 1 ## ## return n * factorial(n-1) ## ##result = factorial(5) ##print(result) # ------------------------------------------------------------- # OOP Practive question: ##class Duck: ## def __init__(self, weight, wings): ## self.weight = weight ## self.wings = wings ## ## def fly(self): ## pass ## ## def quack(self): ## pass ## ##class Rubber_ducks(Duck): ## def details(self): ## print(f"Rubber duck: Weight {self.weight}, wings {self.wings}") ## ## def fly(self): ## print("I don't fly") ## ## def quack(self): ## print("I don't quack") # ---------------------------------------------------- # getter setter: ##class Employee: ## ## def __init__(self, name = 'abc', age = 50, salary = 500): ## self.name = name ## self.__age = age ## self.__salary = salary ## ## @property ## def age(self): ## return self.__age ## ## @age.setter ## def age(self,value): ## self.__age = value ## ## @property ## def salary(self): ## return self.__salary ## ## @salary.setter ## def salary(self, value): ## self.__salary = value ## ## ##obj = Employee() ## ##print(obj.salary) ##print("Previous Salary:", obj.salary) ## ##obj.salary = 10 ##print("Updated Salary :",obj.salary) # -------------------------------------------------------------------- # Practice Question : # Q. Define a class 'Book' with an private attribute: 'title'. Create a getter method # that returns the title, and a setter method that updates the title. # Then, create an instance of 'Book', use the setter to change the title, # and use the getter to print the updated title. # -------------------------------------------------------------------- # Regular Expressions: import re animalstr = 'cat rat mat bat cat sat Mat Cat pat hat fat' ##print(re.search('cat', animalstr)) ## ##print(re.findall('cat',animalstr)) ## ##print(re.findall('[cC]at', animalstr)) ## ##print(re.findall('[^bsmM]at', animalstr)) ## ##string = re.findall('[c-m]at',animalstr) ##print(string) ##string1 = 'earth revolves round the sun' ####n = re.compile('earth') ## ##finalStr = re.sub('earth', 'moon', string1) ## ##print(finalStr) ##string = "Here is \\stuff" ## ##searched_result = re.search(r"\\stuff", string) ##print(searched_result) randStr = "F.B.I. I.R.S. CIA Dr. Mr." ##search = re.search(".",randStr) ##print(search) print("Matches :",re.findall("\..\..\.", randStr))recursion.py# ------------------- RECURSION ------------------- # When a function calls itself it is known as recursion. # Recursive functions render the code look simple and effective. def greet(): print("Hello World") ## greet() greet() #------------------------------------------------------- # Factorial using recursion def factorial(n): if n ==0 or n ==1: return 1 return n* factorial(n-1) result = factorial(5) print(result)regex.py# ------------------ REGULAR EXPRESSIONS ------------------ # Regular Expressions allows us to search for a specific pattern # Regular expressions allows us to- # 1. Search for a specific string in a large amount of data # 2. Verify that a string has the proper format (Email, Phone) # 3. Find a string and replace it with another string # 4. Format data into the proper form import re animalstr = 'cat rat mat bat cat sat Mat Cat pat hat fat' # search returns first occurance of match object ##print(re.search('cat', animalstr)) # findall returns list of matches ##print(re.findall('cat',animalstr)) #[] accepts only one character ##print(re.findall('[cC]at', animalstr)) # Use ^ to denote any character except whatever characters are # between the brackets ##print(re.findall('[^bsmM]at', animalstr)) # printing a range of matches ##string = re.findall('[c-m]at',animalstr) ##print(string) # -------------- Replace All Matches -------------- # You can compile a regex into pattern objects which # provide additional methods # sub() replaces items that match the regex in the string ##string1 = 'earth revolves round the sun' ##n = re.compile('earth') #### ##finalStr = re.sub(n, 'moon', string1) ### substituting regex pattern in a string ##print(finalStr) # Another way of substituting ##a = re.compile('earth') ##match = a.sub('Saturn', string1) ##print(match) ##string1 = 'earth revolves round the sun' ##match = re.sub('earth', 'Saturn', string1) ##print(match) # ---------- Solving Backslash Problems ---------- # Regex use the backslash to designate special characters # and Python does the same inside strings which causes # issues ##print("\\stuff") string = "Here is \\stuff" ##searched_result = re.search("\\stuff", string) ##print(searched_result) ##searched_result = re.search("\\\\stuff", string) ##print(searched_result) ##searched_result = re.search(r"\\stuff", string) # using raw string ##print(searched_result) # ---------- Matching Any Character ---------- # . matches any character, but what if we # want to match a full stop. Backslash the full stop ##randStr = "F.B.I. I.R.S. CIA Dr. Mr." search = re.search(".",randStr) print(search) ##print("Matches :",re.findall("\..\..\.", randStr)) # ---------- Matching Whitespace ---------- # We can match many whitespace characters ##randStr = """This is a long ##string that goes ##on for many lines""" ## ##print(randStr) ## ### Remove newlines ##match = re.sub("\n", " ", randStr) ##print(match) https://www.programiz.com/python-programming/closure?authuser=0https://www.askpython.com/python/built-in-methods/callback-functions-in-python?authuser=0https://www.w3schools.com/python/gloss_python_function_recursion.asp?authuser=028 Septhome .py# static methods in oop: ##class X: ## @staticmethod ## def add(x,y): ## return x + y ## ##print(X.add(3,4)) # -------------------------------------------------------- # Regular Expressions: import re ##animalstr = 'cat rat mat bat cat sat Mat Cat pat hat fat' ## ##print(re.search('cat', animalstr)) ##print(re.findall('cat',animalstr)) ## ##print(re.findall('[cC]at', animalstr)) ## ##print(re.findall('[^bsmM]at', animalstr)) ## ##string = re.findall('[c-m]at',animalstr) ##print(string) ##string1 = 'earth revolves round the sun' ##n = re.compile('earth') ## ##finalStr = re.sub(n, 'moon', string1) ## ##print(finalStr) ##string = "Here is \\stuff" ## ##searched_result = re.search(r"\\stuff", string) ##print(searched_result) # \. --> searches an actual fullstop ##randStr = "F.B.I. I.R.S. CIA Dr. Mr." ## ##search = re.search(".",randStr) ##print(search) ## ##print("Matches :",re.findall("\..\..\.", randStr)) # -------------------------------------------------------------------------------- # file handling: ##open() --> opens your file ##close() --> closes the opened file ##read() --> returns all the lines within one string ##readline() --> returns data line by line ##readlines() --> returns list of string with open('text.txt', 'r') as var: print(var.read()) with open('text.txt', 'a') as var: var.write("hello") print("string added") with open('text.txt', 'r') as var: print(var.read())text.txthello world Hii2 Oct (Edited 2 Oct)Assignment.txt1 - (2 Marks) Write a Python program which searches for all the Phone numbers(Eg: 0755-4926545) in a given text and prints them without the area code. 2 - (2 Marks) Write a Python program which search the first occurrence of "it was good" and print start index and end index of the match. 3 - (2 Marks) Write a Python program which takes an input from the user and checks if the input is a valid company id . Company Id format - INV1234 (INV followed by number which is upto 4 digit long) 4 - (3 Marks) a) Write a Python program which searches for the word farmer in its singular and plural forms and prints the number of matches. The search should NOT be case sensitive. b) Write the above program for a Case Sensitive search. 5 - (3 Marks) Write a Python program which searches in a text file for all the occurrences of an entered text and then prints start indices of all the matches 6 - (4 Marks) Write a Python program which prints "Starts with a number " if a given text starts with a Number, prints "Ends with a number " if a given text ends with a Number, prints both the messages if both the cases are true and prints "Neither starts nor ends with a number" if both the cases are not true. This number can have any number of digits. 7 - (4 Marks) Write a Python program which reads a text file and makes the following changes: a) Removes all the special characters from the text. b) Removes all the new line characters from the text c) Removes all the words which have length two or less d) Replaces all the email Ids in the text with string -'EmailID'(Edited 3 Oct)regex.py# ------------------ REGULAR EXPRESSIONS ------------------ # Regular Expressions allows us to search for a specific pattern # Regular expressions allows us to- # 1. Search for a specific string in a large amount of data # 2. Verify that a string has the proper format (Email, Phone) # 3. Find a string and replace it with another string # 4. Format data into the proper form import re animalstr = 'cat rat mat bat cat sat Mat Cat pat hat fat' # search returns first occurance of match object ##print(re.search('cat', animalstr)) # findall returns list of matches ##print(re.findall('cat',animalstr)) #[] accepts only one character ##print(re.findall('[cC]at', animalstr)) # Use ^ to denote any character except whatever characters are # between the brackets ##print(re.findall('[^bsmM]at', animalstr)) # printing a range of matches ##string = re.findall('[c-m]at',animalstr) ##print(string) # -------------- Replace All Matches -------------- # You can compile a regex into pattern objects which # provide additional methods # sub() replaces items that match the regex in the string ##string1 = 'earth revolves round the sun' ##n = re.compile('earth') #### ##finalStr = re.sub(n, 'moon', string1) ### substituting regex pattern in a string ##print(finalStr) # Another way of substituting ##a = re.compile('earth') ##match = a.sub('Saturn', string1) ##print(match) ##string1 = 'earth revolves round the sun' ##match = re.sub('earth', 'Saturn', string1) ##print(match) # ---------- Solving Backslash Problems ---------- # Regex use the backslash to designate special characters # and Python does the same inside strings which causes # issues ##print("\\stuff") string = "Here is \\stuff" ##searched_result = re.search("\\stuff", string) ##print(searched_result) ##searched_result = re.search("\\\\stuff", string) ##print(searched_result) ##searched_result = re.search(r"\\stuff", string) # using raw string ##print(searched_result) # ---------- Matching Any Character ---------- # . matches any character, but what if we # want to match a full stop. Backslash the full stop ##randStr = "F.B.I. I.R.S. CIA Dr. Mr." search = re.search(".",randStr) print(search) ##print("Matches :",re.findall("\..\..\.", randStr)) # ---------- Matching Whitespace ---------- # We can match many whitespace characters ##randStr = """This is a long ##string that goes ##on for many lines""" ## ##print(randStr) ## ### Remove newlines ##match = re.sub("\n", " ", randStr) ##print(match) # ----------------------------------------------------------- # Practice Questions: animals = 'dog frog cat dog rat cat' # Q. find the first occurrence of "frog". # Q. How many times does "dog" appear in the string animals? # Q. Using animals, find all words that end with "og" but do not start with "d" # or "r". # Q. In the string animals, find all words that start with letters from 'a' to 'f' # followed by "at". # Q. Replace all occurrences of "cat" with "lion" in the string animals. # Q. In the string text = "A.B.C. D.E.F.", find "A.B." # Q. In the string message = "Hello, world!", use regex to find any character # followed by "ello".regex_function .py# Regex functions: matched_result = re.search("sun", "The sun is up") # Print the match print("Match :", matched_result.group()) ##start and ending index of the match print("Span :", matched_result.span()) # Print starting index of the match print("Match :", matched_result.start()) # Print the ending index of the match print("Match :", matched_result.end()) # -------------------------------------------------------------------------- # match(): # The match() function in regex checks if the pattern matches at the beginning of a string, # returns a match object if successful or 'None' if not. string = "The sun is up" matched_result_1 = re.match("sun", string) print(matched_result_1) string = "Sun is up" matched_result_2 = re.match("Sun", string) print(matched_result_1) # ---------------------------------------------------- # --------------------- Finditer -------------------- # It returns an iterator object with only one element ##aString = "The dog ran in a random way" ##match = re.finditer("ran", aString) ##print(list(match)) ##print(type(match)) ## ##for i in match: ## print(i) ## print("Span:",i.span()) ## print("Start Index:",i.start()) ## print("End Index:",i.end())quantifier.py# quantifiers: # quantifiers in regular expressions specifies how many times a character, group or # character class should be matched. import re # '+' quantifier in regex: # '+' matches one or more time. text = "apple pineapple" pattern = r'a+' matches = re.findall(pattern, text) print(matches) # ------------------------------------------ # '?' quantifier in regex: # '?' mathces zero or one times text = "color colours" pattern = r'colou?r' matches = re.findall(pattern, text) print(matches) # ------------------------------------------ # '*' quantifier in regex: # '*' matches zero or more times text = "apple pineapple" pattern = r'a*' matches = re.findall(pattern, text) print(matches) # ------------------------------------------ # {n} : matches exactly n times. (consecutively) text = "apple pineapple" pattern = r'a{2,4}' matches = re.findall(pattern, text) print(matches) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ #IGNORECASE: # a flag that allows for case-insensitive matching pattern = r'hello' text = 'Hello there!' match = re.search(pattern, text, re.IGNORECASE) if match: print("Match found!") # with compile(): pattern = re.compile(r'hello', re.IGNORECASE) text = 'Hello there!' match = re.search(pattern, text) if match: print("Match found!") else: print("not found.")regex3.pyimport re # Metacharacters and special sequence characters # [ ] : Match what is in the brackets # [^ ] : Match anything not in the brackets # ( ) : Return surrounded submatch # . : Match any 1 character or space # + : Match 1 or more of what proceeds (quantifier) # ? : Match 0 or 1 (quantifier) # * : Match 0 or More (quantifier) # *? : Lazy match the smallest match (quantifier) # \b : Word boundary # ^ : Beginning of String # $ : End of String # \n : Newline # \d : Any 1 number # \D : Anything except a number # \w : Same as [a-zA-Z0-9_] # \W : Same as [^a-zA-Z0-9_] # \s : Returns a match where the string contains a white space character # \S : Returns a match where the string DOES NOT contain a white space character # {5} : Match 5 of what preceeds the curly brackets # {5,7} : Match values that are between 5 and 7 in length # -------------- MATCHING A SINGLE SEARCH -------------- ##phone = "567-3746-3767" ##print(re.search("\d{3}-\d{4}-\d{4}", phone)) name = "John Doe" n = re.findall("\w{4}\s\w{3}", name) print(n) ##x = "I got 90 marks in maths" ##print(re.findall("\D{1,30}",x)) ##print(re.findall("\D+", "Hello 123")) # -------------- MATCHING MULTIPLE SEARCHES -------------- numStr = "123 12345 123456 1234567 12345678 123456789" print(re.findall(r"\d{5,7}", numStr)) print(re.findall(r"\b\d{5,7}\b", numStr)) ##PhoneNum = "0755-2345192 0755-5690432 075-5647381" ##matches = re.findall(r"\d{4}-\d{7}", PhoneNum) ##print(matches) # Check if it is a phone number ##phNum = "412-555-1212" ##if re.search("\w{3}-\w{3}-\w{4}", phNum): ## print("It is a phone number") ##else: ## print("Invalid") # ---------------- EMAIL PATTERN SEARCH ---------------- ##email = """@grow_526gmail.com ##5543_tr.@yahoo.com ##limit.less@hotmail.com""" ## ##mail = re.findall("[\w\._%+-]{1,20}@[\w]{1,10}\.[\w]{1,10}", email) ##print(mail) # -------------- MATCHING ZERO, ONE, MANY -------------- #zero or one (?) ##randstr = "cat cats Catsss catssssssssss" ##pattern = re.findall("[cC]ats?", randstr) ##print(pattern) #one or many (+) ##match = re.findall("[cC]ats+", randstr) ##print(match) #zero or many (*) ##match = re.findall("[cC]ats*", randstr) ##print("Matches :",match) # ----------------- WORD BOUNDARIES ----------------- #\b used as a word boundary to define the start and end of a word randomStr = "The cat and catalog are in the category." matches = re.findall(r"cat", randomStr) print(matches) randomStr = "The cat and catalog are in the category." matches = re.findall(r"\bcat\b", randomStr) print(matches) # ------------------ SUB-EXPRESSIONS ------------------ # for matching large block and returning a part of it # ( ) are used astring = "Call me on 412-6547-8877" matches = re.findall(r"412-(.*)", astring) print(matches) astring = "Call me on 412-6547-8877" matches = re.findall(r"(412-.*)", astring) print(matches) ##dstring = "The most commonly occuring natural disaster is earthquake" ##matches = re.findall(r"(earth)quake", dstring) ##print(matches) # -------------- OR CONDITIONAL OPERATOR -------------- Str = "123456 123456-123 1234-12345 123456-786 123-222" regex = re.compile(r"(\d{6}|\d{6}-\d{3})\s") matches = re.findall(regex, Str) print(matches) ##randStr = "1.Cat 2.Dog 3.Rat 4.Panther 5.Camel 6.Hen" ##regex = re.compile (r"\d\.(Dog|Panther|Cow)") ##matches = re.findall(regex, randStr) ##print(matches) ##print("Matches :",len(matches)) # ------------------ GROUP ------------------ Astring = "21-05-1950 22-02-77" regex = re.compile(r"\d{1,2}-\d{1,2}-\d{1,4}") matches = re.findall(regex, Astring) print(matches) ##regex = re.compile(r"(\d{1,2})-(\d{1,2})-(\d{1,4})") ##matches = re.search(regex, Astring) ##print(matches) ##print("My D.O.B. =",matches.group()) ##print("My Birth Date =",matches.group(1)) ##print("My Birth Month =",matches.group(2)) ##print("My Birth Year =",matches.group(3))https://www.geeksforgeeks.org/regular-expression-python-examples/?authuser=03 Octcreate Table User_Info(
User_Id Int primary key,
name varchar(50),
email varchar(50) unique
)
select * from User_Info
insert into User_Info values(1, 'user_1', 'user@gmail.com')
insert into User_Info values(3, 'user_2', 'user2@gmail.com')
update User_Info set name = 'user_new' where User_Id = 1
delete from User_Info where User_Id = 3
truncate table User_InfoSQL.txt-- Creating a table create table BranchTbl( BranchID int primary key, BranchName varchar(50), HOD varchar(20) ) create table Student( StudentID int primary key, StudentName varchar(20), Branch int foreign key references BranchTbl(BranchID), StudentDOB date, ContactNo numeric(10), Address varchar(100) ) --select query select * from BranchTbl select BranchID, BranchName from BranchTbl select * from Student --insert queries insert into BranchTbl values(1,'ME','Amit Sharma') insert into BranchTbl values(2,'CE','Sandeep Gupta') select * from BranchTbl where HOD = 'Ravi Shankar Mishra' select * from BranchTbl where BranchID = 1 insert into Student values(101, 'abc', 2, '2002-06-13', 9999999999, 'Kohefiza') insert into Student values(102, 'xyz', 1, '2000-11-07', 9999999999, 'Panchwati') ----------------------------------------------------------------------------------------------------------------------------------- --update query update Student set ContactNo = 8888888888 where StudentID = 102 --delete record from a table delete from Student where StudentID = 101 --delete table drop table Student --empty the table Truncate table Student --delete database drop database Employee ----------------------------------------------------------------------------------------------------------------------------------- --alter query --add column alter table BranchTbl add HODSalary int --delete column alter table BranchTbl drop column HODSalarySQLNotes.txt-------------------------------- DBMS - SQL -------------------------------- SQL stands for Structured Query Language. It is the standard language for relational database management systems. It is especially useful in handling organized data comprised of entities (variables) and relations between different entities of the data. * What is Database? A database is an organized collection of data, stored and retrieved digitally from a remote or local computer system. * What is DBMS? DBMS stands for Database Management System. DBMS is a system software responsible for the creation, retrieval, updation, and management of the database. It ensures that our data is consistent, organized, and is easily accessible by serving as an interface between the database and its end-users or application software. * What is RDBMS? RDBMS stands for Relational Database Management System. RDBMS stores data in the form of a collection of tables, and relations can be defined between the common fields of these tables. Most modern database management systems like MySQL, Microsoft SQL Server, Oracle are based on RDBMS. * Advantages of DBMS: 1. Controls database redundancy 2. Data sharing 3. Easy maintenance 4. Reduce time 5. Provides backup 6. Multiple User Interface * Data Corruption: It arises when there is an accidental deletion of data or any changes made into the database. * Data Redundancy: When same piece of data exists in multiple tables of a database in multiple forms, it will lead to data redundancy. * What are Tables and Fields? A table is an organized collection of data stored in the form of rows and columns. Columns can be categorized as vertical and rows as horizontal. The columns in a table are called fields while the rows can be referred to as records. * What are Constraints in SQL? It refers to a set of rules for the data in a table. Constraints are used to limit the type of a data so that the data consistency is not disturbed. The constraints are: 1. NOT NULL - Restricts NULL value from being inserted into a column. 2. CHECK - Verifies that all values in a field satisfy a condition. 3. DEFAULT - Automatically assigns a default value if no value has been specified for the field. 4. UNIQUE CONSTRAINT - It is a constraint which ensures that all the values in a column should be different. It is used to restrict a repeated data in a particular column. 5. INDEX - It is used to locate and access the data in a database. Indexes are created using a few database columns. 6. PRIMARY KEY - Uniquely identifies each record in a table. 7. FOREIGN KEY - It is the key of one table whose values are derived from the primary key of another table to relate the two tables. * What is a Join? List its different types. The SQL Join clause is used to combine records (rows) from two or more tables in a SQL database based on a related column between the two. There are three different types of JOINs in SQL: 1. (INNER) JOIN: Retrieves records that have matching values in both tables involved in the join. This is the widely used join for queries. 2. OUTER JOIN: There are three types of outer joins: a. LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched records/rows from the right table. b. RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched records/rows from the left table. c. FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or right table. 3. CROSS JOIN : Returns the cartesian product of the tables involved in the joins * Select Command: The select statement is used to select data from a database. 1. Every table is broken up into smaller entities called fields. 2. A field is a column in a table. 3. A record is a horizontal entity in a table. 4. A column is a vertical entity in a table. * Keywords/SQL Commands: SQL keywords are NOT case sensitive: select is the same as SELECT Some Important SQL Commands: 1. SELECT - extracts data from a database 2. UPDATE - updates data in a database 3. DELETE - deletes data from a database 4. INSERT INTO - inserts new data into a database 5. CREATE DATABASE - creates a new database 6. ALTER DATABASE - modifies a database 7. CREATE TABLE - creates a new table 8. ALTER TABLE - modifies a table 9. DROP TABLE - deletes a table 10. CREATE INDEX - creates an index (search key) 11. DROP INDEX - deletes an index * SELECT DISTINCT: It is used to return only distinct values (if a column contains many duplicate values) * WHERE: It is used to extract only those records which fulfill a specified condition. Operators Used in WHERE: 1. = : Equal 2. < : Less than 3. > : Greater than 4. <= : Less than or equal 5. >= : Greater than or equal 6. <> : Not equal 7. BETWEEN : between a certain range 8. LIKE : Search for a pattern 9. IN : To specify multiple possible values for a column 10. Not in can be used to specify values not required. * AND, OR, NOT Operators: 1. AND- Displays a record if all conditions separated by AND are True. 2. OR- Displays a record if any of the conditions separated by OR is True. 3. NOT- Displays a record if condition is Not True. * Aggregate Functions: An aggregate function in SQL performs a calculation on multiple values and returns a single value. SQL provides many aggregate functions that include- 1. COUNT() - The COUNT() function returns the number of rows in a database table. 2. MAX() - The MAX() function returns the highest value (maximun) in a set. 3. MIN() - The MIN() function returns the lowest value (minimum) in a set. 4. SUM() - The SUM() function returns the total sum of a numeric column. 5. AVG() - The AVG() function returns the average value of a numeric column.4 OctSQL2.txt# Alter Query -- adding a column alter table Student add Age int -- changing datatype alter table Student alter column Age numeric(3) -- deleting a column alter table Student drop column Age ------------------------------------------------------------------------------------------------------------------- # Use of Comaprison Operators -- equal Select * from Student where StudentID = 101 -- not equal Select * from Student where StudentID <> 105 -- greater than equal or less than equal Select * from BranchTable where HODSalary < 50000 Select * from BranchTable where HODSalary >= 50000 Select * from BranchTable where HODSalary <= 80000 ------------------------------------------------------------------------------------------------------------------- # Use of BETWEEN select * from Student where StudentID between 105 and 110 select * from BranchTable where HODSalary between 50000 and 70000 ------------------------------------------------------------------------------------------------------------------- # Use of AND and OR Select * from BranchTable where BranchName = 'IT' and HODSalary = 72000 Select * from BranchTable where BranchName = 'IT' or HODSalary = 72000 ------------------------------------------------------------------------------------------------------------------- # insert query for inserting data into selective columns insert into BranchTable (BranchID, BranchName, HODName, HODSalary) values (10, 'BBA', 'Ajay Kapoor', 75000)5 OctSQL3.txt# Creating Table without Constraints create table Employee( EmpID int, EmpName varchar(50), EmpAge int, EmpDepartment int, EmpSalary int, EmpAddress varchar(100) ) # Applying Constraint --1. not null: alter table Employee alter column EmpID int not null --2. primary key alter table Employee add constraint PK_Employee primary key (EmpID) -Drop constraint alter table Employee drop constraint PK_Employee --3. foreign key alter table Employee add constraint FK_Depart foreign key (EmpDepartment) references BranchTable(BranchID) -Drop constraint alter table Employee drop constraint FK_Depart --4. unique: alter table Employee add constraint Unique_Employee unique (EmpSalary, EmpAddress) -Drop constraint alter table tblemp drop constraint Unique_Employee --5. Check: alter table Employee add constraint CHK_Age Check (EmpAge>=20) -Drop constraint alter table tblemp drop constraint CHK_Age --6. Default: alter table Employee add constraint DF_Salary Default 10 for EmpSalary -Drop constraint alter table Employee drop constraint DF_SalarySQL4.txt-- Aggregate Functions -- 1. min() select min(empSalary) from EMPLOYEE -- 2. max() select max(empSalary) from EMPLOYEE -- 3. sum() select sum(empSalary) as Salary from EMPLOYEE -- 4. avg() select avg(empSalary) as Average from EMPLOYEE -- 5. count() select count(empSalary) from Employee select count(empName) from Employee select count(Department) from EMPLOYEE where Department = 4 select sum(empSalary) as SalarySum from EMPLOYEE where empSalary between 60000 and 800007 Octselect * from Employee
select * into duplicateEMP from EMPLOYEE
select * from duplicateEMP
insert into duplicateEMP values (10, 'emp', 25, 1, 10000, 'xyz')
insert into Employee values (5, 'abc', 78, 1, 700, 'xyz')
select * from EMPLOYEE order by empsalary
select * from EMPLOYEE order by empName
select * from EMPLOYEE order by empName desc
select * from Employee
union
select * from duplicateEMP
select * from Employee
union all
select * from duplicateEMPregex_4.py# ------------------ NAMED GROUP ------------------ text = "John Doe" pattern = r"(?P<first>\w+)\s(?P<last>\w+)" match = re.search(pattern, text) print(match) print(match.group('first')) print(match.group('last')) # -------------------------------------------------------- Astring = "21-05-1950 22-02-77" ##regex2 = re.compile(r"(?P<day>\d{1,2})-(?P<month>\d{1,2})-(?P<year>\d{1,4})") ##matches = re.search(regex2, Astring) ##print("Day :",matches.group('day')) ##print("Month :",matches.group('month')) ##print("Year :",matches.group('year')) # ------------------------------------------------------------ string = "The temperature is 35 degrees today." match = re.search(r"\d{2}", string) print(match) print("My Match is:",match.group()) print("Span :",match.span()) print('Start Index :',match.start()) print('End Index:',match.end()) # ---------------- GREEDY AND LAZY (NOT GREEDY )MATCHING ---------------- # .* --> Greedy match # .*? -- > non Greedy/ lazy match import re text = "The cat sat on the mat." # Greedy match greedy_pattern = r'c.*t' greedy_match = re.search(greedy_pattern, text) print("Greedy match:", greedy_match.group()) # Lazy match lazy_pattern = r'c.*?t' lazy_match = re.search(lazy_pattern, text) print("Lazy match:", lazy_match.group())SQL5.txt-- order by : It sorts the data into ascending or descding order. -- by default it is sorted in ascending order select * from EMPLOYEE order by empsalary select * from EMPLOYEE order by empName asc select * from EMPLOYEE order by empName desc ------------------------------------------------------------------------------------------------- -- creating a duplicate table -- It copies only the data, constraints are not copied select * into duplicateEMP from EMPLOYEE select empID, empName into newTable from EMPLOYEE ------------------------------------------------------------------------------------------------- -- union : returns unique values from both the tables select * from Employee union select * from duplicateEMP -- union all : return unique as well as duplicate values select * from Employee union all select * from duplicateEMP(Edited 10 Oct)(Edited 11 Oct)pyodbc_learning.pyimport pyodbc as p connection = p.connect(r'Driver=SQL Server; Server=DESKTOP-21MU0SK\SQLEXPRESS;Database=EMS_2024;') ##print(connection) cursor = connection.cursor() ##print(cursor) ##cursor.execute("select * from EMPLOYEE") ##rows = cursor.fetchall() ## ##for row in rows: ## print(row) cursor.execute("INSERT INTO EMPLOYEE VALUES (11, 'Emily', 'Data Scientist', '2022-01-15', 60000, 1, 'Koh-e-fiza')") cursor.commit() print("row inserted")DBAL.pyimport pyodbc as p def getConnection(): connection = p.connect(r'Driver=SQL Server; Server=DESKTOP-21MU0SK\SQLEXPRESS;Database=EMS_2024;') cursor = connection.cursor() return cursor ##print(getConnection()) def getAllEmployees(): cursor = getConnection() cursor.execute("Select * from EMPLOYEE") rows = cursor.fetchall() return rows rows = getAllEmployees() print(rows)14 Octcreate table Department (
deptNo int primary key,
deptName varchar(100),
Manager varchar (100)
)
select * from Department
--------------------------------------------------------------------------------
create table EMPLOYEE (
empNo int primary key,
empName varchar(100),
Designation varchar(100),
join_date varchar(100),
Salary int,
DeptNo int foreign key references DEPARTMENT(deptNo),
empAddress varchar (100)
)
select * from EMPLOYEE
-----------------------------------------------------------------------------
INSERT INTO Department VALUES (1, 'Computer Science', 'Dr. Emily Clark')
INSERT INTO Department VALUES (2, 'Information Technology', 'Mr. David Lee')
INSERT INTO Department VALUES (3, 'Software Engineering', 'Ms. Sarah Patel')
-----------------------------------------------------------------------------
INSERT INTO EMPLOYEE VALUES
(1, 'Emily', 'Data Scientist', '2022-01-15', 60000, 1, 'Koh-e-fiza'),
(2, 'Edward', 'Software Developer', '2021-06-10', 55000, 2, 'Idgah Hills'),
(3, 'Ron', 'Software Developer', '2020-03-22', 70000, 3, 'Jahangirabad'),
(4, 'Emma', 'Recruitment Specialist', '2021-11-05', 50000, 1, 'New Market'),
(5, 'Ana', 'Full Stack Developer', '2022-02-18', 65000, 2, 'Shahjahanabad'),
(6, 'Jake', 'Operations Analyst', '2019-08-30', 62000, 3, 'Moti masjid'),
(7, 'Liam', 'Cybersecurity Analyst', '2023-04-12', 75000, 3, 'Idgah Hills'),
(8, 'Olivia', 'Sales Executive', '2022-07-20', 58000, 1, 'Moti Masjid'),
(9, 'Mia', 'Market Research Analyst', '2021-09-15', 64000, 2, 'Shahjahanabad')15 Oct3_tier_architecture.txtTHREE TIER ARCHITECTURE: Three Tier Architecture is a structured approach to software design. In this architecture, a developer divides the project into three separate layers: Presentation Layer (UI), Business Logic Layer (BLL), and Database Access Layer (DBAL). Presentation Layer (UI): This is the user interface layer where the user interacts with the application. Business Logic Layer (BLL): This layer contains the core logic of your application. --> It defines how the data should be processed. --> This layer acts as a "bridge" between the UI and DBAL. Database Access Layer (DBAL): This layer interacts directly with the database. --> It executes SQL queries. --> In DBAL, we establish a connection with the database and write functions that perform CRUD operations. By keeping these layers separate, developers can easily update or change one part without affecting the others. This leads to better organization and flexibility in the application.pyodbc_learning.txtPYODBC: pyodbc is a python libraray that lets us establish conncetion with database Installation of pyodbc (python library) installation command: pip install pyodbc ------------------------------------------------------------------------------------------------ To connect to a database and retrieve data using the Python, you only need a few functions: 1. connect() function to create a connection to the database; 2. cursor() function to create a cursor from the connection; 3. execute() function to execute a select statement; 4. fetchall() function to retrieve all rows from the query. 5. fetchone() function returns a single row as a tuple. 6. commit() function is used to commit the changes made to the database. It is used while performing operations like insert, update or delete. 7. cursor.close() is used to close the cursor. 8. connection.close() is used to close the database connection. ------------------------------------------------------------------------------------------------ import pyodbc as p connection = p.connect(r'Driver=SQL Server; Server=DESKTOP-21MU0SK\SQLEXPRESS;Database=master_2;') print(connection) --------------------------------------------------------------------------------------------- cursor = connection.cursor() print(cursor) ----------------------------------------------------------------------------------------------- cursor.execute("select * from EMPLOYEE") row = cursor.fetchone() rows = cursor.fetchall() print(rows) for row in rows: print(row) print(rows[3][1]) ------------------------------------------------------------------------------------------------ cursor.execute("select * from Employee where empNo = 2") row = cursor.fetchone() print(row)----------------------------------------------------------------------------------------------- Inserting data: cursor.execute("INSERT INTO EMPLOYEE VALUES (10, 'Mantha', 'Data Scientist', '2022-01-15', 60000, 1, 'Koh-e-fiza')") cursor.commit() print("row added successfully")DBAL.pyimport pyodbc as p from BLL import Employee def getConnection(): connection = p.connect(r'Driver=SQL Server; Server=DESKTOP-21MU0SK\SQLEXPRESS;Database=EMS_2024;') cursor = connection.cursor() return cursor ##print(getConnection()) def getEmployees(): cursor = getConnection() cursor.execute("select * from EMPLOYEE") rows = cursor.fetchall() emp_list = [] for row in rows: objEmp = Employee(empNo= row[0], empName = row[1], Designation = row[2],join_date = row[3],Salary= row[4],DeptNo = row[5],empAddress = row[6]) objDict = objEmp.__dict__ emp_list.append(objDict) return emp_list ##print(getEmployees()) def addEmployee(obj): cursor = getConnection() cursor.execute(f"insert into Employee values({obj.empNo},'{obj.empName}','{obj.Designation}',{obj.join_date},{obj.Salary},{obj.DeptNo},'{obj.empAddress}')") cursor.commit() print("row added successfully!") def getEmployeeById(n): cursor = getConnection() cursor.execute(f"select * from EMPLOYEE where empNo = {n}") row = cursor.fetchone() ## print(row) objEmp = Employee(empNo= row[0], empName = row[1], Designation = row[2],join_date = row[3],Salary= row[4],DeptNo = row[5],empAddress = row[6]) objDict = objEmp.__dict__ return objDict def updateEmployee(obj): cursor = getConnection() cursor.execute(f"update EMPLOYEE set empName = '{obj.empName}', Designation = '{obj.Designation}', join_date = {obj.join_date}, Salary = {obj.Salary}, DeptNo = {obj.DeptNo}, empAddress = '{obj.empAddress}' where empNo = {obj.empNo}") cursor.commit() print("row updated sucessfully!") def deleteEmployee(pk): cursor = getConnection() cursor.execute(f"delete from EMPLOYEE where empNo = {pk}") cursor.commit() print("row deleted successfully")BLL.pyclass Employee: def __init__(self,empNo = 200,empName= 'Sara',Designation = 'IT Expert',join_date = '2009-09-09',Salary= 7000,DeptNo = 1,empAddress= 'Idgah'): self.empNo = empNo self.empName = empName self.Designation = Designation self.join_date = join_date self.Salary = Salary self.DeptNo = DeptNo self.empAddress = empAddressUI.pyimport DBAL from BLL import Employee user_input = input("enter 'GET' to fetch all rows, enter 'ADD' to insert a new row, enter 'UPDATE' to update an existing row and 'DELETE' to delete a row: ") if user_input == 'GET': rows = DBAL.getEmployees() print(rows) elif user_input == 'ADD': objEmp = Employee() objEmp.empNo = input("enter a employee number: ") objEmp.empName = input("enter employee name: ") objEmp.Designation = input("enter Designation: ") objEmp.join_date = input("enter join date: ") objEmp.Salary = input("enter Salary:") objEmp.DeptNo = input("enter DeptNo: ") objEmp.empAddress = input("enter address empAddress: ") DBAL.addEmployee(objEmp) elif user_input == 'UPDATE': ID = input("enter the id of the row you want to update: ") row = DBAL.getEmployeeById(ID) print(row) print("ENTER UPDATION DETAILS: ") objEmp = Employee() objEmp.empNo = ID objEmp.empName = input("enter employee name: ") objEmp.Designation = input("enter Designation: ") objEmp.join_date = input("enter join date: ") objEmp.Salary = input("enter Salary:") objEmp.DeptNo = input("enter DeptNo: ") objEmp.empAddress = input("enter address empAddress: ") DBAL.updateEmployee(objEmp) elif user_input == 'DELETE': ID = input("enter the id of the row you want to delete: ") DBAL.deleteEmployee(ID) else: print("please enter valid command.")(Edited 23 Oct)block_vs_inline_diagram.pngindex.html<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <!-- <h1>This is my Heading 1</h1> <h2>This is my Heading 2</h2> <h3>This is my Heading 3</h3> <h4>This is my Heading 4</h4> <h5>This is my Heading 5</h5> <h6>This is my Heading 6</h6> <p> <em>Lorem ipsum dolor</em> <mark>sit amet consectetur adipisicing elit.</mark> <br />Tempora natus ut rerum,<del>tenetur earum suscipit.</del> Reprehenderit perspiciatis quidem, eum accusantium dolore odit iste eius cum maxime molestiae fuga doloribus similique? </p> <p> <b>Lorem ipsum</b> <i>Lorem ipsum dolor sit</i> amet consectetur adipisicing elit.<br /> <q>Quas maiores culpa</q>, odio qui at repellat animi doloremque fugiat iure fugit numquam perferendis? Maiores reprehenderit quo, repudiandae recusandae nam accusantium voluptatem! </p> <p style="color:blue;"> <b>Lorem ipsum </b>dolor sit amet consectetur, adipisicing elit.<br /> Facilis ratione recusandae omnis quisquam, minima delectus. Rem, nostrum dignissimos voluptatum fuga officiis facere eaque molestias quae. Vero debitis voluptates iste quas. Lorem ipsum dolor sit amet consectetur adipisicing elit. Corrupti eos eaque distinctio voluptate. Fugit inventore doloremque sit excepturi? Necessitatibus et facilis in obcaecati quis quas, magnam sed unde maxime dolorem? </p> <a href="https://www.google.co.in/">Google</a> <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxISEBAQEhAPDxAPDw8PDw8PDw8PDw8PFREWFhURFRUYHSggGBolGxUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OFxAQGi0lHR8tLS0tLS0tLS0tLS0tLS0tLS8tLS0tLS0tLS0tLS0tLS0tLTUtLS0tLS0tLS0tLS0tLf/AABEIALYBFAMBIgACEQEDEQH/xAAcAAABBQEBAQAAAAAAAAAAAAADAAECBAUGBwj/xAA6EAACAgEDAgYABAQEBQUBAAABAgADEQQSIQUxBhMiQVFhFDJxkUJSgaEHI2LRU7HB8PEWQ3KS4RX/xAAaAQADAQEBAQAAAAAAAAAAAAAAAQIDBAUG/8QAKxEAAgIBAwMCBAcAAAAAAAAAAAECEQMSITEEQVETIgVhgdEjMnGRscHw/9oADAMBAAIRAxEAPwCuqQ9bASuWkd0xBF/zJIWSgHMKjGBdl5XkxZKgePvhQFrzJHdK3mRg8LAssICxJIPJR6gKbV8TO1dQmy8ztUsm9xM5vV1czG1FeDOn1NMzNRo8zbGzNySMcLJAS7+DjNpJqT6kSpiMYdqCIJlgWmmDzGMmYzQGQjiKLMAERHEjmPEAoooxMAEZAyWZBoANIGOTIkwGNFFHxABRjJSLQAgTFEYohHqjCBNkk5zIBJz2U9g9cuVVwVFcsqJvFKjllNkHrkIdjAWHmDgifVaH2SOI+Y20yHBA87Q2Yap4FkPvHEzaoldSGdZUuSHDwVshsJZ20UnolazTS+xmn0jpaOrX3kihOCAwUsSQO/sMkTTHyYLXllpjuzma9AznaiM7fyopZv2E0k8GaxhkaZgD/O9SH9i2R+09IocUUu9emK1pW1hFYX1BRn5yT37yp4b8V/iwxSiwIpUGxSrICQTtPY5GOcZ9uZ2aNKtm+PppNXb+h5l1PwnrKhubTWFfmvbb/ZCSJzF6959KB8jtOY8VeDqtYpYAVaj+G4J3x7OP4h/cRUnujVRcWeDNGzLPU9FZTa9VqlLEJDA5/cfIPsZTMk3RLMUgDHzEAiYsxiZEmABMxQeZNYAS2wbKYUGKAFYiRxDusCYANHzGMUQx4xikWEBEo0aKAz1byo2yLzY3mTkKaLlBlkyglkKLptGdGTx2GcwYXmRJzCKsfqGTwlinT5h/w4jabtD4mq4MJwoq2IO0o2riaFy4mVqLJlldHO4jGDcwfmx905VK2DjsXOk6A3WY7IvNjdgqzT65rSUNFKrs2GshhWtTLjBU7+Dmc+zttK5IUnJAJGTM99P6h67AM8gP/wBTniLLjzT9sKPoPgnWdD0y/GvV+lr+T1nwbrS+gU5NlmmQ1W14IcW1rnYSe5IxyM5zmcl4D8S26uqy20+r8RaPLUACoZGEwO+Ja8Nk6Ddb6vLtCvqQoYr6UAFuD2bHJxjI+SJj+EqBUdTjhX1modPnyy5xz8jmT8ejKPRc021/dofQyx5OpnpW29bfPY9Eq1IxLlZDDM56sluAdwxk9sibGkswMH2nn/A8ubJNpt6Uvoa9dCEI33ZzX+IfhpdVp3ZEDamobqW7McHLV59wRng++J4Uy44IwR3HYgz6fZMzyX/E3weyO2toUtW3OpRRzU3/ABQP5T7/AAeexOPpnueWnR5uZEwhEYiZmgIxswhEgVgAwMIsHCLACYjxCOIwIkQLCHMGwiAHiNiSIjQAbEiZMxsQGRjSe2KAHfG+Ot8xm1UdNXOKyrOjru4kxbMWnV/ct1XyrA10thqrczNrtzLmnMcdyJSpGtQZaNgxKFTxWvxOuKo4pysWu1HEwdVdLeraZOonF1M+xCRNLJZreZ6GHR5zYnuE1aLpaRXuv6j/AJwReCZ56EGc7idp0LVbhsJO1fSdwfaDjt6SWz+pEtp4awx2P5dZ5xsK5JOTtXk/P/eTA+GtAhJswx49Oc1rjj8p5zyR2nV0unA9IJ/gHLdu54GP+c7Opw480VHIrXJ39PlnjdwdGVV0tuxbCDHC/mbHuTnj27f+NetMY5B+vaGK5A9vuDeg44OR+0zjGEFpgkl8jVuUncnY5cSvY4I9iO2D7/UFZZtPf+3MRAPOQf7Z/eMZ5b468DeXu1OlXNX5rdOo5q+WrHuv17fp289n0dap9p5h498KhWOqpXajHN1QHCsf/cUewPuPbv8AomNbHnxEjialegzLVfTvqSMwfLPxJrSZ0I6f9SQ6f9RDMJNOTDpo5tpofqWF0H1AKMIaP6jjQfU6BNCYden/AFADmT0/6grOn/U638D9Qb6L6gOjjn0UrvpSJ1tuild9F9RAcsaWinQNovqPGKjEbUyVd8oFoWszloZs6e6adFkwaHmto24k0F0bFDS9W8yarJbW+bQSOHLNs1E1GI9mpmSdRIm/MuU6ROODkWrtRmV2XMETDVTgncmdEoJRICuRYYl1UgrwJpjx0cd7lY2yJeA1BxAC+brY3WO1Z2HhLrvJpArFiEsCxUb+5Dbf4yATlicDvjg57jR6xc8Mtj8HFj7QxYjDNxxx6sY7fHE8Vr6bZdfSag7MXCMEH5UPJZj/AC4B49+3vOtvuq/ztP56M1nrWtmQPXqgRu3Ec2WMgxnIAJad08lYk+/Bv0uJTyU+FudxoevI6AqSeTvJOctn2/0g8CXa+oge84tdS+cOFprawmupCHqGf5Wxnnj+svhyPfOP++0ygnpVm+SnJ6eDrncMP+sAyEfOBj4+Zj9P6hztLZ7cc8TXXUf1BlGY9ZOefn4g9bp0YY+QVwex+pPIMiFJGD+g+YgPOuqdCFVhAGEJyv8Ap/0yuuhnomp0K2rtYcj+IdxMDVdOKMVPPuD7EfMiWxSOeGjHxJjRfU1/w/1JLVFYzIGj+oavSTU8mSWqICkmkEKNKJdSuEFcBGY2mEDZpZsNTBNVEMwbdJKz6OdDZTK7UxAc+2jim5+HjwA8WENXBAQ1YmYi1UO01dO+BMugy0tkkmRqLbHbU4mYL/uR8+VqOf022aa3yxXZMdLJcosmcmzpjFI0lMtUyhW8vUtJS3Iyv2lz2lW8whs4lTUWToXB59blLVNMp7MGW9XbMy1o0ehjWx0/g/qwp1ALH0WA1vntg9j++P7zW8c9ERaxfUtatX/m+a2dx8vLeXvHbIzgn4Az2nB6e3md54f655lYpsIJAxzj1D6z3MvVXtfARuErRT6H1sjFdgKhtrbHHNTEZxz/AAHIIb2/Qzds6iVyCmfcFTyf0B+QP3UicZ4i8N21DzKW30oLHJPmb8nbivaMhMAEBhx2BgemdZvrKafU03EFS1ZKMbUUckjH51GB9jH9JrGXZmj8rg7rT9ZqJ4DZIzNzRa8MOD7cTz22vIW6o762O7Nfq592AH91/aa/S9Z27YPwCBu+v9pbj4JtHf0W5Gc89jz7w65PHOR7/P3Of0WoII9weDj+xmwmoww9XGBnn3kMqi2bcKTg5Tlv/jnk/wBJn9XO0K5Gaj3f2qz/ABN8J8n27njJGlqaS6MoYruUg9gcEY4MyelXvSxovBZArFDjixAPUv6j4jStCK1lWJXYS4dMKz5ah/wzg/hLWDellBLac574UFlP8oYfwDNexMHBmM4uLKTsGphFgtsKgk2DCBJMLEphVMoQMiDdZYMGwiAqMsEyy1YsrvJAHiNGLRRgeHIYZTKymEVpmBaV5PzpVDSJaKgLL3QS2wDNIho6CjVpsl2t5j0WS/TbJaA1abJoVWzDrslxL5HDM8itGhZdKWougnula6yaJnOse4O55Usk3eDM1ijsSoZZcpeVVEs1LKkOrOx8O+IyCqWn6V/n6ab/AFvo+n19YSwmpxylids+2VPB/sfuecJN/ovV3T0n1KBnJP5QPkn2mXqaVT4BQepOPJR6j4X12lbduFlAXy1t07CvaM+k2IBuPf4P6y1pxem4Bh1GoV77rtKrg0/TggEH7Ge2eJ2PTuso6Agq6H3BBI/WZnWuhrttu0tJte2tkeoWsgOR+ceoHI/Xn4mkX3i/p9jRSjJ1kVPz90Vema27INVwuVe9F+Fs2/G4cj9TkfM39J1qliFsDaWw+1gzU3Ps/aea3dPrC0tTq9QdfuWu3SWVWpYnHAUnjA+D8/0nUdE1OoOaNUK/N7rXcprd17HBAPqH2JUJqT0tblzwSgtS3R6Roi4A2EOp52k5Uj5Blu6w2IQoAsUEqjjOD8g+882PW6tHb5Y1B0b9/JvBs0zfasOB+oIPPM6bpfi+q1RvG8f8bTMt2w/Pp9X9sj7mrVOjmtPdGr4fZmrs0GpBXG01P7oQwKMpPurBSD7ESvqVDb19IuobZcqkYU4B7dwCPUvyp+sSv4hs1L1o9Fld1WVYXIP81lVshMjjuB7Z4gOpdSrfUU3EPRqrKEqezvXeuSVV17ZDbu4zyMHnEJbplNdyW2SAkaXJJVlCuPjO1h/Mv19e0LictUAyiTEaLMYDkxZkGeIGFiEwlaxZZg3EAKLLGhmXmKAzwNZPdICSjoRLdGLSJMbMNID5kcx4xEKAJW+JcqtmfDVmJxA00slhLZmo0OrxaBFw2QNtkEbI26UogkSjRZjCaDC1rLVYgKpZrmU2UjY6N0gWgu9grTdsXsXsfGSqg/A7n7HeS6o1ShqKKnssOc+rkAcE2McbV574X+sza34xk4GTxn6/2EJreqbNlde2pr2ANi+lRWhPqwexIyef6Tkm2/mdeBq/Fd+5Ts6TrKmFiXV4JwV5QZ9xg8n4zNDp/ii+s7XViO2QGP8AYgGcp1bUKLmwXcqSoZXyrAHhww7gjE2ukgmtm/MGxj5Rl7j9CM//AFEG5Y0m2atYsuppO15Z2Wk65RqCvmoC4IKWMCtqH2Kt3E6roddaszu5uL92sJZh8f7ZHtPMK7CP/wBmppusMuByMfHI/aaRz+eTi3qk9vB2nivwLRrENlT+XeoJrZizKpOPYEe4HzOc6L/hcrDFz26e8Jn8RS/DW5yff9PgEfeYbReJ7Fxgbh74POJZ1HjElWVN5fB2rnB3Y4B/rOqPU2qZj6Vbo5DVeJNd0nUvRZbXqRgeoDBZfYn5P65P3JdN6++ttNa5e23LbM7bWYLkBR24A9u0L0F+lFH1vVLmt1Zdx+G9QaoqSFAVcbj25PEpeHPEDW9Xp1lehPkUslRroqZzTW+aksYqPzZYfR4E3WO2qe77Cjla7HqfS/M8msW480LtY5BzjjPHyMGWWkNSPLdkPse47EHkH9pDzpyvZlp3uSJkWMYvI7pAxmMdGkTEIkwoLmRcxAyLNLsQJhFETFCxnge2PthSsiRNqJB4kSJMxoARixJRhAQgIRZASawoYVDChoAGTVoUATdH3QZMW6ABd0dDA7pNGgwLtRlqsyjW0tVtObIUi2glbrnTgP8AMzlTisnsK328jH2TjPbjEsIYfVVsaF2+Wf8AMbK2Ny4Cj0qpOG79u/bExj+YuzjbKXJdmGMYyeQBNvw5YQjKCcMORg7TxwQYTQurWsrVnhGXy2dfLQ+7gEcADJ7+/HtNjSdI2q+wbjuTbyM7Tn0jP37fcvItS0sqMnB2isBHBjmNMKJDVvDi7Pfn79/3lMGSDQTaGUvEXRDeRbXjeAA4A5cD3+2x+89Q6V4m6R0jRKaiGZ1X01gNqNQwHdvj374A7fU8/ruI7Seh6Bo9Vq631NnkV8m7bhRZjkAt/D9n/wAzu6fLfsfcxyQ7nQ6Hx7//AELmc0+QPy1+rdnGTtJwBnb2/Q/E2F1Mudb8WdH6Ymm0YoW1FXzEShK7fKz6d7FjncQzHPJPM4/R9XW1RYn5X5AB/L/p/p2l9QkqaFj8HVLdDI8w9NqwZoVXTms1o0QYiYBLJLfGOghMGzRi0ExhYqJkxSGY0LCjxIyDSci06zME0hmEaQIiAYGLMbEUAJZkg0HFmAgoaS3wIMcGAwu6LdBgx8wET3QiNAZj7omMuJZLVTzMV5aoeYzQ0a9TTb6VozYhwU3EWBN6qwBCqSFyOCc9+/pnO1PNTp2qZfyY3D1ITyFOCM4/rMFsyifUc/hVHlo4ZsoAieZnlnZGAzwN3fI4kOm2mxGqD4wFNYrUqBt7HeTyMYyPuaV2outK2sgp2IK3TNK1+WSNzAkEjPyfuE6TpVZ0UEVI5CI2S/mLxtqL+3PIx8e/EqL7F/MxnfJJ+TniRzCazTNXY9bAgoxB/wCh/aAmL5JHzI7pEyJioLCb5JbIDMQMY7Oy/wANfA+h1Fh1Nthayq3euk9K18YIZvdlz7duMSHiO3pa2316NhXcNVY9oG80tuYq6jPpTa69hxtYEe+OUHIIyVyOGUlWU/IIlr/0HZX0y7qK312lRXtrrDZClzXarZH5huB4+D9T08eT1YOL7f79zGUad2aWnvwZqafVTmOmajdTWxOXwVfOe6ng598jH7TQrtnny9ro6I8HUU6iG86c7Tq5ZXVRaitJtedINbMxdVE2pj1BpNMWxplfiYorDSeV7ooLdJqZ6BzDkSOITEW2MARWRxDlYtkBAMRbYbZG2RABjyZWMVgMjHj4jQELMYmEWrMkaoDABpYpsgWrjKZm0Bq1WzR0Wo2sp+CM/Y9xMKqyXqbJhKI0z0XQ6ZdWjK9YW7y12obHxs7ocA8jOc8dwfqaN3S2NHk1EaexkVq61wANoByD+uP2zMNOjWC2pktFblUrW2skk4Qbgw7EZBOOew9pqF/IvrvubUaiytLA7LteltP2bai424yvJB95MEmyzG8WaOxWqucs/nVjNhAHrHcccZxiYM9D691HS6nRFKCXx/mIprINZxnk4wO59/eedq0WSNMBFYNoYmDYSAB4jCSMjEwCLLtGttVHqW11ptINtQxtcjGD9HgdviUUhlMak48DQYNJb5XJkTZM2WmXK7ZbrtmTW/M0KIItMtiwyFl+IwaV9WZdBZM6qKZbvz3igSckIQRRT0kcwRYVRFFGgH2xbY8UYESsbbFFEAxEgwjRQEDaKscxRRDLEeKKAEWEr2RRRMBkeGW2KKQ0B6F4RsXU1iuzepp2OrqfVtztK/8AOE6jcll7rYjNp0aujC2Olhwc84O0gttzx/CCOY8U5Vs3RpBWyz0VGtXFa1adQWTapazcjEKAWPOBnt9fc5DODj44iije45ckw0YmKKKiSDGRDRRSQJgyYaKKSNDF4NniihQ0TofmaNLRRSootB90q6uziKKV2BmU9nMUUUzIP//Z" alt="bird" width="300" height="200" /> <img src="download (1).jpg " alt="bird" /><br /> <ol> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ol> <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> --> <!-- <table border="1"> <tr> <th>flower</th> <th>color</th> <th>season</th> </tr> <tr> <td>Rose</td> <td>Pink</td> <td>Winter</td> </tr> --> <!-- <tr> <td>Sunflower</td> <td>Yellow</td> <td>Summer</td> </tr> </table> <form> Id <input type="number" /> Name <input type="text" /> age <input type="number" /> email <input type="email" /> password <input type="password" /> <button>Click me</button> <input type="submit" /> <br /><br /><br /><br /> <br /><br /><br /><br /> </form> --> <!-- <form> id <input type="number" /> Name<input type="text" /> Email <input type="email" /> Password <input type="password" /> <input type="submit" /> <button>Click me</button> Have Laptop? <label for="1">yes</label> <input type="radio" name="Laptop" id="1" /> <label for="2"> no</label> <input type="radio" name="Laptop" id="2" /><br /> Languages Known: Hindi<input type="checkbox" /> English <input type="checkbox" /> Urdu <input type="checkbox" /> </form> <hr /> <br /><br /><br /><br /> <br /><br /><br /><br /> <header> <pre> Home Products about us </pre > </header> <main> <section> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo molestias animi sit nostrum inventore dignissimos non tenetur, rem perferendis delectus expedita eum harum repellendus neque aliquid illo ratione cum asperiores voluptas soluta assumenda. A porro veritatis enim nobis, officia ea officiis reprehenderit, omnis quos quod nulla esse sint facilis, quae odio itaque sunt amet tempora? Placeat, asperiores ratione quaerat possimus eaque sit inventore tenetur, deserunt ducimus excepturi fuga? Maxime praesentium obcaecati inventore a error fuga nulla est exercitationem corrupti iusto? Provident illum itaque, quidem unde tempore doloribus ad iste eaque beatae suscipit corporis atque dolores magnam. Recusandae adipisci illum maxime. --> <!-- </section> <br /> <section> Lorem ipsum dolor sit amet consectetur adipisicing elit. Cupiditate veniam molestiae nesciunt deserunt voluptas accusantium, odit et ad tempore iure itaque ducimus ut enim voluptatem incidunt voluptates quisquam obcaecati labore fugit. Necessitatibus unde laborum fugiat autem deserunt doloremque similique consequatur totam eum? Labore enim, iure ad, eos reiciendis accusamus voluptates nam sed vel eveniet quam, in voluptatibus laboriosam itaque error numquam corrupti ipsam beatae? Repudiandae saepe voluptate, sapiente eaque at magnam officia deleniti quas quae aspernatur? Saepe natus distinctio dicta debitis fugiat veniam ullam perferendis laborum accusantium suscipit enim accusamus aliquam numquam blanditiis, maiores eveniet hic dolores ipsa! Amet, voluptatibus? </section> --> <!-- <br /> <article> Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab debitis commodi, aspernatur unde tempora assumenda ut culpa dolores numquam. Magnam in similique debitis! Officia voluptates nesciunt molestias expedita molestiae, quod animi provident quia aliquid eveniet, aliquam perspiciatis minima corrupti sint quam similique ut soluta architecto, sit optio. Vel dolore, optio consequatur ex repellat temporibus provident possimus eveniet. Voluptate error laborum doloribus distinctio aliquid repellat. Enim, illum earum maxime deserunt rem vel nihil doloribus itaque nobis atque dolor, iure sed incidunt laborum sapiente debitis porro nesciunt reprehenderit est cupiditate voluptatem! Itaque --> <!-- beatae non rerum aliquam, temporibus sint eaque omnis sed quos iusto, labore laborum dolores quis, deserunt totam tenetur. Sunt iste atque vel qui, velit illum recusandae! Assumenda consequuntur recusandae quo enim eum. Esse totam cumque ducimus officiis repellat, possimus illum ipsa exercitationem delectus cum distinctio earum repellendus ex odio maxime a placeat at dolores. Iusto, natus beatae qui sapiente nemo in, veritatis quibusdam inventore ut quam numquam. Consectetur, ut. Totam architecto, quis maiores accusamus ipsam incidunt omnis nam officia doloremque, voluptatum repudiandae, accusantium eveniet! Eligendi totam tempore, possimus repellat cumque, facilis vitae deleniti quasi ipsa aspernatur labore quisquam enim? Fuga, quis ad quo quam repellendus illo deleniti porro quas sequi! </article> --> <!-- </main> <footer> <center><h4>contact us : xyz@gmail.com</h4></center> </footer> <br /><br /><br /><br /> <br /><br /><br /><br /> <br /><br /><br /><br /> <br /><br /><br /><br /> <br /><br /><br /><br /> <br /><br /><br /><br /> --> <!-- <header> <pre> Home Products about us </pre > </header> --> <div> <h1>Div 1</h1> <p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Similique illo quaerat, <span style="color:crimson" >veniam asperiores quos vitae suscipit debitis in illum nostrum, </span> aspernatur natus aperiam fugit beatae aliquid inventore fugiat, nemo ipsa. </p> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed, laboriosam. Quaerat vitae soluta, odio at aspernatur eveniet iure facilis voluptatem mollitia laborum quisquam impedit, omnis ipsum nulla doloremque hic consequuntur. </p> </div> <br /><br /> <div style="background-color:brown">Hello World</div> <br /><br /> <span style="background-color:rgb(86, 86, 185) ">Hello World</span> </body> </html>index_2.html<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> <link href="style.css" rel="stylesheet" /> </head> <body> <div> <h1 class="color_pink">Heading 1</h1> <h1>Heading 2</h1> <h1>Heading 3</h1> <h2>Heading</h2> <p class="color_pink"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eius commodi hic nostrum harum rerum earum nihil? Rerum asperiores nam aut, dolores quaerat quia aliquam nisi quod ipsum blanditiis vitae animi eaque quis excepturi id earum voluptatem distinctio recusandae sapiente totam aperiam dignissimos in! Facilis aliquam tempore iure modi id labore? </p> <br /> <a href="https://www.google.com/">Google</a> </div> <br /> <br /> <p class="color_pink"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat beatae facilis architecto blanditiis? Repellendus commodi ullam illo pariatur, minus itaque! Rerum harum cupiditate impedit omnis? At, suscipit optio in, sunt illo necessitatibus ex ad blanditiis tempora ipsam aspernatur earum quo doloremque mollitia numquam distinctio accusantium. Excepturi at voluptas tempora ducimus. </p> <br /> <h2>Sub Heading</h2> <p class="color_pink"> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Reprehenderit maiores, hic quis perferendis quo error mollitia consectetur cum! Culpa sapiente ipsam odio. Et ea repudiandae distinctio qui laudantium odit reprehenderit id voluptate iusto hic, libero doloribus, aperiam fuga? Totam voluptates consequuntur nulla minima repudiandae, blanditiis ipsa dolorem eveniet repellat error! </p> <br /> <p> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Officia iste pariatur ipsa est veniam provident assumenda sunt non, nobis at aperiam odit sit quas vero alias cum, eaque id quisquam debitis suscipit illum itaque culpa eligendi! Numquam pariatur, nostrum dolore dicta excepturi eligendi, magnam mollitia velit provident harum quaerat saepe. </p> </body> </html>home.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>My Personal Profile</title> </head> <body> <header> <center> <h1>Emily Jones</h1> <p>Welcome to my personal profile page!</p> </center> </header> <main> <center> <img src="download (2).jpg" alt="A photo" width="150" /> <section> <h2>About Me</h2> <p style="color:crimson"> Hello! I'm <em>Emily</em>, I am learning web development. </p> </section> </center> <br /><br /><br /> <section> <h2>Hobbies</h2> <article> <p>In my free time, I enjoy:</p> <ul> <li><b>Coding</b></li> <li><i>Reading</i></li> <li><u>Traveling</u></li> </ul> </article> <p>One of my favorite activities is <mark>painting</mark>.</p> </section> <section> <h2>Contact Me</h2> <form> <label for="name">Name:</label><br /> <input type="text" id="name" /><br /><br /> <label for="email">Email:</label><br /> <input type="email" id="email" /><br /><br /> <label for="num">Contact number</label><br /> <input type="number" id="num" /><br /><br /> <label>Preferred Contact Method:</label><br /> <input type="radio" name="contact" /> <label for="emailContact">Email</label><br /> <input type="radio" name="contact" /> <label for="phoneContact">Phone</label><br /><br /> <input type="submit" /> </form> </section> <section> <h2>Goals</h2> <p>Here are some of my goals:</p> <input type="checkbox" /> Learn JavaScript<br /> <input type="checkbox" /> Build a personal website<br /> <input type="checkbox" /> learn AI/ML<br /> </section> </main> <footer> <p style="color:crimson">email: xyz@gmail.com</p> </footer> </body> </html>style.cssh1 { text-align: center; text-decoration: underline; text-decoration-color: black; text-decoration-style: wavy; border-style: dotted; border-color: rgb(216, 91, 91); font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif; } p{ font-family: cursive; } a{ text-decoration: none; color:black }CSS.txtCASCADING STYLE SHEETS: --------------------------------------------- A stylesheet is a separate component that is merged with HTML pages. It is used for giving a special appearance to an HTML page. Syntax: selector { key:value; } It is a key/value pair where value can be predefined/user-defined. more than one key/value pair can be joined by a semicolon. stylesheet syntaxes are highly case-sensitive and all keys are generally in small cases. ----------------------------------------------------------------------------------------------------------------------------------------------- There are three types of stylesheets: 1. External Stylesheet: A seperate file is created with extension as .css. This css file is then linked into the HTML page as: ex- <link href="yourcssfile.css" rel="stylesheet" /> Link tag must be written inside <head> tag. 2. Internal Stylesheet: It is specific to one particular page. syntax: <head> <style> selector { property: value; } </style> </head> 3. Inline Stylesheet: It is specific to one particular HTML element/tag. All HTML elements have \"style\" attribute. This attribute is used to specify stylesheet key/value pairs. More than one key/value pairs are joined by a semicolon. ex- <table style="background-color: red; color: blue; font-weight: bold;"> ... </table> ------------------------------------------------------------------------------------------------------------------------------------------------------ Stylesheet can be written in 3 ways: 1. stylesheet for an element/tag- for <body>: syntax: body { background-color: blue; } for <p>: syntax: p { background-color: cyan; color: blue; font-weight: bold; } 2. stylesheet class- A class is used to group certain HTML elements together. A class is created using a . (dot) ex: .myclass1 { background-color: blue; color: white; font-weight: bold; } 3. stylesheet id- It is a unique identifier for an HTML element. An id is used using a # symbol ex: #myid { background-color: blue; color: cyan; font-weight: bold; } ------------------------------------------------------------------------------------------------------------------------------- Comment: css comment: /* single/multine comment.... */block_vs_inline_diagram.pngoriginal.pnghttps://www.w3schools.com/html/html_intro.asp?authuser=0https://www.w3schools.com/css/?authuser=023 Octindex.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="style.css" /> </head> <body> <!-- <div></div> <h1>Heading</h1> --> <div></div> <div></div> <div></div> </body> </html>style.css/*div { height: 100px; width: 100px; background-color: crimson; border-width: 3px; border-style: dashed; border-color: darkblue; border: 3px solid darkblue; border-radius: 50%; } h1{ width: 150px; border: 1px solid black; padding: 20px 30px 40px 50px; margin: 50px; }*/ div{ height: 100px; width:100px; background-color: cornflowerblue; margin:20px; display: inline-block; border-radius: 50%; }boxModelCSS.txtCSS Box Model: In CSS, "box model" is a concept that represents how all elements on a webpage are structured inside rectangular boxes These boxes have four main components: Content: This is where the actual text, images, or other content of the element is placed. Padding: The padding is a space around the content, It provides some distance between the content and the border. Border: It's a visible border that surrounds the content and padding, defining the element's outer edge. Margin: The margin is an invisible space outside the border, creating separation between elements.download.pngDemo.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style>body { background-color: crimson; } div { height: 205px; width: 200px; text-align: center; background-color: white; padding: 20px; margin-left: auto ; margin-right: auto; }</style> </head> <body> <div> <h1>Login Form</h1> <p>Login to access your dashboard</p> <form action=""> <input type="text" placeholder = "enter E-mail"><br> <input type="password" placeholder="password"><br> </form> <button>Login</button> </div> </body> </html>home.html<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style_1.css" /> <style> #pera1 { border-style: dotted; border-color: rgb(216, 91, 91); font-family: cursive; } h1 { color: black; } #pera1 { color: tomato; } div { background-color: coral; } .yellow_background { background-color: rgb(228, 228, 132); } * { color: crimson; } </style> <title>Document</title> </head> <body> <h1 style="color:rgb(126, 126, 166); ">Heading 1</h1> <p id="pera1"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Mollitia hic accusamus voluptas quae laudantium voluptates, ipsum magnam sequi quod perferendis error magni consectetur eius quidem aliquid eligendi voluptatibus. Adipisci cum saepe enim autem nisi unde. Veniam, debitis. Repellat, voluptate! Consequuntur eius explicabo numquam maxime provident non eligendi cum tenetur, officiis earum. Quos at mollitia vel omnis cumque? Unde culpa, commodi illum aliquid autem nostrum? Neque quam sapiente iusto rem! Nihil distinctio minima temporibus quos sit atque maiores earum ipsum! Laudantium culpa eos quis sunt enim! Obcaecati rerum qui labore! Velit ex quae eveniet reprehenderit odit nostrum consectetur omnis obcaecati explicabo. </p> <br /><br /><br /> <h3 class="yellow_background">Sub Heading</h3> <h3 class="yellow_background">Sub Heading 2</h3> <p class="yellow_background"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nostrum, iure quaerat. Natus, sunt saepe quaerat hic eius at ipsum assumenda excepturi, dolorem incidunt culpa quis quibusdam aut non mollitia sit! </p> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus aliquam dolorum optio. Saepe nobis et quisquam eveniet eum sed magnam molestias! Assumenda eaque laborum neque molestias. Quam repellendus nemo impedit corporis, minima saepe aut debitis suscipit at delectus eveniet illum laudantium consequuntur eum minus ipsum iusto sequi officiis est perspiciatis quisquam quidem odio! Accusantium nisi illum labore debitis, rerum saepe nostrum fuga laborum ducimus ea temporibus voluptatem cupiditate eius nulla id, expedita, enim repudiandae soluta. Sed impedit, vel praesentium ipsa fugit culpa architecto officiis porro? Adipisci distinctio praesentium repellat quidem nam dolor voluptates consectetur sit ipsam aspernatur. Delectus cumque itaque quas eius quod, accusantium omnis. Eius enim corporis quia sint porro nulla, numquam ea delectus nemo quaerat perspiciatis molestiae sunt vel deserunt dolor, explicabo natus, voluptas laboriosam debitis expedita? Quam nobis laudantium in sit labore rem, ipsum fugit quas nisi, saepe aperiam ab ea? Aut modi natus deserunt ex illum harum nobis repudiandae unde iure, non laborum obcaecati vitae nam deleniti iste! Eius, provident quibusdam suscipit deserunt exercitationem voluptatem nemo aut a doloribus doloremque placeat porro commodi optio ex quo. Reiciendis quibusdam ab, optio, unde praesentium quas corrupti aliquid dolorem, eos voluptatibus consequatur facere vitae sunt dicta! Illum magni, voluptatum sed saepe consequuntur ea nemo laboriosam modi quas facilis tenetur quos aperiam voluptates, nesciunt soluta laborum nobis. Vero reprehenderit, voluptatem beatae maiores facere dolore ipsum harum impedit, enim illo, ut earum adipisci? Consequuntur et nobis rerum accusamus similique quidem suscipit perferendis est quibusdam, doloremque explicabo eius minus! Veritatis odit voluptates ex tempore perspiciatis iusto molestias, fuga id tempora similique. Aperiam aliquam numquam cum iste vel error laboriosam minima. Nulla, magni accusamus delectus voluptatum cupiditate saepe amet, excepturi praesentium earum officia architecto esse quia? Ab quasi nihil esse eaque nesciunt neque eius vitae nemo voluptatibus, inventore nisi error, fuga adipisci doloremque! </p> <br /><br /> <p class="yellow_background"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur libero vel quidem, odit ratione veritatis. </p> <br /><br /> <a href="https://www.google.co.in/">Google</a> <p id="pera2"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis, natus minus, corporis quod blanditiis illum earum tempore iure deleniti nesciunt suscipit quisquam, quia et. Voluptas laudantium accusamus delectus repellendus quibusdam! </p> </body> </html>style_1.cssh1{ /*background-image: url("images.jpg"); background-size: cover;*/ text-align: center; text-decoration: underline; text-decoration-style: wavy; text-decoration-color: blueviolet; } a{ text-decoration: none; color: black; } #pera1{ border-style: dotted; border-color: rgb(216, 91, 91); font-family: cursive; } #pera2{ border-style: double; border-color: olive; }23 Oct28 OctORM.pyimport pyodbc as p def getConnection(): connection = p.connect(r'Driver=SQL Server; Server=DESKTOP-21MU0SK\SQLEXPRESS;Database=master_2;') cursor = connection.cursor() return cursor class Model: def fetch(self): cursor = getConnection() cursor.execute("select * from EMPLOYEE") rows = cursor.fetchall() return rows def save(self): cursor = getConnection() cursor.execute(f"Insert into Employee values({self.empNo},'{self.empName}','{self.Designation}',{self.Salary},{self.join_date},{self.DeptNo},'{self.empAddress}')") cursor.commit() print("row inserted successfully") def update(self): cursor = getConnection() cursor.execute(f"update EMPLOYEE set empName = '{self.empName}', Designation = '{self.Designation}', join_date = {self.join_date}, Salary = {self.Salary}, DeptNo = {self.DeptNo}, empAddress = '{self.empAddress}' where empNo = {self.empNo}") cursor.commit() print("Employee Updated Successfully!") def delete(self): cursor = getConnection() cursor.execute(f"delete from EMPLOYEE where empNo = {self.empNo}") cursor.commit() print("row deleted successfully")models.pyimport ORM class Employee(ORM.Model): def __init__(self, empNo= 100, empName= 'Harry', Designation= 'IT Expert', join_date = '2020-09-09', Salary= 3000, DeptNo= 3, empAddress = 'VIP Road'): self.empNo = empNo self.empName = empName self.Designation = Designation self.join_date = join_date self.Salary = Salary self.DeptNo = DeptNo self.empAddress = empAddress def __str__(self): return (f"Employee No: {self.empNo}\n" f"Name: {self.empName}\n" f"Designation: {self.Designation}\n" f"Join Date: {self.join_date}\n" f"Salary: ${self.Salary}\n" f"Department No: {self.DeptNo}\n" f"Address: {self.empAddress}")views.pyfrom models import Employee def getEmployees(): objEmp = Employee() rows = objEmp.fetch() empList = [] for row in rows: employee = Employee(empNo= row[0], empName = row[1], Designation= row[2],join_date = row[3], Salary= row[4], DeptNo= row[5], empAddress = row[6]) empDict = employee.__dict__ empList.append(empDict) return empList def addEmployee(empNo, empName, Designation, join_date, Salary, DeptNo, empAddress): objEmp = Employee(empNo, empName, Designation, join_date, Salary, DeptNo, empAddress) objEmp.save() def updateEmployee(empNo, empName, Designation, join_date, Salary, DeptNo, empAddress): objEmp = Employee(empNo, empName, Designation, join_date, Salary, DeptNo, empAddress) objEmp.update() def deleteEmployee(empNo): objEmp = Employee(empNo) objEmp.delete()templates.pyimport views from models import Employee user_input= input("enter 'GET' to fetch data, 'ADD' to insert data, 'UPDATE' to update data & 'DELETE' to Delete data: ") if user_input == 'GET': rows = views.getEmployees() print(rows) elif user_input == 'ADD': empNo = input("Enter Employee no: ") empName = input("Enter your Name: ") Designation = input("Enter Desgnation: ") join_date = input("Enter join date: ") Salary = input("Enter Salary: ") DeptNo = input("Enter department no: ") empAddress = input("Enter Address: ") views.addEmployee(empNo, empName, Designation, join_date, Salary, DeptNo, empAddress) elif user_input == 'UPDATE': empNo = input("Enter Employee no: ") empName = input("Enter your Name: ") Designation = input("Enter Desgnation: ") join_date = input("Enter join date: ") Salary = input("Enter Salary: ") DeptNo = input("Enter department no: ") empAddress = input("Enter Address: ") views.updateEmployee(empNo, empName, Designation, join_date, Salary, DeptNo, empAddress) elif user_input == 'DELETE': empNo = input("Enter Employee no: ") views.deleteEmployee(empNo) else: print("please enter a valid commandx")28 OctJavascript.txtJAVASCRIPT JavaScript is a programming language that is primarily used for web development. It allows developers to add interactive elements, dynamic content, and behavior to websites. It is a high-level, interpreted language, which means it is executed directly by web browsers without the need for compilation. It is an advanced programming language that makes web pages more interactive and dynamic. JavaScript is widely supported by all modern web browsers and is an essential component of web development. It has a relatively easy-to-learn syntax and is known for its flexibility and versatility. * Some key features and uses of JavaScript: 1. Client-Side Scripting: Most JavaScript code runs in the user's browser, meaning it can reduce server load and provide a smoother experience by processing data locally. 2. DOM manipulation: JavaScript provides powerful tools for manipulating the Document Object Model (DOM) of a web page. It allows developers to access and modify the structure, content, and styling of HTML elements dynamically. 3. Event handling: JavaScript enables developers to define event handlers that trigger specific actions or behaviors when certain events occur such as mouse clicks, keyboard input, and form submissions. 4. Asynchronous programming: With features like Promises and async/await, JavaScript can handle tasks that take time (like fetching data from a server) without blocking the rest of the code from running. 5. Frameworks and libraries: JavaScript has a vast ecosystem of frameworks and libraries that extend its capabilities. Examples include React, Angular, and React Native. 6. Versatile: JavaScript can be used in a variety of contexts and for different purposes, i.e., it can be used for both front-end (what users see) and back-end (server-side) development, especially with frameworks like Node.js. Frameworks like React Native allow developers to build mobile applications for iOS and Android using JavaScript, making it easier to create cross-platform apps. 7. Dynamically typed language: JavaScript is a dynamically typed language. This means that you don't need to specify the data type of a variable when you declare it. The type is determined at runtime based on the value assigned to the variable. ----------------------------------------------------------------------------------------------------------------------------- * Datatypes in JS: 1. Number: Represents numeric values, including integers and floating-point numbers. 2. String: Represents sequences of characters enclosed in single quotes ('') or double quotes (""). 3. Boolean: Represents a logical value, either true or false. 4. Null: Represents the intentional absence of any object value. 5. Undefined: Represents a variable that has been declared but has not been assigned a value. 6. Symbol: Represents a unique identifier. Symbols are used to create private object properties and other advanced use cases. # ---------------------------------------------------------------------------- Composite Data Types: In programming, composite data types are those that can hold multiple values or a collection of other data types. 1. Object: Represents a collection of key-value pairs. Objects can be created using object literals {} or using the new Object() constructor. 2. Array: Represents an ordered list of values. Arrays are created using square brackets [] and can contain elements of any data type. 3. Function: Represents reusable blocks of code that can be invoked or called. Functions can take parameters, perform operations, and return values. III. Special Data Types: 1. BigInt: Represents arbitrary precision integers. It is used when numbers exceed the maximum value that can be represented by the Number type. 2. Date: Represents a specific date and time.JavaScript_basics.txt<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> <!-- <script> // printing a statement in JavaScript // console.log("hello") // printing a warning in JavaScrript // console.warn("This is a warning") // printing an error in JavaScript // console.error('This is an error') // Datatypes - string, number, booelean // string - characters, special char, numbers everything written in single or double // quotes // number - all numbers // boolean - True or False // checking a datatype // console.log(typeof(10)) // console.log(typeof('10')) // variables in JS - container to store any value / memory location // a = 10 // b = 5 // x = 7 // y = 7 // console.log(x == y) // console.log(x!=y) // console.log(x) // ------------------------------------------------------------------------- //var a = "apple"; //var b = "apple"; //console.log(a == b); //var sym1 = Symbol("apple"); //var sym2 = Symbol("apple"); //console.log(sym1 == sym2); // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Operators - // Addition: // console.log(x+y) // sum = x+y // console.log(sum) // Subtraction: // difference = a-b // console.log(difference) // Multiplication: // console.log(a*b) // Division: // console.log(x/b) // Modulus: // console.log(x%b) // power: // console.log(a**b) // --------------------------------------------------------------- // let, var and const // var - can be redeclared and reassigned, function scoped // let - cannot be redeclared but can be reassigned, object scoped // const - neither redeclared nor reassigned, object scoped // var name=3 // console.log(a) // var name=5 // console.log(a) // let b = 23 // console.log(b) // b = 2 // console.log(b) // const x = 12 // console.log(x) // x = 'hello' // it will raise an error // console.log(x) // ----------------------------------------------------------------------------- Conditional (Ternary) Operator: let num = 5; let condition = num == 10 ? "true" : "not true"; console.log(condition); // -------------------------------------------------------------------------- let age = 18; let canVote = age >= 18 ? "Yes, can vote" : "No, cannot vote"; console.log(canVote); </script> --> </html>Hoisting_in_JS.txtHoisting: Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope, before the code is executed. 1. Variable Hoisting var Declarations: Variables declared with var are hoisted to the top of their enclosing function or global scope. However, only the declaration is hoisted, not the initialization. console.log(x); var x = 5; console.log(x); In this example, var x is hoisted to the top, so the first console.log outputs undefined because the variable is declared but not yet initialized. // --------------------------------------------------------------------------------------------------- let and const Declarations: Variables declared with let and const are also hoisted, but accessing them before the declaration results in a ReferenceError due to a "temporal dead zone(TDZ) console.log(y); let y = 10; // --------------------------------------------------------------------------------------------------- 2. Function Hoisting Function Declarations: Entire function declarations are hoisted, meaning you can call a function before it is defined in the code. greet(); function greet() { console.log("Hello!"); } // -------------------------------------------------------------------------------------------------- Function Expressions: If you assign a function to a variable (either with var, let, or const), only the variable declaration is hoisted, not the function itself. sayHi(); var sayHi = function() { console.log("Hi!"); }; // ------------------------------------------------------------------------------------------------ Summary of Hoisting Behavior: var: Declarations are hoisted, but not initializations. Resulting in undefined if accessed before assignment. let and const: Declarations are hoisted but cannot be accessed before their initialization (temporal dead zone). Function Declarations: Fully hoisted, can be called before their definition. Function Expressions: Only the variable declaration is hoisted, leading to potential errors if invoked before assignment. // ------------------------------------------------------------------------------------------------- To avoid confusion and potential errors caused by hoisting: Declare variables at the top of their scope. Prefer using let and const over var for better block scope management. Always define functions before calling them, unless using function declarations.https://www.w3schools.com/js/?authuser=029 OctJavaScript_basics_2.txtindex.htmlConditional (Ternary) Operator: let num = 5; let condition = num == 10 ? "true" : "not true"; console.log(condition); // -------------------------------------------------------------------------- let age = 18; let canVote = age >= 18 ? "Yes, can vote" : "No, cannot vote"; console.log(canVote); // ------------------------------------------------------------- // ------------------------------------------------------------- // logical operators in JS: // && - Logical AND // let a = 10; // let b = 20; // console.log(a == 10 && b != 20); // ------------------------------------------------------------- // || - Logical OR // console.log(a != 10 || b != 20); // ------------------------------------------------------------- // ! - Logical NOT // let c = 5; // let d = 10; // console.log(!(c < d)); // console.log(!(c > d)); -------------------------------------------------------------------------------------------- ----------------------------------- Common escape sequences characters in JavaScript: \": Represents a double quote within a double-quoted string. \': Represents a single quote within a single-quoted string. \\: Represents a literal backslash. \n: Represents a newline character. \t: Represents a tab character. --------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------- alert function : In JavaScript, the alert() function is a built-in function that displays a dialog box with a message and an OK button. It is commonly used to show a simple notification to the user. alert('hello world') --------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------- confirm function : In JavaScript, the confirm() function is used to display a dialog box with a message and two buttons - OK and Cancel buttons. The confirm() function is a simple way to get user input for a "yes" or "no" decisions and is commonly used for tasks where user confirmation is required before performing an action. confirm("Do you want to delete this item?") -------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- prompt() is used take input from a user : let userName = prompt("enter your name: "); console.log("Hello", userName); let num1 = prompt("enter number 1: "); let num2 = prompt("enter number 2: "); console.log(num1 + num2); ----------------------------------------------------------------------------------------- ---------------------------------------------------- // Type casting in JavaScript: parseInt() is used to convert a string into a number : let num1 = parseInt(prompt("enter number 1: ")); let num2 = parseInt(prompt("enter number 2: ")); console.log(num1 + num2); String() is used to convert a number into a string: let num = 42; let str = String(num); console.log(str); console.log(typeof str); toString() is also used to convert a number into a string: let str_1 = num.toString(); console.log(str_1); console.log(typeof str_1);Operators.txt--------------------------------------------- OPERATORS IN JS --------------------------------------------- * Some commonly used operators in JavaScript: I. Arithmetic Operators: 1. + Addition: Adds two values together. 2. - Subtraction: Subtracts the second value from the first. 3. * Multiplication: Multiplies two values. 4. / Division: Divides the first value by the second. 5. % Modulo: Returns the remainder of the division. 6. ++ Increment: Increases the value by 1. 7. -- Decrement: Decreases the value by 1. II. Assignment Operators: 1. = Assignment: Assigns a value to a variable. 2. += Addition assignment: Adds and assigns a value. 3. -= Subtraction assignment: Subtracts and assigns a value. 4. *= Multiplication assignment: Multiplies and assigns a value. 5. /= Division assignment: Divides and assigns a value. 6. %= Modulo assignment: Performs modulo operation and assigns a value. III. Comparison Operators: 1. == Equal to: Checks if two values are equal. 2. === Strict equal to: Checks if two values are equal. 3. != Not equal to: Checks if two values are not equal. 4. !== Strict not equal to: Checks if two values are not equal. 5. > Greater than: Checks if the left value is greater than the right value. 6. < Less than: Checks if the left value is less than the right value. 7. >= Greater than or equal to: Checks if the left value is greater than or equal to the right value. 8. <= Less than or equal to: Checks if the left value is less than or equal to the right value. IV. Logical Operators: 1. && Logical AND: Returns true if both operands are true. 2. || Logical OR: Returns true if at least one of the operands is true. 3. ! Logical NOT: Returns the inverse boolean value of the operand. V. String Operators: 1. + Concatenation: Concatenates two strings together. VI. Conditional (Ternary) Operator: 1. condition ? value1 : value2: Evaluates the condition and returns value1 if true, or value2 if false.template_literals_Js.txtES6: ECMAScript 6 (ES6), also known as ECMAScript 2015, is a significant update to the JavaScript language that introduced a variety of new features and improvements. Here are some of the key features of ES6: Key Features of ES6: 1. Let and Const: Introduced let and const for variable declarations, providing block scope. let x = 10; // mutable const y = 20; // immutable 2. Arrow Functions: A more concise syntax for writing function expressions. const add = (a, b) => a + b; 3. Template Literals: Template literals allow you to create dynamic strings with embedded expressions and multi-line support. 4. Default Parameters, 5. Promises(), 6. Iterators and Generators and much more. // ------------------------------------------------------------------------------------------------ // JavaScript Template Literals: // a string using backticks (``). The expressions within ${} are evaluated and their values are inserted into the resulting string. // ex- let name1 = "Alice"; let greeting = `Hello, ${name1}!`; console.log(greeting); // -------------------------------------------------------------------------------------------- let Name = prompt("enter your name: "); let Age = prompt("enter your age: "); console.log(`the name of the user is ${Name} and the age is ${Age}`);If_else_Js.txtif-else in JavaScript: In JavaScript, an "if-else" statement is a conditional statement that allows you to execute different blocks of code based on a specified condition. It's used to make decisions in your code by evaluating whether a condition is true or false. Questions to practice "if-else": let age = 18; let user_age = parseInt(prompt("enter your age:")); if (user_age >= age) { console.log("you are eligable to vote"); } else { console.log("not eligable"); } //--------------------------------------------------------------------------------------------------------- let num1 = parseInt(prompt('enter a number')) let num2 = parseInt(prompt('enter another number')) if (num1 > num2){ console.log(`${num1} is greater than ${num2}`) } else if(num1 < num2){ console.log(`${num1} is smaller than ${num2}`) } else{ console.log(`${num1} and ${num2} are equal`) } //----------------------------------------------------------------------------------------------------------- let num = parseInt(prompt('enter a number') if (num>0){ console.log('Positive') } else if(num<0){ console.log('negative') } else{ console.log('neither positive nor negative') } //---------------------------------------------------------------------------------------------------------- let num = parseInt(prompt("enter a number: ")); if (num % 4 == 0) { console.log("Number is divisible by 4"); } else { console.log("Number is not divisible by 4"); } //--------------------------------------------------------------------------------------------------------- let score = 85; if (score >= 90) { console.log("You got an A."); } else if (score >= 80) { console.log("You got a B."); } else if (score >= 70) { console.log("You got a C."); } else if (score >= 60) { console.log("You got a D."); } else { console.log("You failed the exam."); }index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="index.js"></script> </head> <body> <h1>Java Script</h1> </body> <!-- <script> console.log("hiii"); </script> --> </html>index.js// console.log("Hello World"); // console.warn("this is a warning!"); // console.error("this is an error"); // x = 5; // console.log(x); // console.log(x); // var x = 5; // console.log(a); // let a = 10; // console.log(b); // const b = 5; // console.log(a); // var a = 10; // can re-declare and re assign the values // var a = 12; // let b = 16; // cannot re-declare but can re assign the value // b = 12; // console.log(b); // const c = 100; // cannot re-declare nor re-assign the value // c = 112; // console.log(Name1); // var Name1 = "abc"; // console.log(Name); // const Name = "xyz"; // let a = "100"; // console.log(typeof a); // let b = true; // console.log(typeof b); // let a = Symbol("apple"); // let b = Symbol("apple"); // console.log(a == b); const a = 10; const b = 20; // const sum = a + b; // console.log(sum); // console.log(a == 10 && b == 10); // console.log(a == 10 || b == 50); // console.log(!(a == 10 || b == 50)); // console.log(!(a == 10)); // Ternary operator: // let age = 18; // user_age = prompt("enter your age: "); // let canVote = user_age >= age ? "eligable to vote" : "not eligable"; // console.log(canVote); // ------------------------------------------------------------- // alert("Hello World"); // confirm("are you sure, you want to delete this value ?"); // let num_1 = parseInt(prompt("enter number 1: ")); // let num_2 = parseInt(prompt("enter number 2: ")); // console.log(num_1 + num_2); // let num_3 = 10; // let newNumber = String(num_3); // console.log(typeof newNumber); // let num = 10; // let str_1 = num.toString(); // console.log(str_1); // console.log(typeof str_1); // ---------------------------------------------------- // Template Literals in JS: // let Name = prompt("enter you name: "); // let greeting = `Hello ${Name}`; // console.log(greeting); // let Name1 = prompt("enter your name: "); // let Age = prompt("enter your age: "); // console.log(`the name of the user is ${Name1} and the age is ${Age}`); // Conditional Statements: let num_1 = 12; if (num_1 == 10) { console.log("yes, num_1 = 10"); } else { console.log("no! num is not equal to 10"); }30 Octswitch.txtSwitch Statement in Java Script: A switch expression is a way to choose between different options based on a value. Here’s how it works: 1. Evaluate the expression: You start with a value that you want to check. 2. Compare with cases: The value is compared to a list of possible options (cases). 3. Execute the match: If it finds a match, it runs the code associated with that option. 4. Default case: If there’s no match, it runs a special block of code called the default. let fruit = "apple"; switch (fruit) { case "banana": console.log("found banana!"); break; case "pine-apple": console.log("found apple!"); break; case "kiwi": console.log("found kiwi!"); break; default: console.log("not found"); break; } // --------------------------------------------------------------------- let dayNumber = 3; switch (dayNumber) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; case 4: console.log("Thursday"); break; case 5: console.log("Friday"); break; case 6: console.log("Saturday"); break; case 7: console.log("Sunday"); break; default: console.log("Invalid day number!"); }string_methods_JS.txtStrings in Java Script : 1. strings are immutable in JavaScript. This means that once a string is created, it cannot be changed. Any operation that appears to modify a string actually creates a new string. 2. strings in JavaScript are indexed. Each character in a string can be accessed by its position, starting from 0 let str = "Java Script"; console.log(str[0]); console.log(str[5]); // -------------------------------------------------------------------------------------------------- '+' operator is the most common way to concatenate strings let firstName = prompt("enter your first Name: "); let lastName = prompt("enter your last Name: "); let fullName = firstName + " " + lastName; console.log(fullName); // -------------------------------------------------------------------------------------------------- // .length property: to find out the length of a string let string = "Hello"; console.log(string.length); // -------------------------------------------------------------------------------------------------- STRING METHODS: toUpperCase(): converts all characters in a string to uppercase. let greeting = "Hello, World!"; let greeting_2 = greeting.toUpperCase(); console.log(greeting_2); // -------------------------------------------------------------------------------------------------- toLowerCase(): converts all characters in a string to lowercase. let str = "HAVE A LOVELY DAY!"; let str_2 = str.toLowerCase(); console.log(str_2); console.log(str); // original string // -------------------------------------------------------------------------------------------------- trim(): removes whitespace from both ends of a string. let message = " Hello World! "; let trimmedMessage = message.trim(); console.log(trimmedMessage); // -------------------------------------------------------------------------------------------------- includes() checks if a string contains a specified substring and returns true or false. let phrase = "The quick brown fox"; let hasFox = phrase.includes("fox"); console.log(hasFox); // -------------------------------------------------------------------------------------------------- indexOf() returns the index of the first occurrence of a specified substring. If not found, it returns -1. let sentence = "I am learning the Java Script."; let index = sentence.indexOf("Java"); console.log(index); // ------------------------------------------------------------------------------------------------- slice() This method extracts a section of a string and returns it as a new string. let text = "Hello, World!"; let newText = text.slice(7, 12); let newText_1 = text.slice(0, 5); let newText_2 = text.slice(0, 6); console.log(newText); console.log(newText_1); console.log(newText_2); // ------------------------------------------------------------------------------------------------- split() splits a string into an array of substrings based on a specified delimiter. let fruits = "apple,banana,cherry"; let fruitsArray = fruits.split(","); console.log(fruitsArray); // -------------------- let sentence = "Learning JavaScript is fun and rewarding."; let words = sentence.split(" "); console.log(words); index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="index.js"></script> </head> <body> <h1>Java Script</h1> </body> <!-- <script> console.log("hiii"); </script> --> </html>index.js// console.log("Hello World"); // console.warn("this is a warning!"); // console.error("this is an error"); // x = 5; // console.log(x); // console.log(x); // var x = 5; // console.log(a); // let a = 10; // console.log(b); // const b = 5; // console.log(a); // var a = 10; // can re-declare and re assign the values // var a = 12; // let b = 16; // cannot re-declare but can re assign the value // b = 12; // console.log(b); // const c = 100; // cannot re-declare nor re-assign the value // c = 112; // console.log(Name1); // var Name1 = "abc"; // const Name = "xyz"; // Name = "abc"; // console.log(Name); // let a = "100"; // a = 12; // console.log(a); // let b = true; // console.log(typeof b); // let a = Symbol("apple"); // let b = Symbol("apple"); // console.log(a == b); const a = 10; const b = 20; // const sum = a + b; // console.log(sum); // console.log(a == 10 && b == 20); // console.log(a == 10 || b == 50); // console.log(!(a == 10 || b == 50)); // console.log(!(a == 10)); // Ternary operator: // let age = 18; // user_age = prompt("enter your age: "); // let canVote = user_age >= age ? "eligable to vote" : "not eligable"; // console.log(canVote); // ------------------------------------------------------------- // alert("Hello World"); // confirm("are you sure, you want to delete this value ?"); // let num_1 = parseInt(prompt("enter number 1: ")); // let num_2 = parseInt(prompt("enter number 2: ")); // console.log(num_1 + num_2); // let num_3 = 10; // let newNumber = String(num_3); // console.log(typeof newNumber); // let num = 10; // let str_1 = num.toString(); // console.log(str_1); // console.log(typeof str_1); // let num1 = parseInt(prompt("enter a number: ")); // let num2 = parseInt(prompt("enter another number: ")); // let sum = num1 + num2; // console.log(`the sum of ${num1} and ${num2} is ${sum}`); // Template Literals in JS: // let Name = prompt("enter you name: "); // let greeting = `Hello ${Name}`; // console.log(greeting); // let Name1 = prompt("enter your name: "); // let Age = prompt("enter your age: "); // console.log(`the name of the user is ${Name1} and the age is ${Age}`); // Conditional Statements: // let num_1 = 12; // if (num_1 == 10) { // console.log("yes, num_1 = 10"); // } else { // console.log("no! num is not equal to 10"); // } // let num = parseInt(prompt("enter a number: ")); // if (num > 0) { // console.log("positive number"); // } else if (num < 0) { // console.log("negative number"); // } else { // console.log("number is zero"); // } // let score = 85; // if (score >= 90) { // console.log("you've got an A"); // } else if (score >= 80) { // console.log("you've got a B"); // } else if (score >= 70) { // console.log("you've got a C"); // } else if (score >= 60) { // console.log("you've got a D"); // } else if (score >= 50) { // console.log("you've got an E"); // } else { // console.log("you have failed the exam!"); // } // let fruit = "apple"; // switch (fruit) { // case "banana": // console.log("found banana!"); // break; // case "apple": // console.log("found apple!"); // break; // case "kiwi": // console.log("found kiwi"); // break; // default: // console.log("not found"); // break; // } // let dayNumber = 3; // switch (dayNumber) { // case 1: // console.log("Monday"); // break; // case 2: // console.log("Tuesday"); // break; // case 3: // console.log("Wednesday"); // break; // case 4: // console.log("Thursday"); // break; // case 5: // console.log("Friday"); // break; // case 6: // console.log("Saturday"); // break; // case 7: // console.log("Sunday"); // break; // default: // console.log("Invalid day number!"); // } const string = "hello"; console.log(string.length); console.log(string[0]); let greeting = "Hello, World!"; let greeting_2 = greeting.toUpperCase(); console.log(greeting_2); console.log(greeting);(Edited 6 Nov)array_Js.txt// Array in Javascript - used to store collection of elements // let myArr = [20,30,40,50,60,70] // console.log("Array:",myArr) // Index - Accessing elements by their position // console.log("First Element:",myArr[0]) // console.log(myArr[4]) // console.log(myArr[1]) // console.log("Length of an Array:",myArr.length) // string array // let stringArray = ['dog', 'lion', 'horse', 'camel', 'bear'] // console.log(stringArray) // array with multiple data types // multArray = ['a',"a",'B',34, 35.7, true] // console.log(multArray) // -------------------------------------------------------- // let array1 = ['rose', 'lotus', 'marigold', 'lily', 'sunflower'] // console.log(array1) // push() - Adds element to the end of an array // array1.push('tulip') // console.log(array1) // adding multiple elements // array1.push("jasmine", "dandelion"); // console.log(array1) // pop() - Removes the last element from an array // array1.pop() // console.log(array1) // shift() - Removes the first element from an array // array1.shift(); //console.log(array1); //unshift() -Adds one or more elements to the beginning of an array. // array1.unshift("dandelion"); // console.log(array1); // let fruits = ["banana", "orange", "apple"]; // fruits.unshift("mango", "papaya"); // console.log(fruits); // ---------------------------------------------------------------- slice(): The slice() method in JavaScript is used to create a shallow copy of a portion of an array into a new array. It does not modify the original array and can be used to extract elements based on specified indices. syntax: array.slice(start, end) let fruits = ["apple", "banana", "cherry", "date"]; let slicedFruits = fruits.slice(1, 3); console.log(slicedFruits); console.log(fruits); // ------------------------------------ let numbers = [1, 2, 3, 4, 5]; let numberSlice = numbers.slice(-3, -1); console.log(numberSlice); // ---------------------------------------------------------------- splice(): The splice() function in JavaScript is used to change the contents of an array by adding, removing, or replacing elements. It modifies the original array and returns an array containing the removed elements It returns an array with the deleted items syntax: array.splice(start, deleteCount, item1, item2, ...) let fruits = ["banana", "orange", "apple"]; fruits.splice(1, 1, "kiwi"); console.log(fruits); // ---------------------------------------------------------------- let fruits = ["apple", "banana", "cherry", "date"]; let removedFruits = fruits.splice(1, 2); console.log(fruits); // ------------------------------------------------------------------ let numbers = [1, 2, 3, 4]; let replacedNumbers = numbers.splice(2, 1, 5); console.log(numbers); console.log(replacedNumbers); //--------------------------------------------------------------------------- join() combines all elements of an array into a single string. let fruits = ["Banana", "Orange", "Apple", "Mango"]; let string = fruits.join(); console.log(string); let string_2 = fruits.join(" - "); console.log(string_2 ); //--------------------------------------------------------------------------- sort() arranges the elements of an array in place and returns the sorted array, using a specified comparison function to determine the order // let strArray = ['b','z','i','a','m','s','y'] // console.log(strArray.sort()) //let numArray = [2, 5, 30, 1, 6, 8, 9, 4, 7, 10, 100000000] // console.log(numArray.sort()) let numArray = [2, 5, 30, 1, 6, 8, 9, 4, 7, 10, 100000000]; numArray.sort((a, b) => a - b); console.log(numArray); // ------------------------------------ reverse() reverses the order of the elements in an array in place and returns the modified array. console.log(numArray.reverse()); object_Js.txt// object in js- // It is used to store collection in the form of key, value pairs. // let obj1 = {'Name':'Jack','age':34,"Place":"Bhopal","Designation":"Trainer"} // console.log(obj1) // printing a value using keys of an object // console.log(obj1.age) // obj1['Place'] = 'India' // console.log(obj1) // obj1.Name = 'John' // console.log(obj1) // obj1['Qualification'] = 'B.Tech.' // console.log(obj1) // ------------------------------------------ // Nested Objects let Student = { Ben: { Age: 15, Address: "Bhopal" }, Skills: { Python: 4.5, JavaScript: 3.5 }, }; console.log(Student); // adding a key value to a nested object Student.Phone_No = 9898989898; Student.Skills.SQL = 5; console.log(Student); console.log(Student["Skills"]); console.log(Student["Skills"]["Python"]); Student["Skills"]["Python"] = 3; console.log(Student);<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="index.js"></script> </head> <body> <h1>Java Script</h1> </body> <!-- <script> console.log("hiii"); </script> --> </html>index.js12 Nov// console.log("Hello World"); // console.warn("this is a warning!"); // console.error("this is an error"); // x = 5; // console.log(x); // console.log(x); // var x = 5; // console.log(a); // let a = 10; // console.log(b); // const b = 5; // console.log(a); // var a = 10; // can re-declare and re assign the values // var a = 12; // let b = 16; // cannot re-declare but can re assign the value // b = 12; // console.log(b); // const c = 100; // cannot re-declare nor re-assign the value // c = 112; // console.log(Name1); // var Name1 = "abc"; // const Name = "xyz"; // Name = "abc"; // console.log(Name); // let a = "100"; // a = 12; // console.log(a); // let b = true; // console.log(typeof b); // let a = Symbol("apple"); // let b = Symbol("apple"); // console.log(a == b); const a = 10; const b = 20; // const sum = a + b; // console.log(sum); // console.log(a == 10 && b == 20); // console.log(a == 10 || b == 50); // console.log(!(a == 10 || b == 50)); // console.log(!(a == 10)); // Ternary operator: // let age = 18; // user_age = prompt("enter your age: "); // let canVote = user_age >= age ? "eligable to vote" : "not eligable"; // console.log(canVote); // ------------------------------------------------------------- // alert("Hello World"); // confirm("are you sure, you want to delete this value ?"); // let num_1 = parseInt(prompt("enter number 1: ")); // let num_2 = parseInt(prompt("enter number 2: ")); // console.log(num_1 + num_2); // let num_3 = 10; // let newNumber = String(num_3); // console.log(typeof newNumber); // let num = 10; // let str_1 = num.toString(); // console.log(str_1); // console.log(typeof str_1); // let num1 = parseInt(prompt("enter a number: ")); // let num2 = parseInt(prompt("enter another number: ")); // let sum = num1 + num2; // console.log(`the sum of ${num1} and ${num2} is ${sum}`); // Template Literals in JS: // let Name = prompt("enter you name: "); // let greeting = `Hello ${Name}`; // console.log(greeting); // let Name1 = prompt("enter your name: "); // let Age = prompt("enter your age: "); // console.log(`the name of the user is ${Name1} and the age is ${Age}`); // Conditional Statements: // let num_1 = 12; // if (num_1 == 10) { // console.log("yes, num_1 = 10"); // } else { // console.log("no! num is not equal to 10"); // } // let num = parseInt(prompt("enter a number: ")); // if (num > 0) { // console.log("positive number"); // } else if (num < 0) { // console.log("negative number"); // } else { // console.log("number is zero"); // } // let score = 85; // if (score >= 90) { // console.log("you've got an A"); // } else if (score >= 80) { // console.log("you've got a B"); // } else if (score >= 70) { // console.log("you've got a C"); // } else if (score >= 60) { // console.log("you've got a D"); // } else if (score >= 50) { // console.log("you've got an E"); // } else { // console.log("you have failed the exam!"); // } // let fruit = "apple"; // switch (fruit) { // case "banana": // console.log("found banana!"); // break; // case "apple": // console.log("found apple!"); // break; // case "kiwi": // console.log("found kiwi"); // break; // default: // console.log("not found"); // break; // } // let dayNumber = 3; // switch (dayNumber) { // case 1: // console.log("Monday"); // break; // case 2: // console.log("Tuesday"); // break; // case 3: // console.log("Wednesday"); // break; // case 4: // console.log("Thursday"); // break; // case 5: // console.log("Friday"); // break; // case 6: // console.log("Saturday"); // break; // case 7: // console.log("Sunday"); // break; // default: // console.log("Invalid day number!"); // } // const string = "hello"; // console.log(string.length); // console.log(string[0]); // let greeting = "Hello, World!"; // let greeting_2 = greeting.toUpperCase(); // console.log(greeting_2); // console.log(greeting); // Q. Write a program to create a calculator that performs three mathematical operations - // Addition, Subtraction, and Multiplication by user inputted numbers and operator and // returns a message for invalid operator otherwise. // let string = "Hello World!"; // console.log(string.length); // let string_2 = string.toUpperCase(); // console.log(string_2); // let string_3 = " hello "; // let string_4 = string_3.trim(); // console.log(string_4); // let phrase = "The quick brown fox"; // let hasFox = phrase.includes("fox"); // console.log(hasFox); // let sentence = "I am learning the Java Script."; // let index = sentence.indexOf("Java"); // console.log(index); // let text = "Hello, World!"; // let newText = text.slice(0, 5); // console.log(newText); // let fruits = "apple,banana,cherry"; // let fruitsArray = fruits.split(","); // console.log(fruitsArray); // let sentence = "Learning JavaScript is fun and rewarding."; // let words = sentence.split(" "); // console.log(words); // let greeting = "Hello, world!"; // let newGreeting = greeting.replace("world", "everyone"); // console.log(newGreeting); // let arr = [1, 2, 3, 4, 5, "apple", true]; // console.log(arr); // console.log(arr.length); // console.log(arr[1]); // console.log(typeof arr); // arr.push("hello", "orange"); // console.log(arr); // arr.pop(); // console.log(arr); // let arr = [1, 2, 3, 4, 5, "apple", true]; // arr.shift(); // // console.log(arr); // // arr.unshift("Hello"); // // console.log(arr); // let fruits = ["apple", "banana", "cherry", "date"]; // let slicedFruits = fruits.slice(1, 3); // console.log(slicedFruits); // console.log(fruits); // let numbers = [1, 2, 3, 4, 5]; // let numberSlice = numbers.slice(-4, -1); // console.log(numberSlice); // let fruits = ["banana", "orange", "apple"]; // fruits.splice(0, 0, "kiwi", "papaya"); // console.log(fruits); // let fruits = ["apple", "banana", "cherry", "date"]; // let removedFruits = fruits.splice(1, 2); // console.log(fruits); // console.log(removedFruits); // let numbers = [1, 2, 3, 4]; // let replacedNumbers = numbers.splice(0, 3, 5); // console.log(numbers); // console.log(replacedNumbers); // let obj = { // Name: "Ben", // age: 10, // address: "Bhopal", // }; // console.log(obj.Name); // obj["Name"] = "Hannah"; // console.log(obj); // obj["Hobby"] = "Coding"; // console.log(obj); // delete obj.Name; // console.log(obj); // let fruits = ["Banana", "Orange", "Apple", "Mango"]; // let string = fruits.join(); // console.log(string); // let string_2 = fruits.join(" - "); // console.log(string_2); // let strArray = ["b", "z", "i", "a", "m", "s", "y"]; // console.log(strArray.sort()); // let numArray = [2, 5, 30, 1, 6, 8, 9, 4, 7, 10, 100000000]; // console.log(numArray.sort()); // let numArray = [2, 5, 30, 1, 6, 8, 9, 4, 7, 10, 100000000]; // numArray.sort((a, b) => a - b); // console.log(numArray.reverse()); // let obj1 = { Name: "Jack", age: 34, Place: "Bhopal", Designation: "Trainer" }; // console.log(obj1); // delete obj1.Name; // console.log(obj1); // let Student = { // Ben: { Age: 15, Address: "Bhopal" }, // Skills: { Python: 4.5, JavaScript: 3.5 }, // }; // console.log(Student); // // // adding a key value to a nested object // Student.Phone_No = 9898989898; // Student.Skills.SQL = 5; // console.log(Student); // for (let i = 2; i < 10; i += 2) { // console.log(i); // } let array_1 = [1, 2, 3, true, "hello"]; for (let i = 0; i < array_1.length; i++) { console.log(array_1[i]); }forLoop_Js.txt// For Loop - A for loop in JavaScript is used for repeatedly executing a block of code for a specific number of times. It consists of three parts: initialization, condition, and increment/decrement, which work together to define the loop's behavior. The loop continues to run as long as the condition remains true and is often used to perform repetitive tasks. printing a same string 10 time: // for (let i = 0; i < 10; i++) { // console.log("Hello World"); // } // for (let i = 0; i < 10; i++) { // console.log(i); // } // for (i = 2; i < 10; i += 2) { // console.log(i); // } // -------------------------------------------------------------------------------- printing squares of 20 numbers: // for (let i = 1; i <= 20; i++) { // console.log(i ** 2); // } // table of two: // const num = 2; // for (i = 1; i <= 10; i++) { // console.log(num * i); // } // table of 9 with Template Literals: // let num = 9 // for (i=1; i<=10; i++){ // console.log(`${num} x ${i} = ${num*i}`) // } // ---------------------------------------------------------------------------------------------------- // printing all the elements of an array using for loop: // let array1 = ["Hello", 2, true, "world"]; // for (let i = 0; i < array1.length; i++) { // console.log(array1[i]); // } // ---------------------------------------------------------------------------------------------------- //to check even and odd between 1 to 20 // for (i = 1; i <= 20; i++) { // if (i % 2 == 0) { // console.log(`${i} is an even number`); // } else { // console.log(`${i} is an odd number1`); // } // }(Edited 7 Nov)forLoop_Js(2).txt// Practice questions // WAP to print all the even numbers from the given array- numArray = [23, 44, 46, 51, 76, 13, 34, 67, 90, 17]; for (i = 0; i < numArray.length; i++) { if (numArray[i] % 2 == 0) { console.log(numArray[i], "even"); } } // WAP to check whether the num in the given list are divisible by 4- Array1 = [25, 16, 54, 44, 98, 72, 17, 30, 28, 40, 71, 83, 24]; // console.log(Array1); for (i = 0; i < Array1.length; i++) { // console.log(Array1[i]) let x = Array1[i]; if (x % 4 == 0) { console.log(x, "divisible by 4"); } } //---------------------------------------------------------------------------------------------------- // WAP to print the sum of first 10 natural numbers: let sum = 0; for (let i = 1; i <= 10; i++) { sum = sum + i; } console.log(sum); //---------------------------------------------------------------------------------------------------- // WAP to print the factorial of a user inputted number let num = parseInt(prompt("Enter a number: ")); let factorial = 1; for (i = num; i >= 1; i--) { factorial = i * factorial; } console.log(`The factorial of ${num} is ${factorial}`);forLoop_Js(3).txt// WAP to check whether the user inputted number is prime or not: let num = parseInt(prompt("Enter a number:")); if (num <= 1) { console.log(num, " is not a prime number."); } else { let isPrime = true; for (let i = 2; i < num; i++) { if (num % i == 0) { console.log(num, " is not a prime number."); isPrime = false; break; // No need to check further } } if (isPrime) { console.log(num, " is a prime number."); } }for...in_&_for..of.txtDifference between for loop, for in & for of: 1. for Loop (Traditional Loop) The traditional for loop is used when you want to iterate over a block of code a specific number of times. It is typically used with numeric indices when you want to loop through arrays or perform repeated tasks. let numbers = [10, 20, 30, 40]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } // Output: 10, 20, 30, 40 // -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------- 2. for in: The for in loop is used to iterate over the keys of an object or the indices of an array. It is generally used when you want to work with the properties of an object or iterate over the enumerable properties of an object. let person = { name: "John", age: 30, city: "New York", }; for (let key in person) { console.log(key); } // ------------------------------------------------------------------------------ let person = { name: "John", age: 30, city: "New York", }; for (let key in person) { console.log(key + ":" + person[key]); } // ------------------------------------------------------------------------------ let numbers = [10, 20, 30, 40]; for (let i in numbers) { console.log(i); } // ------------------------------------------------------------------------------ let numbers = [10, 20, 30, 40]; for (let i in numbers) { console.log(numbers[i]); } // -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------- 3. for of: The for of loop is used to iterate over values of iterable objects such as arrays, strings, and other iterable data structures. It does not give you the index or key but directly provides the value of each element. for of loop does not work directly with objects. let numbers = [10, 20, 30, 40]; for (let i of numbers) { console.log(i); } // --------------------------------------------------------------------- let string = "hello"; for (let i of string) { console.log(i); }; // --------------------------------------------------------------------- let person = { name: "John", age: 30, city: "New York", }; for (let key of person) { console.log(key); } // this throws an error as for of doesn't directly work on objects // ------------------------------------------------------------------------ using Object.values(): let person = { name: "Alice", age: 25, city: "New York", }; for (let value of Object.values(person)) { console.log(value); }while.txt// initialization // while (condition){ // increment/decrement // } let i = 0; while (i < 10) { console.log("Hello World"); i++; } let i = 10; while (i > 0) { console.log("Hello World"); i--; } // --------------------------------------- let i = 0; let array = [10, 20, 30, 40, 50]; while (i < array.length) { console.log(array[i]); i++; } // --------------------------------------- // WAP to print the list of even number upto 30 using while loop let evenArray = [] let i=1 while(i<31){ if (i%2==0){ evenArray.push(i) } i++ } console.log(evenArray) // --------------------------------------------------- StudentArray = []; while (true) { let input = prompt("Are you a student?"); let obj = {}; if (input == "yes") { let fname = prompt("Enter first name"); let lname = prompt("Enter last name"); obj["fname"] = fname; obj["lname"] = lname; StudentArray.push(obj); } else { break; } } console.log(StudentArray); // -------------------------------------------------- // do while: let i = 0; do { console.log("Hello World"); i++; } while (i < 10); // ------------------------------------------------- let i = 5; do { console.log("Hello World"); i++; } while (i < 4);break_&_continue.txt// break: The break statement is used to exit or terminate the loop immediately when a specified condition is met. It stops the loop from further execution, even if there are more iterations left. for (let i = 1; i <= 10; i++) { if (i == 6) { break; } console.log(i); } console.log("out of loop"); // ---------------------------------------------------------------------------------------------- // continue: The continue statement is used to skip the current iteration of a loop and move to the next iteration, without executing the remaining code in the current loop cycle. for (let i = 1; i <= 10; i++) { if (i == 6) { continue; } console.log(i); } console.log("out of loop"); // ------------------------------------------------------------- for (let i = 1; i <= 10; i++) { if (i == 6) { console.log("this is the 6th iteration"); continue; } console.log(i); } console.log("out of loop"); // ------------------------------------------------------------ // WAP that prints all numbers from 1 to 10, but skips the even numbers (i.e., prints only // odd numbers). // Hint: Use the continue statement to skip even numbers. for (let i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; } console.log(i); } // -------------------------------------------------------------------------------------------------- // Practice Questions: // WAP that prints all the elements from the given array except pineapple // let fruits = ["apple", "banana", "pineapple", "kiwi"]; // WAP that checks numbers from 1 to 10 to see if a user inputted number is present. // If the number is found, print a message "Number is found" and stop the loop. // If not found, print a message "Number not found" after the loop ends. // Write a program that calculates the sum of all even numbers in an array using while loop. // let array = [5, 10, 15, 20, 25] // Write a program that removes duplicate values from the given array using while loop. // let array = [10, 20, 10, 30, 40, 20];7 Novindex.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="index.js"></script> </head> <body> <h1>Java Script</h1> </body> <!-- <script> console.log("hiii"); </script> --> </html>index.js// let found = false; // if (found) { // console.log("hello "); // } // -------------------------------------------------------------- // num = prompt(parseInt("enter a number: ")); // let found = false; // for (let i = 0; i < 11; i++) { // if (i == num) { // console.log("number is found!"); // found = true; // break; // } // } // if (!found) { // console.log("number not found!"); // } // ------------------------------------------------------------- // do while: // let i = 11; // do { // console.log("Hello World"); // i++; // } while (i < 10); // --------------------------------------------------------------- // let array = [5, 10, 15, 20, 25]; // let sum = 0; // let i = 0; // while (i < array.length) { // if (array[i] % 2 === 0) { // sum += array[i]; // } // i++; // } // console.log(sum); // --------------------------------------------------------------------- // functions in Java Script: // function greet(a) { // console.log("Hello", a); // } // greet("Emma"); // ----------------------------------------------------- // function add(a, b) { // return a + b; // } // result = add(2, 3); // console.log(result); // ------------------------------------------------------ // Home Work : // // Write a program that removes duplicate values from the given array using while loop. // let array = [10, 20, 10, 30, 40, 20];8 NovFunctions_in_Js.txt// Functions in JS // Reusable block of code that can be executed whenever it is called // Function returns a value // creating our own functions- // function greet(){ // console.log('hello') // } // greet() //-------------------------------------------------------------------------------- // function returns a value // function greet2(){ // return 'hello world' // } // let a = greet2() // console.log(a) // console.log(greet2()) // ------------------------------------- // Sum Function- // function Sum(a,b){ // return (a+b) // } // console.log(Sum(4,5)) // let n = Sum(7,8) // console.log(n) //-------------------------------------- function sum (a,b){ return (a+b) } let num1 = parseInt(prompt('enter a number')) let num2 = parseInt(prompt('enter another number')) let solution = sum(num1,num2) console.log(`the addition of ${num1} & ${num2} is ${solution}`) //------------------------------------- // Product Function- // function product(a,b){ // return a*b // } // product(7,10) //will not print the output // console.log(product(7,10)) //will prints the output // ----------------------------- // Even Function- // function even (a){ // if (a%2==0){ // return('even') // } // else{ // return('odd') // } // } // console.log(even(3)) //----------------------------------------------------------------- // user input // let num = parseInt(prompt("Enter a number:")) // console.log(even(num)) // odd function- // function Odd(n){ // if(n%2 != 0){ // return 'Odd' // } // else{ // return 'Even' // } // } // let num = parseInt(prompt()) // console.log(Odd(num)) //--------------------------------------------------------------------------arrow_function.txt// arrow functions - Arrow functions provide a concise syntax for // writing functions in JavaScript. // ()=>{} // let greet = ()=> 'Hello World' // console.log(greet()) //let add = function(a, b) { // return a + b; // }; // let add = (a, b) => a + b; // ----------------------------------------------------------- // let wish = (name) => "hello " + name; // console.log(wish("Emma")); // let add = (a,b)=> a+b // console.log(add(3,7)) // let prod = (x,y)=> {return x*y} // console.log(prod(6,7)) // let square = (n) => {console.log(n*n)} // square(7) // square(3) // let Square = (n)=> n*n // console.log(Square(5)) // ----------------------------------------- let newfunction = (n) => { if (n%2==0) { console.log('even') } else{ console.log('odd') } } newfunction(5) //----------------------------------------------------------------------------------------------------------- // even, odd questions using arrow function in one line code : // this returns answer in 'true' or 'false' // let even = (n) => n%2==0 // console.log(even(20)) // let odd = (n) => n%2!=0 // console.log(odd(11))index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="index.js"></script> </head> <body> <h1>Java Script</h1> </body> <!-- <script> console.log("hiii"); </script> --> </html>index.js// Write a program that removes duplicate values from the given array using while loop. // let array = [10, 20, 10, 30, 40, 20]; // let i = 0; // let uniqueArray = []; // while (i < array.length) { // if (!uniqueArray.includes(array[i])) { // uniqueArray.push(array[i]); // } // i++; // } // console.log(uniqueArray); // ------------------------------------------------------------------ // functions : // greet(); // greet_2("Emma"); // function greet() { // console.log("Hello World"); // } // function greet_2(name) { // console.log("Hello", name); // } // // ------------------------------------- // myfunc(); // let myfunc = function() { // console.log("Have a nice day"); // }; // // ------------------------------------- // myfunc1(); // var myfunc1 = function() { // console.log("Have a nice day"); // }; // function add(a, b) { // sum = a + b; // return sum; // } // let result = add(1, 2); // console.log(result); // ----------------------------------------------------------- // function sum (a,b){ // return (a+b) // } // let num1 = parseInt(prompt('enter a number')) // let num2 = parseInt(prompt('enter another number')) // let solution = sum(num1,num2) // console.log(`the addition of ${num1} & ${num2} is ${solution}`) // ---------------------------------------------------- // function checkEven(n) { // if (n % 2 == 0) { // console.log("even"); // } else { // console.log("odd"); // } // } // checkEven(11); // -------------------------------------------- // function my_func(m, n) { // let total_sum = 0; // for (i = m; i <= n; i++) { // total_sum += i; // } // return total_sum; // } // console.log(my_func(1, 10)); // ------------------------------------------------- // function my_function(m, n) { // let sum = 0; // let i = m; // while (i <= n) { // sum += i; // i++; // } // return sum; // } // console.log(my_function(1, 10)); // ------------------------------------------------- // arrow functions: // ()=>{} // let greet = () => { // return "Hello World"; // }; // console.log(greet()); // let greet = (name) => { // return `Hello ${name}`; // }; // console.log(greet("Mariya")); // -------------------------------------------------------- // let add = (a, b) => { // return a + b; // }; // console.log(add(5, 5)); // -------------------------------------------------------- // let square = (n)=> {console.log(n*n)} // let even = (n) => n % 2 == 0; // console.log(even(6));(Edited 9 Nov)Java_script_Assignment.txtJava Script Assignment m.m[20] Q.1, WAP that prints numbers from 1 to 100, For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz" instead of the number. For numbers which are multiples of boths 3 and 5, print "FizzBuzz". (1) Q.2, WAP that calculates the sum of all the odd numbers from the given array. let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; (1) Q.3, What do you understand by ternary operator? explain with an example. (2) Q.4, Write a program that finds the largest number in a given array. let numArr = [45, 89, 32, 71, 56]; (2) Q.5, WAP that calculates the factorial of a user inputted number. (2) Q.6, Write a program to check whether a user inputted number is even or odd. (using Arrow function)(2) Q.7, Define a function that accepts two perameters: an array and a number, and returns the number of times the number appears in the array. let arr = [1, 2, 2, 3, 4, 2, 5, 5, 1, 11]; (3) Q.8, What is hoisting in JavaScript? Write down a brief explanation and describe how variable and function declarations are hoisted differently.(in your ownn words) (3) Q.9, WAP to check whether the user inputted number is prime or not. (use while loop)(4) (All the Best)map_filter_reduce.txt// map()- Map function is applied on a given array by passing // each of its elements into a callback function used // and returns a new array let Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function cube(n) { return n * n * n; } let cubeArr = Arr.map(cube); console.log(cubeArr); // --------------------------------------------------------------------- let Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; console.log(Arr.map((n) => n ** 3)); // -------------------------------------------------------------------- // adding all the elements of Arr with 10 // console.log(Arr.map((n)=>n+10)) // ------------------------------------------------------------------- // to print the table of user inputted number using map // let num = parseInt(prompt(enter a number: )); // console.log(Arr.map((n) => n * num)); // ---------------------------------------------------------------- // to convert a number array into a string array let Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let newArr = Arr.map((n) => String(n)); console.log(Arr); console.log(newArr); // ---------------------------------------------------------------- // let strNum = ['10','20','30','40','50'] // console.log(strNum.map((n)=>parseInt(n))) // --------------------------------------------------------------- // to calculate the length of elements of a string array // let stringArray = ['car', 'pencil', 'bottle', 'bag'] // console.log(stringArray.map((n)=>n.length)) // ----------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------- // filter() let Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; console.log(Arr.map((n) => n % 2 == 0)); // filtering even numbers let Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; console.log(Arr.filter((n) => n % 2 == 0)); // filtering odd numbers // console.log(NumArr.filter((n)=>n%2!=0)) // ------------------------------------------------------- MarksArr = [76, 62, 31, 45, 85, 36, 90, 74]; console.log(MarksArr.filter((n) => n > 33)); // ----------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------- // reduce method - it reduces all the elements of a given array and // returns a single value // let Array2 = [1,2,3,4,5] // console.log(Array2.reduce((a,b)=>a*b)) // console.log(Array2.reduce((a,b)=>a+b)) // -------------------------------------------------- // replace method - string method to repalce the first occurence // let newString = 'Hello World, this World' // console.log(newString.replace('World', 'Everyone')) // let week = "Monday, Tuesday, Monday, Sunday" // console.log(week.replace('Monday', 'Wednesday'))DOM.txtdom.htmlJAVASCRIPT DOM JavaScript DOM is a powerful feature that enables web developers to create dynamic, interactive, and responsive web pages by manipulating the content and structure of the document in real-time. Using the DOM, JavaScript can dynamically modify the content and structure of web pages in response to user actions, events, or any other logic. With the help of Javascript DOM we can do things like: 1. Accessing and changing the content of HTML elements. 2. Modifying element attributes and styles. 3. Creating, adding, or removing elements from the page. 4. Responding to user clicks, keypresses, and other events. 5. Animating elements on the page. 6. Fetching data from the server and updating the page content dynamically. The DOM represents an HTML or XML document as a tree structure with distinct nodes in the tree. Nodes can be of different types such as element nodes, attribute nodes, text nodes, comment nodes, etc. ------------------------------------------------------------------------------------------------------------------------ * document.write() - It is a method in JavaScript that allows you to write content directly to the HTML document while it's being parsed or loaded. It is one of the oldest and simplest ways to add content to a web page dynamically using JavaScript. It has some limitations: 1. If document.write() is called after the page has loaded, it will overwrite the entire document, effectively clearing its content. 2. It may block the loading process and cause delays. 3. It can lead to unexpected behavior if used carelessly. Due to these limitations and potential issues, it is generally recommended to avoid using document.write() in modern web development.DOM_Methods.txtdocument.write('Hello People') //------------------------------------------------------------------------------------------------- // targetting elements by their TagNames: //console.log(document.getElementsByTagName('h1')[0]) // document.getElementsByTagName('h1')[0].style.color='red' // document.getElementsByTagName('h1')[1].style.color='blue' // console.log(document.getElementsByTagName('p')) // document.getElementsByTagName('p')[1].style.color='purple' //-------------------------------------------------------------------------------------------------- //targetting elements by ID: // console.log(document.getElementById('purple').innerText) // document.getElementById('purple').style.color ='purple' // document.getElementById('purple').style.backgroundColor='blue' // console.log(document.getElementById('heading')) // document.getElementById('heading').style.backgroundColor='orange' //------------------------------------------------------------------------------------------------- //targetting elements by ClassName: // console.log(document.getElementsByClassName('p2')[0]) // document.getElementsByClassName('p2')[0].style.backgroundColor = 'grey' // document.getElementsByClassName('p2')[0].style.border='green solid 2px' //------------------------------------------------------------------------------------------------- //targetting elements by Name attribute: //console.log(document.getElementsByName ('change')) // document.getElementsByName('change')[0].style.border = 'red dotted 2px'htmltree.gif<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <h1>Heading 1</h1> <h1>Heading 2</h1> <h3>Heading 3</h3> <h1 id="bold">NEW <b>Heading</b></h1> <p id="pera"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Consequuntur accusantium rerum quidem, consequatur pariatur dignissimos officia hic laudantium reiciendis facere cumque error nulla voluptate, dolore assumenda. Harum beatae fugit cumque! </p> <p class="class1"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Consequuntur accusantium rerum quidem, consequatur pariatur dignissimos officia hic laudantium reiciendis facere cumque error nulla voluptate, dolore assumenda. Harum beatae fugit cumque! </p> <p name="change"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Consequuntur accusantium rerum quidem, consequatur pariatur dignissimos officia hic laudantium reiciendis facere cumque error nulla voluptate, dolore assumenda. Harum beatae fugit cumque! </p> <br /> <!-- <button onclick="myFunction()">Click me</button> <input type="submit" onclick="Submit()" /> --> </body> <script src="dom.js"></script> </html>dom.js-------------------------------------------------------------------------------document.write("Hello People"); // console.log(document.getElementById("new")); // document.getElementById("new").innerText = "NEWW"; // console.log("hello"); // document.write("hello"); // console.log(document.getElementsByTagName("h1")[0]); // document.getElementsByTagName("h1")[0].style.color = "red"; // let h1 = document.getElementsByTagName("h1")[0]; // h1.style.color = "blue"; // document.getElementsByTagName("h1")[1].style.color = "blue"; // targetting elements by id: // console.log(document.getElementById("pera")); // document.getElementById("pera").style.backgroundColor = "grey"; // ------------------------------------------------------- // targettig elements by class name: // console.log(document.getElementsByClassName("blue")); // document.getElementsByClassName("blue")[0].style.color = "blue"; // document.getElementsByClassName("blue")[1].style.border = "red dotted 2px"; // -------------------------------------------------------- // targettig elements by name attribute: // document.getElementsByName("change")[0].style.border = "green dotted 2px"; // --------------------------------------- //innerTEXT: // document.getElementsByTagName("h3")[0].innerText = "wow" // ------------------------------------------------------------------- // // innerHTML: // document.getElementById("bold").innerText = "Changing the <i>Heading<i>"; // document.getElementById("bold").innerHTML = "Changing the <i>Heading<i>"; // -------------------------------------------------------------------- // -------------------------------------------------------------------- // query selectors: // document.querySelector("h1").style.background = "yellow"; // document.querySelector("#pera").style.background = "blue"; // document.querySelector(".class1").style.background = "red"; // document.querySelector("[name = 'change']").style.background = "blue"; // ------------------------------------------------------------------- // querySelectorAll: // console.log(document.querySelectorAll("h1")); // document.querySelectorAll("h1")[0].style.color = "blue"; // ------------------------------------------------------------------ // Events: // function myFunction() { // alert("Hello world"); // } // function Submit() { // console.log("Data Submitted"); // }index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="index.js"></script> </head> <body> <h1>Java Script</h1> </body> <!-- <script> console.log("hiii"); </script> --> </html>index.js// i = 11; // do { // console.log("Hello World"); // i++; // } while (i < 9); // Write a program that removes duplicate values from the given array using while loop. // let array = [10, 20, 10, 30, 40, 20]; // let i = 0; // let uniqueArray = []; // while (i < array.length) { // if (!uniqueArray.includes(array[i])) { // uniqueArray.push(array[i]); // } // i++; // } // console.log(uniqueArray); // ------------------------------------------------------------------ // functions : // greet(); // a(); // let a = function() { // console.log("Hello World"); // } // function greet_2(name) { // console.log("Hello", name); // } // // ------------------------------------- // myfunc(); // let myfunc = function() { // console.log("Have a nice day"); // }; // // ------------------------------------- // myfunc1(); // var myfunc1 = function() { // console.log("Have a nice day"); // }; // function add(a, b) { // sum = a + b; // return sum; // } // let result = add(1, 2); // console.log(result); // ----------------------------------------------------------- // function sum (a,b){ // return (a+b) // } // let num1 = parseInt(prompt('enter a number')) // let num2 = parseInt(prompt('enter another number')) // let solution = sum(num1,num2) // console.log(`the addition of ${num1} & ${num2} is ${solution}`) // ---------------------------------------------------- // function checkEven(n) { // if (n % 2 == 0) { // console.log("even"); // } else { // console.log("odd"); // } // } // checkEven(11); // -------------------------------------------- // function my_func(m, n) { // let total_sum = 0; // for (i = m; i <= n; i++) { // total_sum += i; // } // return total_sum; // } // console.log(my_func(1, 10)); // ------------------------------------------------- // function my_function(m, n) { // let sum = 0; // let i = m; // while (i <= n) { // sum += i; // i++; // } // return sum; // } // console.log(my_function(1, 10)); // ------------------------------------------------- // arrow functions: // ()=>{} // let greet = () => { // return "Hello World"; // }; // console.log(greet()); // let greet = (name) => { // return `Hello ${name}`; // }; // console.log(greet("Mariya")); // -------------------------------------------------------- // let add = (a, b) => { // return a + b; // }; // console.log(add(5, 5)); // -------------------------------------------------------- // let square = (n) => { // console.log(n * n); // }; // let even = (n) => n % 2 == 0; // console.log(even(6)); // let newfunction = (n) => { // if (n % 2 == 0) { // console.log("even"); // } else { // console.log("odd"); // } // }; // newfunction(5); // let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // let num = parseInt(prompt("enter a number")); // console.log(array.map((n) => n * num)); // -------------------------------------------- // let Arr = [1, 2, 3, 4, 5]; // function cube(m) { // return m * m * m; // } // let cubeArr = Arr.map(cube); // console.log(cubeArr); // console.log(cube(3)); // console.log(Arr.map((n) => n ** 3)); // // console.log(cubeArr); // // console.log(array); // console.log(array.map((n) => n + 10)); // let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // let newArr = array.map((n) => String(n)); // console.log(newArr); // let Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // console.log(Arr.map((n) => n % 2 == 0)); // console.log(Arr.filter((n) => n % 2 == 0)); // let marksArray = [100, 20, 30, 31, 25, 50]; // console.log(marksArray.filter((i) => i > 30)); let Array2 = [1, 2, 3, 4, 5]; console.log(Array2.reduce((a, b) => a * b)); console.log(Array2.reduce((a, b) => a + b));13 NovforEach_findIndex_findAll.txtJava Script functions: forEach(): // used to execute a function on each element of an array. //It doesn't return a new array; it just loops through the array. // The forEach() method calls the provided function once for each element in the array. const numbers = [1, 2, 3, 4]; numbers.forEach((num) => { console.log(num * 2); }); // ----------------------------------------------------------------------------------- find(): // returns the first element in the array that satisfies the provided condition. // If no element matches, it returns undefined const numbers = [1, 2, 3, 4, 5]; const found = numbers.find((num) => num > 3); console.log(found); // ----------------------------------------------------------------------------------- findIndex(): //returns the index of the first element in the array that satisfies the condition. // If no element matches, it returns -1. const numbers = [1, 2, 3, 4, 5]; const index = numbers.findIndex((num) => num > 3); console.log(index); // ----------------------------------------------------------------------------------- // with filter() const numbers = [1, 2, 3, 4, 5]; const foundAll = numbers.filter(num => num > 3); console.log(foundAll);events.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <!-- <h1>Hello World</h1> <button onclick="alert('Button clicked!')">Click me!</button> --> <!-- ------------------------------------------------------ --> <!-- <input type="text" placeholder=" name" id="name" onmouseover="colorChange()" onmouseout="undoColorChange()" /> <input type="submit" /> --> <!-- ---------------------------------------------------------------- --> <!-- <h1 id="form">F O R M</h1> <form> Name: <input type="text" id="name" onchange="my_func()" /><br /><br /> Age: <input type="number" id="age" /><br /><br /> Email: <input type="email" id="email" /><br /><br /> Password: <input type="password" id="pass" /><br /><br /> </form> <input type="submit" onclick="Submit()" /> --> <!-------------------------------------------------------------- --> <!-- <button id="myButton">Click me!</button> <div id="myDiv" style="width: 200px; height: 200px; background-color: lightblue;" ></div> <br /><br /> --> <!-- ------------------------------------------------- --> <form id="myForm"> <input type="text" id="name" placeholder="Enter your name" /> <button type="submit">Submit</button> </form> <!-- </body> --> <script src="events.js"></script> </html>events.js// events : // function colorChange() { // let variable = document.getElementById("name"); // variable.style.backgroundColor = "red"; // } // function undoColorChange() { // let variable = document.getElementById("name"); // variable.style.backgroundColor = ""; // } // ------------------------------------------------------- // function my_func() { // var x = document.getElementById("name").value; // // console.log(x); // // console.log(x.toUpperCase()); // document.getElementById("name").value = ""; // document.getElementById("name").value = x.toUpperCase(); // } // function Submit() { // let userName = document.getElementById("name").value; // let userAge = document.getElementById("age").value; // let userEmail = document.getElementById("email").value; // let userPassword = document.getElementById("pass").value; // console.log(userName); // console.log(userAge); // console.log(userEmail); // console.log(userPassword); // document.getElementById("form").innerHTML = userName; // document.getElementById("name").value = ""; // } //----------------------------------------------------------------- //----------------------------------------------------------------- // addEventListener: // document.getElementById("myButton").addEventListener("click", function() { // alert("Button clicked!"); // }); // // ------------------------------------ // const div = document.getElementById("myDiv"); // div.addEventListener("mouseover", function() { // div.style.backgroundColor = "lightgreen"; // }); // div.addEventListener("mouseout", function() { // div.style.backgroundColor = "lightblue"; // }); // // ------------------------------------------------------- // document.getElementById("myForm").addEventListener("submit", function() { // alert("Form submitted!"); // }); // // ----------------------------------------------addEventListener().html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form> Name: <input type="text" id="name"><br><br> Age: <input type="number" id="age"><br><br> Email: <input type="email" id="email"><br><br> Password: <input type="password" id="pass"><br><br> </form> <input type="submit" id="btn"> <br><br><br> <!-- <div id="myDiv" style="width: 100px; height: 100px; background-color: rgb(110, 189, 216);"></div> --> <br><br><br> <!-- <input type="password" id="password" placeholder="Enter password"> <button id="checkBtn">Check Strength</button> --> </body> <script> document.getElementById('btn').addEventListener('click', function () { alert('Button clicked!'); }); //-------------------------------------------------------- // document.getElementById('myDiv').addEventListener('mouseover', function () { // this.style.backgroundColor = 'red'; // }) // document.getElementById('myDiv').addEventListener('mouseout', function () { // this.style.backgroundColor = 'rgb(110, 189, 216)'; // }) //------------------------------------------------------------ // document.getElementById('checkBtn').addEventListener('click', function() { // let password = document.getElementById('password').value; // if (password.length < 6) { // console.log('Weak password: Too short'); // } else if (password.length < 10) { // console.log('Moderate password: Decent length'); // } else { // console.log('Strong password: Good length'); // } // }); </script> </html>index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="index.js"></script> </head> <body> <h1>Java Script</h1> </body> <!-- <script> console.log("hiii"); </script> --> </html>index.js// forEach: const numbers = [1, 2, 3, 4, 5]; // numbers.forEach((num) => { // console.log(num * 2); // }); // -------------------------------------------------- // find: // const found = numbers.find((num) => num > 3); // console.log(found); // -------------------------------------------------- // findIndex: // const index = numbers.findIndex((num) => num > 3); // console.log(index); // ------------------------------------------------- // filter: // const foundAll = numbers.filter((num) => num > 3); // console.log(foundAll); const person = { name: "Alice", greet: function() { console.log(`Hello, my name is ${this.name}`); }, }; person.greet();this_keyword_in_JS.txtthis: // The this keyword in JavaScript is a special variable that refers to the current execution // // context //it basically refers to the object that is currently executing the code. const person = { name: "Alice", greet: function() { console.log(`Hello, my name is ${this.name}`); }, }; person.greet();Q.1 Create a HTML heading, "Have a beautiful day", then create a
button, On clicking it, the text in heading should change from
"Have a beautiful day" to "Hello world" and the color of the heading should
change from black to blue. (Use onclick event) [2]
Q.2 Create a form with a submit button. On clicking it, display the text you
filled in uppercase on console screen. (Use onclick event) [2]
Q.3. Create a text box. On clicking a button, display the data entered into the
text box on your webpage inside a heading h2 in blue color. (Use addEventListener). [2]
Q.4. Create a button. On clicking it, insert a link inside an already existing paragraph.
(Use addEventListener). [2]
Q.5 Create a div. On hovering over it, the background color of the div should change. and
on hovering out, the background color should get back to it's original color.
(Use addEventListener) [2]18 Novhome.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <!-- <button onclick="alert('Button clicked!')">Click me!</button> --> <!-- <input type="text" placeholder=" name" id="name" onmouseover="colorChange()" onmouseout="undoColorChange()" /> <input type="submit" /> --> <!-- ---------------------------------------------------------------- --> <!-- <h1 id="form">F O R M</h1> <form> Name: <input type="text" id="name" onchange="my_func()" /><br /><br /> Age: <input type="number" id="age" /><br /><br /> Email: <input type="email" id="email" /><br /><br /> Password: <input type="password" id="pass" /><br /><br /> </form> <input type="submit" onclick="Submit()" /> --> <!-------------------------------------------------------------- --> <!-- <button id="myButton">Click me!</button> --> <!-- <div id="myDiv" style="width: 200px; height: 200px; background-color: lightblue;" ></div> <br /><br /> --> <!-- ------------------------------------------------- --> <!-- <form id="myForm"> <input type="text" id="name" placeholder="Enter your name" /> <button type="submit">Submit</button> </form> --> <!-- </body> --> </body> <script src="home.js"></script> </html>home.js// events : // function colorChange() { // let variable = document.getElementById("name"); // variable.style.backgroundColor = "red"; // } // function undoColorChange() { // let variable = document.getElementById("name"); // variable.style.backgroundColor = ""; // } // document.write("Hello World"); // let array = [1, 2, 3]; // array.forEach((Element) => document.write(Element + "<br>")); // ------------------------------------------------------- // function my_func() { // var x = document.getElementById("name").value; // // console.log(x); // // console.log(x.toUpperCase()); // document.getElementById("name").value = ""; // document.getElementById("name").value = x.toUpperCase(); // } // function Submit() { // let userName = document.getElementById("name").value; // let userAge = document.getElementById("age").value; // let userEmail = document.getElementById("email").value; // let userPassword = document.getElementById("pass").value; // console.log(userName); // console.log(userAge); // console.log(userEmail); // console.log(userPassword); // document.getElementById("form").innerHTML = userName; // document.getElementById("name").value = ""; // } //----------------------------------------------------------------- //----------------------------------------------------------------- // addEventListener: // document.getElementById("myButton").addEventListener("click", function() { // alert("Button clicked!"); // }); // // ------------------------------------ // const div = document.getElementById("myDiv"); // div.addEventListener("mouseover", function() { // div.style.backgroundColor = "lightgreen"; // }); // div.addEventListener("mouseout", function() { // div.style.backgroundColor = "blue"; // }); // // ------------------------------------------------------- // document.getElementById("myForm").addEventListener("submit", function() { // alert("Form submitted!"); // }); // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // array destructuring: // let array = [1, 2, 3, 4]; // let a = array[0]; // let [a, b, , d] = array; // console.log(d); // let c = 1; // let e = 2; // [c, e] = [e, c]; // console.log(e); // let [a, b, ...c] = array; // rest operator // console.log(c); // let string = "Have a beautiful day !".split(" "); // console.log(string); // [a, , ...rest] = string; // console.log(a); // console.log(rest); // spread operator (...) // let array1 = [1, 2, 3]; // let array2 = ["a", "b", "c"]; // let array3 = [...array1, ...array2]; // spread operator // console.log(array3); // function addandMul(a, b) { // return [a + b, a * b, a - b]; // } // let result = addandMul(5, 2); // console.log(result); // let [result1, result2, result3 = "no result"] = addandMul(2, 3); // console.log(result1); // console.log(result2); // console.log(result3); // ------------------------------------------------------------- // object destructuring // let person = { // name: "Harry", // age: 15, // address: { // city: "torano", // country: "USA", // }, // }; // const { // name, // address: { city }, // } = person; // console.log(city); // console.log(newCity); // const { name: newName, age: newVariable } = person; // console.log(newVariable); // console.log(newName); // let person_1 = { // name: "Harry", // age: 15, // address: { // city: "torano", // country: "USA", // }, // favouriteColor: "blue", // }; // let person_2 = { // name: "Ana", // hobby: "singing", // }; // let person_3 = { ...person_1, ...person_2 }; // console.log(person_3); // --------------------------------------------------------- // function my_func1(user) { // console.log(`name is ${user.name}, age is ${user.age}`); // } // my_func1(person_1); // --------------------------------------------------------- let person_1 = { name: "Harry", age: 15, address: { city: "torano", country: "USA", }, favouriteColor: "blue", }; function my_func1({ name, age, favouriteColor = "orange" }) { console.log( `name is ${name}, age is ${age} and favourite color is ${favouriteColor}` ); } my_func1(person_1);Destructuring_in_JS.txt// array destructuring: let array_1 = [1, 2, 3, 4]; // console.log(array_1[1]); // [a, b, c, d] = array_1; // console.log(d); // [a, b, , d] = array_1; // console.log(d); // swaping the values using array destructuring // let a = 1; // let b = 2; // [a, b] = [b, a]; // console.log(b); // // ------------- rest operator (...) --------------------- // let string = "Have a beautiful day !".split(" "); // console.log(string); // [a, , ...rest] = string; // // console.log(a); // console.log(rest); // ----------------------------------------------------------- // combining two arrays // let arr = [1, 2, 3, 4, 5]; // let arr2 = ["a", "b", "c"]; // let new_arr = [...arr, ...arr2]; // spread operator // console.log(new_arr); // ----------------------------------------------------------- // function addandMul(a, b) { // return [a + b, a * b, a - b]; // } // let result = addandMul(5, 2); // console.log(result); // let [result1, result2, result3 = "no result"] = addandMul(2, 3); // console.log(result1); // console.log(result2); // console.log(result3); // --------------------------------------------------------- // object destructuring: // let person = { // name: "Harry", // age: 15, // address: { // city: "torano", // country: "USA", // }, // }; // const { name, age } = person; // console.log(age); // const { name: first_name, ...rest } = person; // console.log(first_name); // console.log(rest); // const { // name, // address: { city: newCity }, // } = person; // console.log(city); // console.log(newCity); // ----------------------------------------- let person_1 = { name: "Harry", age: 15, address: { city: "torano", country: "USA", }, }; let person_2 = { name: "Ana", hobby: "singing", }; let person_3 = { ...person_1, ...person_2 }; console.log(person_3); // ---------------------------------------- // function my_func1(user) { // console.log(`name is ${user.name}, age is ${user.age}`); // } // my_func1(person_1); // --------------------------------------- function my_func1({ name, age, favouriteColor = "orange" }) { console.log( `name is ${name}, age is ${age} and favourite color is ${favouriteColor}` ); } my_func1(person_1);20 Novset_Time_out.txtsetTimeout(): // a function that allows you to delay the execution of a piece of code by a specified amount of // time (in milliseconds). //Once the time has passed, the code inside the setTimeout() function executes. setTimeout(() => alert("Hii"), 3000); setTimeout(() => console.log("Hello world!"), 4000); // ---------------------------------------------------------------------------------- function greet() { console.log("Have a lovely day!"); } setTimeout(greet, 5000); // ---------------------------------------------------------------------------------- console.log("Start"); setTimeout(() => { console.log("i am a set time out function"); }, 1000); console.log("End"); // ---------------------------------------------------------------------------------- function changeColor() { document.getElementById("pera").style.color = "orange"; } setTimeout(changeColor, 4000); // ---------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------- clearTimeout: let myfunc = setTimeout(() => { console.log("Hi, i am function"); }, 1000); clearTimeout(myfunc); // ---------------------------------------------------------------------------- let myfunc = setTimeout(() => { console.log("Hi, i am function"); }, 3000); setTimeout(() => { clearTimeout(myfunc); }, 5000); // ---------------------------------------------------------------------------- // passing arguments in setTimeout(): function add(a, b) { console.log(a + b); } setTimeout(add, 2000, 5, 5); // -------------------------------------------------------------------------- input = prompt("do you want to run the setTimeout ?"); myfunc2 = setTimeout(() => { console.log("Hello World!"); }, 2000); if (input == "no") { clearTimeout(myfunc2); }setInterval.txtsetInterval(): A function that repeatedly executes a piece of code at a specified interval (in milliseconds). The code continues to run at the given interval until clearInterval() is called. setInterval(() => console.log("Hello"), 1000); // -------------------------------------------------------------------- setInterval(() => { alert("This is an alert!"); }, 5000); // -------------------------------------------------------------------- let count = 1; const intervalId = setInterval(() => { console.log(count); count++; if (count > 5) { clearInterval(intervalId); } }, 1000); // ------------------------------------------------------------------ // adding a simple animation using setInterval() currentPosition = 0; function Animation() { currentPosition += 10; div = document.getElementsByTagName("div")[0]; div.style.marginLeft = currentPosition + "px"; } setInterval(Animation, 1000); // ------------------------------------------------------------------ // Practice Question: // Q. stop adding the margin once it reaches to 100px. (HINT: use clearInterval()) currentPosition = 0; function Animation() { if (currentPosition == 100) { clearInterval(variable); } else { currentPosition += 10; div = document.getElementsByTagName("div")[0]; div.style.marginLeft = currentPosition + "px"; } } let variable = setInterval(Animation, 1000);home.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> div { height: 100px; width: 100px; background-color: rgb(141, 82, 41); } </style> </head> <body> <div></div> </body> <script src="home.js"></script> </html>home.js// array destructuring: // let array = [1, 2, 3, 4]; // let a = array[0]; // let [a, b, ...c] = array; // console.log(c); // let c = 1; // let e = 2; // [c, e] = [e, c]; // console.log(e); // let [a, b, ...c] = array; // rest operator // console.log(c); // let string = "Have a beautiful day !".split(" "); // console.log(string); // [a, , ...rest] = string; // console.log(a); // console.log(rest); // spread operator (...) // let array1 = [1, 2, 3]; // let array2 = ["a", "b", "c", 1, 2, 3]; // let array3 = [...array1, ...array2]; // spread operator // console.log(array3); // function addandMul(a, b) { // return [a + b, a * b, a - b]; // } // let result = addandMul(5, 2); // console.log(result); // let [result1, result2, result3 = "no result"] = addandMul(2, 3); // console.log(result1); // console.log(result2); // console.log(result3); // ------------------------------------------------------------- // object destructuring // let person = { // name: "Harry", // age: 15, // address: { // city: "torano", // country: "USA", // }, // }; // const { // name, // address: { city }, // } = person; // console.log(city); // // console.log(newCity); // const { name: newName, age: newVariable } = person; // console.log(newVariable); // console.log(newName); // let person_1 = { // name: "Harry", // age: 15, // address: { // city: "torano", // country: "USA", // }, // favouriteColor: "blue", // }; // let person_2 = { // name: "Ana", // hobby: "singing", // }; // let person_3 = { ...person_1, ...person_2 }; // console.log(person_3); // --------------------------------------------------------- // function my_func1(user) { // console.log(`name is ${user.name}, age is ${user.age}`); // } // my_func1(person_1); // --------------------------------------------------------- // let person_1 = { // name: "Harry", // age: 15, // address: { // city: "torano", // country: "USA", // }, // favouriteColor: "blue", // }; // function my_func1({ name, age, favouriteColor = "orange" }) { // console.log( // `name is ${name}, age is ${age} and favourite color is ${favouriteColor}` // ); // } // my_func1(person_1); // console.log("a") // console.log("b") // setTimeout(() => console.log("i am an arrow function"), 7000); // setTimeout(function() { // console.log("Hello"); // }, 2000); // // ----------------------------- // function add(a, b) { // console.log(a + b); // } // setTimeout(add, 1000, 5, 5); // -------------------------------- // function greet() { // console.log("Have a nice day"); // } // let myfunc = setTimeout(greet, 3000); // setTimeout(() => { // clearTimeout(myfunc); // }, 5000); // function changeColor() { // let div = document.getElementsByTagName("div")[0]; // div.style.backgroundColor = "blue"; // } // setTimeout(changeColor, 3000); // let input = prompt("do you want to run the setTimeout?"); // let myfunc5 = setTimeout(function() { // console.log("Hi, i am a setTimeout function"); // }, 2000); // if (input == "no") { // clearTimeout(myfunc5); // } // setInterval(() => console.log("Hello world"), 2000); // let a = setInterval(() => alert("Hello world"), 2000); // clearInterval(a); // count = 10; // let myfunc6 = setInterval(() => { // console.log(count); // count--; // if (count < 0) { // clearInterval(myfunc6); // } // }, 1000); // currentPosition = 0; // function Animation() { // if (currentPosition == 100) { // clearInterval(stop); // } else { // currentPosition += 10; // div = document.getElementsByTagName("div")[0]; // div.style.marginLeft = currentPosition + "px"; // } // } // let stop = setInterval(Animation, 500); // function func1() { // console.log("function 1"); // } // function func2(callback) { // console.log("function 2"); // callback(); // } // func2(func1); function simpleGreet_function(name) { console.log("Hello, " + name); } function greetJohn(callback) { let name = "John"; callback(name); } greetJohn(simpleGreet_function);26 Novhome.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> div { height: 100px; width: 100px; background-color: rgb(141, 82, 41); } </style> </head> <body> <div></div> </body> <script src="home.js"></script> </html>home.js// setTimeout(() => console.log("i am an arrow function"), 7000); // setTimeout(function() { // console.log("Hello"); // }, 2000); // function add(a, b) { // console.log(a + b); // } // setTimeout(add, 2000, 5, 5); // // ----------------------------- // function greet() { // console.log("Have a nice day"); // } // let myfunc = setTimeout(greet, 3000); // clearTimeout(myfunc); // setTimeout(() => { // clearTimeout(myfunc); // }, 5000); // -------------------------------- // function changeColor() { // let div = document.getElementsByTagName("div")[0]; // div.style.backgroundColor = "blue"; // } // setTimeout(changeColor, 3000); // -------------------------------- // let input = prompt("do you want to run the setTimeout?"); // let myfunc5 = setTimeout(function() { // console.log("Hi, i am a setTimeout function"); // }, 2000); // if (input == "no") { // clearTimeout(myfunc5); // } // ---------------------------------------------------------- // ---------------------------------------------------------- // setInterval(() => console.log("Hello world"), 2000); // let a = setInterval(() => alert("Hello world"), 2000); // clearInterval(a); // --------------------------------------------------------- // count = 10; // let myfunc6 = setInterval(() => { // console.log(count); // count--; // if (count < 0) { // clearInterval(myfunc6); // } // }, 1000); // -------------------------------------------------------- // currentPosition = 0; // function Animate() { // if (currentPosition == 100) { // clearInterval(stop); // } else { // currentPosition += 10; // div = document.getElementsByTagName("div")[0]; // div.style.marginLeft = currentPosition + "px"; // } // } // let stop = setInterval(Animate, 500); // -------------------------------------------------- // function func1() { // console.log("function 1"); // } // function func2(callback) { // console.log("function 2"); // callback(); // } // func2(func1); // ------------------------------------------------ // function simpleGreet_function(name) { // console.log("Hello, " + name); // } // function greetJohn(callback) { // let name = "John"; // callback(name); // } // greetJohn(simpleGreet_function); // ------------------------------------------------ // let Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // function cube(n) { // console.log(n * n); // } // let cubeArr = Arr.forEach(cube); // console.log(cubeArr); // let Arr = ["1", "2", "3"]; // let newArr = Arr.forEach((n) => console.log(typeof parseInt(n))); // let stringArray = ["car", "pencil", "bottle", "bag"]; // MarksArr = [76, 62, 31, 45, 85, 36, 90, 74, 20]; // let week = "Monday, Tuesday, Monday, Sunday"; // let Array2 = [1, 2, 3, 4, 5]; // console.log(Array2.reduce((a, b) => a * b)); // let array = [1, 2, 3, 4, "hello"]; // let [a, b, ...c] = array; // console.log(c); // let array1 = [1, 2, 3]; // let array2 = ["a", "b", "c", 1, 2, 3]; // setInterval(() => console.log("hello"), 3000); // console.log("world"); // ------------------------------------------------------------ // function calc(n1, n2, output) { // console.log("Before adding two numbers"); // s = n1 + n2; // output(s); // console.log("After calling result function"); // } // function result(c) { // console.log(c); // console.log("After displaying the result"); // } // calc(2, 3, result); // ----------------------------------------------------- // function fetchData(callback) { // setTimeout(() => { // const data = { username: "Alice", age: 25 }; // callback(data); // }, 2000); // } // function displayData(userData) { // console.log("User Data: ", userData); // } // fetchData(displayData); // ----------------------------------------------------- // function greet() { // setTimeout(() => { // console.log("hello"); // setTimeout(() => { // console.log("everyone"); // setTimeout(() => { // console.log("How are you all!!!!"); // }, 2000); // }, 2000); // }, 5000); // } // greet(); // --------------------------------------------------------- // let promise1 = new Promise((resolve, reject) => { // setTimeout(() => { // console.log("promise is resolved"); // reject("success"); // }, 2000); // }); // console.log(promise1); // function myfunc(a, callback) { // setTimeout(() => { // console.log(a); // if (callback) { // callback(); // } // }, 1000); // } // myfunc(1, () => { // myfunc(2, () => { // myfunc(3); // }); // }); // myfunc(2); // myfunc(3); // ------------------------------------- function myfunc(a, callback) { setTimeout(() => { console.log("function", a); if (callback) { callback(); } }, 2000); } myfunc(1, () => { myfunc(2, () => { myfunc(3, () => { myfunc(4, () => { myfunc(5); }); }); }); });callback.txtcallback: // callback is a function that is passed into another function as an argument. // and is then executed (called back) at a later time. // Callbacks allow us to ensure that a certain action happens after something else has been // completed. // in simple words, The callback function gets called inside the function it's passed to, at the // appropriate time (like after a delay or after some operation). function simpleGreet_function(name) { console.log("Hello, " + name); } function greetJohn(callback) { let name = "John"; callback(name); } greetJohn(simpleGreet_function); // ------------------------------------------------------------------------------------ function showMessage(message) { console.log(message); } function greet(callback) { const message = "Welcome to JavaScript!"; callback(message); } greet(showMessage); // --------------------------------------------------------------------------------- function fetchData(callback) { setTimeout(() => { const data = { username: "Alice", age: 25 }; callback(data); }, 2000); } function displayData(userData) { console.log("User Data: ", userData); } fetchData(displayData); // -------------------------------------------------------------------------------- // function calc(n1, n2, output){ // console.log("Before adding two numbers") // s = n1+n2 // output(s) // console.log("After calling result function") // } // function result(c){ // console.log(c) // console.log("After displaying the result") // } // calc(2,3,result) // --------------------------------------------------------------------------- // Callback Hell // function greet(){ // setTimeout(()=>{ // console.log('hello'); // setTimeout(()=>{ // console.log('everyone'); // setTimeout(()=>{ // console.log("How are you all!!!!") // },2000) // },2000) // },5000) // } // greet() // -------------------------------------------------------------- function myfunc(a) { setTimeout(() => { console.log("function", a); }, 2000); } myfunc(1); myfunc(2); myfunc(3); // ------------------------------------------------------------- function myfunc(a, callback) { setTimeout(() => { console.log("function", a); if (callback) { callback(); } }, 2000); } myfunc(1, () => { myfunc(2); }); // ----------------------------------------------------------------- // call back hell: function myfunc(a, callback) { setTimeout(() => { console.log("function", a); if (callback) { callback(); } }, 2000); } myfunc(1, () => { myfunc(2, () => { myfunc(3, () => { myfunc(4, () => { myfunc(5, () => {}); }); }); }); });28 Novhome.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> div { height: 100px; width: 100px; background-color: rgb(141, 82, 41); } </style> </head> <body> <div></div> </body> <script src="home.js"></script> </html>home.js// promise: // let promise1 = new Promise((resolve, reject) => { // console.log("i am a promise"); // }); // console.log(promise1); // ------------------------------------ // let promise1 = new Promise((resolve, reject) => { // setTimeout(() => { // console.log("promise is rejected"); // reject("rejected"); // }, 2000); // }); // console.log(promise1); // .then() // .catch() // ------------------------------------ // let myPromise = new Promise((resolve, reject) => { // let success = false; // if (success) { // resolve("The operation was successful!"); // } else { // reject("Something went wrong!"); // } // }); // myPromise // .then(function(result) { // console.log(result); // }) // .catch(function(error) { // console.log(error); // }); // Practice Questions: //Write a Promise that resolves with the string "Data Loaded" after 4 seconds using setTimeout. Use .then() to log the string to the console. // Write a function combineStrings() that takes two strings as arguments and combines them. The callback function should log the combined result // Write a function that takes an age and a callback function. If the age is 18 or older, the callback should log "You are an adult!". Otherwise, it should log "You aren't adult!" // function checkAge(age, callback) { // if (age >= 18) { // callback("You are an adult!"); // } else { // callback("You are a minor!"); // } // } // function logMessage(message) { // console.log(message); // } // checkAge(20, logMessage); // checkAge(16, logMessage); // --------------------------------------- // Write a series of three functions that simulate an asynchronous process using callbacks: // task1(callback) that takes a callback and calls it after 1 second. // task2(callback) that takes a callback and calls it after 2 seconds. // task3(callback) that takes a callback and calls it after 3 seconds. Chain these functions together so that task1 runs first, followed by task2, and then task3.https://www.w3schools.com/jsref/met_win_settimeout.asp?authuser=0https://www.w3schools.com/jsref/met_win_setinterval.asp?authuser=0https://www.w3schools.com/js/js_callback.asp?authuser=0https://www.geeksforgeeks.org/javascript-promise/?authuser=029 Novhome.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> div { height: 100px; width: 100px; background-color: rgb(141, 82, 41); } </style> </head> <body> <div></div> </body> <script src="home.js"></script> </html>home.js// promise: // let promise1 = new Promise((resolve, reject) => { // console.log("i am a promise"); // }); // console.log(promise1); // ------------------------------------ // let promise1 = new Promise((resolve, reject) => { // setTimeout(() => { // // console.log("promise is rejected"); // reject("rejected"); // }, 2000); // }); // console.log(promise1); // .then() // .catch() // ------------------------------------ // let myPromise = new Promise((resolve, reject) => { // let success = false; // if (success) { // resolve("The operation was successful!"); // } else { // reject("Something went wrong!"); // } // }); // myPromise // .then(function(result) { // console.log(result); // }) // .catch(function(error) { // console.log(error); // }); // Practice Questions: //Write a Promise that resolves with the string "Data Loaded" after 4 seconds using setTimeout. Use .then() to log the string to the console. // Write a function combineStrings() that takes two strings as arguments and combines them. The callback function should log the combined result // Write a function that takes an age and a callback function. If the age is 18 or older, the callback should log "You are an adult!". Otherwise, it should log "You aren't adult!" // function checkAge(age, callback) { // if (age >= 18) { // callback("You are an adult!"); // } else { // callback("You are a minor!"); // } // } // function logMessage(message) { // console.log(message); // } // checkAge(20, logMessage); // checkAge(16, logMessage); // --------------------------------------- // Write a series of three functions that simulate an asynchronous process using callbacks: // task1(callback) that takes a callback and calls it after 1 second. // task2(callback) that takes a callback and calls it after 2 seconds. // task3(callback) that takes a callback and calls it after 3 seconds. Chain these functions together so that task1 runs first, followed by task2, and then task3. // function task1() { // setTimeout(() => { // console.log("Task 1 completed!"); // }, 1000); // } // function task2() { // setTimeout(() => { // console.log("Task 2 completed!"); // }, 2000); // } // function task3() { // setTimeout(() => { // console.log("Task 3 completed!"); // }, 3000); // } // ----------------------------------------------------------------- // solution: // function task1(callback) { // setTimeout(() => { // console.log("Task 1 completed!"); // callback(); // }, 1000); // } // function task2(callback) { // setTimeout(() => { // console.log("Task 2 completed!"); // callback(); // }, 2000); // } // function task3(callback) { // setTimeout(() => { // console.log("Task 3 completed!"); // callback(); // }, 3000); // } // task1(() => { // task2(() => { // task3(() => { // console.log("All tasks completed!"); // }); // }); // }); // ---------------------------------------------------------------------- // function greet(x) { // let z = new Promise((resolve, reject) => { // setTimeout(() => { // resolve(x); // }, 5000); // }); // return z; // } // greet("hello") // .then((x) => { // console.log(x); // }) // .catch((e) => console.log("error")); // let result = greet("hello"); // console.log(result instanceof Promise); // --------------------------------------------------------- // function myfunc() { // return new Promise((resolve, reject) => { // setTimeout(() => { // console.log("i am promise 1"); // resolve("success"); // }, 3000); // }); // } // function myfunc2() { // return new Promise((resolve, reject) => { // setTimeout(() => { // console.log("i am promise 2"); // resolve("success"); // }, 3000); // }); // } // myfunc(); // myfunc2(); // p1 = myfunc().then((res) => { // console.log(res); // p2 = myfunc2().then((res) => { // console.log(res); // }); // }); // -------------------------------------------------------------- // let p1 = myfunc(); // console.log(p1 instanceof Promise); // ------------------------------------------------------------- // Write a function that returns a Promise which resolves with a message after a given delay of 2 seconds. // function delayedMessage(message, delay) { // return new Promise((resolve) => { // setTimeout(() => { // resolve(message); // }, 2000); // }); // } // delayedMessage("Hello after 2 seconds", 2000).then((message) => // console.log(message) // );promise.txt// Promise - Promises are features in JS to handle asynchronous // operations in a more structured and readable way. // A promise has three possible states: // 1. Pending // 2. Fulfilled // 3. Rejected // ------------------------------------------------------------ // Creating a new Promsie // let promise1 = new Promise((resolve,reject)=>{ // setTimeout(()=>{ // console.log('promise is resolved') // resolve('success') // },5000) // }) // console.log(promise1) // ------------------------------------------------------------ let myPromise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("The operation was successful!"); } else { reject("Something went wrong!"); } }); myPromise .then(function(result) { console.log(result); }) .catch(function(error) { console.log(error); }); // ------------------------------------------------------------ let promise1 = new Promise((resolve, reject) => { setTimeout(() => { console.log("promise isn't resolved"); reject("not success"); }, 3000); }); promise1 .then((message) => { console.log(message); }) .catch((error) => { console.log(error); }); // --------------------------------------------------- ## // const a = new Promise((resolve,reject)=>{ // let x = 2 // if(x==3){ // resolve('success') // } // else{ // reject('error') // } // }) // a.then((msg)=>{console.log(msg)}).catch((e)=>{console.log(e)}) // ------------------------------------------------------------ // function greet(x){ // let z = new Promise((resolve,reject)=>{ // setTimeout(()=>{ // resolve(x) // }, 5000) // }) // return z // } // greet('hello').then((x)=>{console.log(x)}).catch((e)=>console.log('error')) // checking whether the result contains promise // let result = greet("hello"); // console.log(result instanceof Promise); // ------------------------------------------------------------ function myfunc() { return new Promise((resolve, reject) => { setTimeout(() => { console.log("i am promise 1"); resolve("success"); }, 3000); }); } function myfunc2() { return new Promise((resolve, reject) => { setTimeout(() => { console.log("i am promise 2"); resolve("success"); }, 3000); }); } let p1 = myfunc(); p1.then((res) => { console.log(res); let p2 = myfunc2(); p2.then((res) => { console.log(res); }); }); // --------------------------------------------------- // with simple syntax: myfunc().then((res) => { console.log(res); myfunc2().then((res) => { console.log(res); }); }); // -------------------------------------------------- function fetchData(success) { return new Promise((resolve, reject) => { setTimeout(() => { if (success) { resolve("Data fetched successfully"); } else { reject("Error fetching data"); } }, 2000); }); } fetchData(true) .then((data) => console.log(data)) .catch((error) => console.log(error)); fetchData(false) .then((data) => console.log(data)) .catch((error) => console.log(error));4 Decasync-await.txtAsync and await are used to handle asynchronous operations more easily as compared to callbacks or promises. async: The async keyword is used to define a function that returns a promise. It tells JavaScript that this function will contain asynchronous code and will eventually return a promise. await: The await keyword is used inside an async function to pause the execution of the function until a promise is resolved (or rejected). function my_func(id) { return new Promise((resolve, reject) => { setTimeout(() => { console.log(id); resolve("success"); }, 2000); }); } async function calling_my_func() { await my_func(1); await my_func(2); await my_func(3); await my_func(4); await my_func(5); } calling_my_func(); // ----------------------------------------- async function calling_my_func() { let result1 = await my_func(1); console.log(result1); let result2 = await my_func(2); console.log(result2); let result3 = await my_func(3); console.log(result3); let result4 = await my_func(4); console.log(result4); let result5 = await my_func(5); console.log(result5); } calling_my_func();exception_handling_ in_JS.txtException Handling in JavaScript: In JavaScript, exceptions are handled using the try...catch statement, and optionally finally. Here's how it works: try block: This is where you write code that might throw an exception (an error). catch block: If an exception occurs in the try block, it is caught in catch block where you can handle the error. finally block (optional): This block executes no matter what, whether an exception was thrown or not. It's useful for cleanup tasks. setTimeout(() => { console.log("i am a set time out function 1"); }, 1000); setTimeout(() => { console.log("i am a set time out function 2"); }, 2000); try { console.log(Mariya); } catch (error) { console.log(error); } setTimeout(() => { console.log("i am a set time out function 3"); }, 3000); // ------------------------------------------------------------------------- // try { // let age = -1; // if (age < 0) { // throw new RangeError("Age cannot be negative!"); // } // let user = null; // if (!user) { // throw new TypeError("User object is null!"); // } // } catch (error) { // if (error instanceof RangeError) { // console.log("RangeError:", error.message); // } else if (error instanceof TypeError) { // console.log("TypeError:", error.message); // TypeError; // } else { // console.log("Unknown error:", error.message); // } // } // ------------------------------------------------------------------------fetch_API.txt// --------------------------------- Fetch API -------------------------------------- // fetch - The fetch() method in JavaScript is used to request data from a server. // The request can be of any type of API that returns the data in JSON. // fetch returns a promise // console.log(fetch("https://jsonplaceholder.typicode.com/todos")) // ------------------------------------------------------------- // How fetch works?? // fetch("https://jsonplaceholder.typicode.com/todos") // .then((response)=>{console.log(response)}) // Fetch returns a Promise that resolves to the Response to that request, whether it is successful or not. // It allows us to work with responses available in various formats like json, text, binary, etc. // This response is parsed into json format which allows us to access and work with the // data in a structured and reliable manner // On parsing response into json, it returns another promise which is again resolved by another then. // This is the concept of using .then two times. // ex- // fetch("https://jsonplaceholder.typicode.com/todos") // .then((response)=>{return response.json()}) // .then((data)=>{console.log(data)}) // ------------------------------------------------------------- // get request using fetch // function func(){ // fetch('https://jsonplaceholder.typicode.com/todos') // .then((response)=>{ // return response.json() // }).then((data)=>{ // // console.log(data) // // console.log(data[0]) // document.getElementById('un_li').innerHTML = `<li>${data[0].userId},${data[0].id},${data[0].title},${data[0].completed}</li>` // }) // } // func()home.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> div { height: 100px; width: 100px; background-color: rgb(141, 82, 41); } </style> </head> <body> <div></div> <ul id="un_li"></ul> </body> <script src="home.js"></script> </html>home.js// Write a series of three functions that simulate an asynchronous process using callbacks: // task1(callback) that takes a callback and calls it after 1 second. // task2(callback) that takes a callback and calls it after 2 seconds. // task3(callback) that takes a callback and calls it after 3 seconds. Chain these functions together so that task1 runs first, followed by task2, and then task3. // function task1() { // setTimeout(() => { // console.log("Task 1 completed!"); // }, 1000); // } // function task2() { // setTimeout(() => { // console.log("Task 2 completed!"); // }, 2000); // } // function task3() { // setTimeout(() => { // console.log("Task 3 completed!"); // }, 3000); // } // ----------------------------------------------------------------- // solution: // function task1(callback) { // setTimeout(() => { // console.log("Task 1 completed!"); // callback(); // }, 1000); // } // function task2(callback) { // setTimeout(() => { // console.log("Task 2 completed!"); // callback(); // }, 2000); // } // function task3(callback) { // setTimeout(() => { // console.log("Task 3 completed!"); // callback(); // }, 3000); // } // task1(() => { // task2(() => { // task3(() => { // console.log("All tasks completed!"); // }); // }); // }); // ---------------------------------------------------------------------- // function greet(x) { // let z = new Promise((resolve, reject) => { // setTimeout(() => { // resolve(x); // }, 5000); // }); // return z; // } // greet("hello") // .then((x) => { // console.log(x); // }) // .catch((e) => console.log("error")); // let result = greet("hello"); // console.log(result instanceof Promise); // --------------------------------------------------------- // function myfunc() { // return new Promise((resolve, reject) => { // setTimeout(() => { // console.log("i am promise 1"); // resolve("success"); // }, 3000); // }); // } // function myfunc2() { // return new Promise((resolve, reject) => { // setTimeout(() => { // console.log("i am promise 2"); // resolve("success"); // }, 3000); // }); // } // myfunc(); // myfunc2(); // myfunc().then((res) => { // console.log(res); // myfunc2().then((res) => { // console.log(res); // }); // }); // p1 = myfunc().then((res) => { // console.log(res); // p2 = myfunc2().then((res) => { // console.log(res); // }); // }); // -------------------------------------------------------------- // let p1 = myfunc(); // console.log(p1 instanceof Promise); // ------------------------------------------------------------- // Write a function that returns a Promise which resolves with a message after a given delay. // function delayedMessage(msg, delay) { // return new Promise((resolve, reject) => { // setTimeout(() => { // resolve(msg); // }, delay); // }); // } // delayedMessage("Hello World", 3000).then((message) => { // console.log(message); // }); // // ----------------------------------------------------------------- // function my_func(id) { // return new Promise((resolve, reject) => { // setTimeout(() => { // console.log(id); // resolve("success"); // }, 2000); // }); // } // promise chain // my_func(1).then((res) => { // console.log(res); // my_func(2).then((res) => { // console.log(res); // my_func(3).then((res) => { // console.log(res); // my_func(4).then((res) => { // console.log(res); // }); // }); // }); // }); // my_func(2); // my_func(3); // --------------------------------------------------------------- // async-await: // function my_func(id) { // return new Promise((resolve, reject) => { // setTimeout(() => { // console.log(id); // resolve("success"); // }, 2000); // }); // } // async function calling_my_func() { // let result1 = await my_func(1); // console.log(result1); // let result2 = await my_func(2); // console.log(result2); // let result3 = await my_func(3); // console.log(result3); // let result4 = await my_func(4); // console.log(result4); // let result5 = await my_func(5); // console.log(result5); // } // calling_my_func(); // // -------------------------------------------------------- // -------------------------------------------------------------------- /// error handling : // setTimeout(() => { // console.log("i am a set time out function 1"); // }, 1000); // try { // console.log(Mariya); // } catch (e) { // console.log(e); // } // setTimeout(() => { // console.log("i am a set time out function 2"); // }, 2000); // setTimeout(() => { // console.log("i am a set time out function 3"); // }, 3000); // -------------------------------------------------- // ---------------------------------------------- // try { // let age = 1; // if (age < 0) { // throw new RangeError("Age cannot be negative!"); // } // let user = "a user"; // if (!user) { // throw new TypeError("User object is null!"); // } // } catch (error) { // if (error instanceof RangeError) { // console.log("RangeError:", error.message); // } else if (error instanceof TypeError) { // console.log("TypeError:", error.message); // TypeError; // } else { // console.log("Unknown error:", error.message); // } // } // console.log("hhsd"); // -------------------------------------------------------- // let promise = fetch("https://jsonplaceholder.typicode.com/todos"); // console.log(promise); // -------------------------------------------------------- // let url = "https://jsonplaceholder.typicode.com/todos"; // let promise = fetch(url).then((res) => { // console.log(res); // }); // console.log(promise); // fetch("https://jsonplaceholder.typicode.com/todos").then((response) => { // return response.json().then((data) => { // console.log(data[0]); // }); // }); // ----------------------------------------------------- // ----------------------------------------------------- // function func() { // fetch("https://jsonplaceholder.typicode.com/todos") // .then((response) => { // return response.json(); // }) // .then((data) => { // // console.log(data); // console.log(data[0]); // // console.log(data[0].userId); // document.getElementById( // "un_li" // ).innerHTML = `<li>${data[0].userId},${data[0].id},${data[0].title},${data[0].completed}</li>`; // }); // } // func(); // // { // // "userId": 1, // "id": 101, // "title": "Learn JavaScript", // "completed": false // } // <li>1, 101, Learn JavaScript, false</li>https://www.geeksforgeeks.org/what-is-an-api/?authuser=0https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch?authuser=05 Decfetch_API (2).txt// fetch("https://jsonplaceholder.typicode.com/todos") // .then((response) => { // return response.json(); // }) // .then((data) => { // const ul = document.getElementById("un_li"); // data.forEach((todo) => { // const li = document.createElement("li"); // li.innerHTML = `${todo.userId}, ${todo.id}, ${todo.title}, ${todo.completed}`; // ul.appendChild(li); // }); // }) // .catch((error) => { // console.error("Error:", error); // }); // -------------------------------------------------home.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> div { height: 100px; width: 100px; background-color: rgb(141, 82, 41); } </style> </head> <body> <div></div> <ul id="un_li"></ul> </body> <script src="home.js"></script> </html>home.js// let obj1 = { // userId: 999999, // id: 8453, // title: "My First API Object", // completed: true, // }; // function postdata() { // y = { // method: "POST", // headers: { // "Content-Type": "application/json", // }, // body: JSON.stringify(obj1), // }; // fetch("https://jsonplaceholder.typicode.com/todos", y) // .then((response) => { // return response.json(); // }) // .then((data) => { // console.log(data); // }); // } // postdata();// let promise = fetch("https://jsonplaceholder.typicode.com/todos"); // console.log(promise); // -------------------------------------------------------- // let url = "https://jsonplaceholder.typicode.com/todos"; // let promise = fetch(url).then((res) => { // console.log(res); // }); // console.log(promise); // fetch("https://jsonplaceholder.typicode.com/todos").then((response) => { // return response.json().then((data) => { // console.log(data[0]); // }); // }); // ----------------------------------------------------- // ----------------------------------------------------- // function func() { // fetch("https://jsonplaceholder.typicode.com/todos") // .then((response) => { // return response.json(); // }) // .then((data) => { // // console.log(data); // console.log(data[0]); // // console.log(data[0].userId); // document.getElementById( // "un_li" // ).innerHTML = `<li>${data[0].userId},${data[0].id},${data[0].title},${data[0].completed}</li>`; // }); // } // func(); // ------------------------------------------------------------- // JSON: Javascript Object Notation: // { // "userId": 1, // "id": 101, // "title": "Learn JavaScript", // "completed": false // } // <li>1, 101, Learn JavaScript, false</li> // ---------------------------------------------------------------- // fetch("https://jsonplaceholder.typicode.com/todos") // .then((response) => { // return response.json(); // }) // .then((data) => { // const ul = document.getElementById("un_li"); // data.forEach((todo) => { // const li = document.createElement("li"); // li.innerHTML = `${todo.userId}, ${todo.id}, ${todo.title}, ${todo.completed}`; // ul.appendChild(li); // }); // }) // .catch((error) => { // console.error("Error:", error); // }); // ------------------------------------------------- // let obj1 = { // userId: 999999, // id: 8453, // title: "My First API Object", // completed: true, // }; // function postdata() { // y = { // method: "POST", // headers: { // "Content-Type": "application/json", // }, // body: JSON.stringify(obj1), // }; // fetch("https://jsonplaceholder.typicode.com/todos", y) // .then((response) => { // return response.json(); // }) // .then((data) => { // console.log(data); // }); // } // postdata();(Edited 12 Dec)DATABASES = {
'default': {
'ENGINE': 'mssql',
'HOST' : 'your database server name',
'PORT' : '',
'NAME': 'your database name',
},
}
class Designation(models.Model):
title = models.CharField(max_length=255)class Employee(models.Model):
name = models.CharField(max_length=100, blank=True)
branch = models.CharField(max_length = 100)
HOD = models.CharField(max_length=50)
salary = models.IntegerField()
did = models.ForeignKey(Designation, on_delete=models.DO_NOTHING)
insert into MyApp_designation(title)VALUES ('Software Engineer')
insert into MyApp_designation(title)VALUES ('Project Manager')
insert into MyApp_designation(title)VALUES ('Data Analyst')
insert into MyApp_employee (name,branch,HOD,salary,did_id)
values ('Emily','IT','Robert Williams',5000,1),
('Anna','ML','Harry Brown',8000,3),
('Ben','IT','Robert Williams',9000, 2)
python manage.py makemigrations
python manage.py migrate
pip install mssql-django11 DecSHARING DJANGO COMMANDS :
1. command to install django:
pip install django
2.create project :
django-admin startproject ProjectName
3.create app :
django-admin startapp AppName
4.settings to be made :
Add app name in INSTALLED_APPS
5. command to run your web application:
python manage.py runserver
6. commands to make migration in django:
python manage.py makemigrationspython manage.py migrate11 Decmodels.pyfrom django.db import models # Create your models here. class Designation(models.Model): title = models.CharField(max_length=255) class Employee(models.Model): name = models.CharField(max_length=100, blank=True) branch = models.CharField(max_length = 100) HOD = models.CharField(max_length=50) salary = models.IntegerField() did = models.ForeignKey(Designation, on_delete=models.DO_NOTHING)urls.pyfrom django.urls import path from . import views urlpatterns = [ path("", views.home, name="home"), path("add", views.getEmployees, name="getallEmployees"), ]views.pyfrom django.shortcuts import render from django.http import HttpResponse from .models import Employee # Create your views here. # def home(request): # return HttpResponse("Hello World") def home(request): return render(request, "index.html", {"name": "Mariya"}) def getEmployees(request): obj = Employee.objects.all() # print(obj) empList = [] for i in obj: employee = i.__dictempList.append(employee) print(empList) return HttpResponse(empList)index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { background-color: crimson; } </style> </head> <body> <h1>Hello {{name}}</h1> </body> </html>12 Decurls.pyfrom django.urls import path from . import views urlpatterns = [ path("", views.home, name="home"), path("get", views.getEmployees, name="getallEmployees"), path("add", views.addEmployee, name="addAnEmployee"), ]views.pyfrom django.shortcuts import render from django.http import HttpResponse from .models import Employee from django.views.decorators.csrf import csrf_exempt # Create your views here. # def home(request): # return HttpResponse("Hello World") def home(request): return render(request, "index.html", {"name": "Mariya"}) def getEmployees(request): obj = Employee.objects.all() # print(obj) empList = [] for i in obj: employee = i.__dict__ empList.append(employee) print(empList) # return HttpResponse(empList) return render(request, "index.html", {"employee": empList}) @csrf_exempt def addEmployee(request): if request.method == "GET": return render(request, "form.html") if request.method == "POST": value = request.POST name = value["name"] branch = value["branch"] hod = value["hod"] salary = value["salary"] did = value["did"] objEmp = Employee(name=name, branch=branch, HOD=hod, salary=salary, did_id=did) objEmp.save() return HttpResponse("Employee added successfully!")form.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { background-color: crimson; } </style> </head> <body> <form action="" method="POST"> Name <input type="text" name="name" /><br /><br /> branch <input type="text" name="branch" /><br /><br /> hod <input type="text" name="hod" /><br /><br /> salary <input type="number" name="salary" /><br /><br /> did <input type="number" name="did" /><br /><br /> <input type="submit" /> </form> </body> </html>20 DecSharing Django Rest Framework files for practice
I have also attached the DRF documentation's link. please go through it for better understanding of the framework.
Important commands and code:
1. command to install Django :
pip install django
2. then Install Django REST framework :
pip install djangorestframework
3.create project :
django-admin startproject ProjectName
4.create app :
django-admin startapp AppName
#-------------------------------------------------5. add your App name and django_rest in Installed_Apps, in your
settings.py file.
add django_rest framework by writing:
rest_framework
#--------------------------------------------------
#---------------------------------------------------DATABASES = {
'default': {
'ENGINE': 'mssql',
'HOST' : 'Write your server name here',
'PORT' : '',
'NAME': 'Database name',
},
}
#-------------------------------------------------
model class:
class Employee(models.Model):
Name = models.CharField(max_length = 255)
hod = models.CharField(max_length=250)
salary = models.IntegerField()migration commands:
python manage.py makemigrations
python manage.py migratemodels.pyfrom django.db import models # Create your models here. class Employee(models.Model): Name = models.CharField(max_length=255) hod = models.CharField(max_length=250) salary = models.IntegerField()urls.pyfrom django.urls import path from . import views urlpatterns = [path("", views.home), path("emp", views.Emp)]views.pyfrom rest_framework.response import Response from rest_framework.decorators import api_view from .models import Employee from .serializers import EmployeeSerializer # Create your views here. @api_view() def home(request): return Response({"message": "Hello World"}) @api_view(["GET", "POST"]) def Emp(request): if request.method == "GET": queryset = Employee.objects.all() serializer = EmployeeSerializer(queryset, many=True) # print(serializer.data) return Response({"emp": serializer.data}) if request.method == "POST": value = request.data # print(value) serializer = EmployeeSerializer(data=value) if serializer.is_valid(): serializer.save() return Response("Employee added successfully!")serializers.pyfrom .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = "__all__"https://www.django-rest-framework.org/?authuser=0https://www.django-rest-framework.org/?authuser=0(Edited 27 Dec)SP.txt// STORED PROCEUDURE: Stored Procedure (SP) in SQL is a pre-written set of SQL statements that are stored in the database. It is basically like a function that you can execute whenever needed without having to rewrite the SQL code each time. select * from Person.Person CREATE PROCEDURE NEW_PROCEDURE as select * from Person.Person Exec NEW_PROCEDURE Execute NEW_PROCEDURE // ------------------------------------------------------------------------------------------ // creating SP with perameters: create procedure Procedure_2 @variable int as select * from Person.Person where EmailPromotion = @variable exec Procedure_2 @perameter = 2 // ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------ CREATE TABLE Customers ( CustomerID INT PRIMARY KEY, CustomerName VARCHAR(100), Email VARCHAR(100) ); // ------------------------------------------------------------------------------------------ INSERT INTO Customers (CustomerID, CustomerName, Email) VALUES (1, 'John Doe', 'johndoe@example.com'), (2, 'Jane Smith', 'janesmith@example.com'), (3, 'Sam Brown', 'sambrown@example.com'); // ---------------------------------------------------------------------------------------- CREATE PROCEDURE GetAllCustomers AS SELECT CustomerID, CustomerName FROM Customers; exec GetAllCustomers // ----------------------------------------------------------------------------------------- // Creating Stored Procedure With Parameters: CREATE PROCEDURE GetCustomerByID @CustomerID INT AS SELECT CustomerID, CustomerName, Email FROM Customers WHERE CustomerID = @CustomerID; EXEC GetCustomerByID @CustomerID = 2; // --------------------------------------------------------------------------------------- // Creating Stored Procedure With Parameters CREATE PROCEDURE GetCustomerByID @CustomerID INT AS SELECT CustomerID, CustomerName, Email FROM Customers WHERE CustomerID = @CustomerID; EXEC GetCustomerByID @CustomerID = 2; // ------------------------------------------------------------------------------------ CREATE PROCEDURE GetCustomersByFilters @CustomerID INT = NULL, @CustomerName VARCHAR(100) = NULL, @Email VARCHAR(100) = NULL AS SELECT CustomerID, CustomerName, Email FROM Customers WHERE (@CustomerID IS NULL OR CustomerID = @CustomerID) AND (@CustomerName IS NULL OR CustomerName LIKE '%' + @CustomerName + '%') AND (@Email IS NULL OR Email LIKE '%' + @Email + '%'); EXEC GetCustomersByFilters; EXEC GetCustomersByFilters @CustomerID = 1; EXEC GetCustomersByFilters @CustomerName = 'John'; EXEC GetCustomersByFilters @Email = 'example.com'; EXEC GetCustomersByFilters @CustomerID = 1, @CustomerName = 'John'; EXEC GetCustomersByFilters @CustomerID = 1, @CustomerName = 'John', @Email = 'example.com';indexing.txtIndexing in databases is the process of creating a data structure (an index) that allows for faster retrieval of records from a table. It works by providing a quick lookup of data, typically in the form of a sorted list or tree structure, enabling efficient search operations. Difference between Clustered and Non-Clustered Indexing: Clustered Index: In a clustered index, the data rows are stored in the same order as the index itself. There can only be one clustered index per table because the data rows can only be sorted in one way. It determines the physical order of the data. Non-Clustered Index: A non-clustered index, on the other hand, is a separate structure from the data rows. It contains pointers to the actual data, allowing for multiple non-clustered indexes on the same table. The data itself is stored in a different order, not necessarily matching the index order. SET STATISTICS IO ON select * FROM Person.Address SELECT AddressLine1,PostalCode FROM Person.Address WHERE City = 'Bothell'; CREATE NONCLUSTERED INDEX IX_City ON Person.Address (City) DROP INDEX IX_City ON Person.Address; // ---------------------------------------------------------------------------------------- CREATE NONCLUSTERED INDEX IX_PERSON_City ON Person.Address (City) include (AddressLine1,PostalCode) drop index IX_PERSON_City on Person.Address; // ---------------------------------------------------------------------------------------- CREATE CLUSTERED INDEX (table name) ON (column name)

Comments
Post a Comment