0% found this document useful (0 votes)
9 views40 pages

Python DS

The document provides an overview of Python programming basics, including data types, operators, input handling, control structures, functions, string formatting, loops, lists, and tuples. It covers key concepts such as dynamically typed variables, arithmetic and logical operators, user input, and the use of loops for iteration. Additionally, it explains string manipulation techniques and the differences between lists and tuples in Python.

Uploaded by

yuvraj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
9 views40 pages

Python DS

The document provides an overview of Python programming basics, including data types, operators, input handling, control structures, functions, string formatting, loops, lists, and tuples. It covers key concepts such as dynamically typed variables, arithmetic and logical operators, user input, and the use of loops for iteration. Additionally, it explains string manipulation techniques and the differences between lists and tuples in Python.

Uploaded by

yuvraj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
‘16/25, 7:22 PM 01 _Python_Basies Python is a dynamically typed object oriented programming language # Dynamically typed matlab hume datatypes define nahi karne padte y= 23 ke2 str = "Yuvraj Sachdeva" print(str) Yuvraj Sachdeve # This is a comment print (type(str)) print(float(k)) # Type Casting 21.0 ‘type(k) int str2 print(stri+str2) # Strings don't add up, they concatenate 2123 print(int(str1) + int(str2)) 44 localhost B888Habitree/Python_Revisioi01_Python_Basicsipynb? a 1516/25, 7:24 PM 02. strings In [1]: mame = "Yuvraj" In [5]: name eS): "Yuvraj" In [9]: name-upper() out[9]: "YUVRAI Tp [13]: name. lower () our[a3}s "yuvraj" In [17]: [Link]("j") out[i7]: True In [21]: mame-endswith("Y") out[2i}: False In [25]: name-count("a") out [25]: 4 In [31]: name[@:5] # Slicing of a string from Oth index till (n-1)th index out "Yuvra" 1] # Concept of negative indices In [39]: # Negative index ko positive main convert krne ke Liye jo thumbrule use hota hai vo # Uss negative index main string Length ko add kardenge toh kaam ban jayega In [43]: print(Len(name) ) 6 In [47]: name[1:5] # name[1:(-146)] = name[1:5] = name[1:-1] 7): ‘uvra In [Si]: # Ek or tareeka hai ki negative index main add karne ki jagah hum positive index ma In [55]: mame[-5:-2] put (55): ‘uvra localhost B888abitree/Python,Revisioi02_Stringsipynb? a 1516/25, 7:24 PM (03_Operators Operators in python 1. Arithmetic Operators Used for basic mathematical operations a=10 bes print(a +b) # Addition print(a - b) # Subtraction print(a * b) # Multiplication print(a / b) # Division print(a // b) # Floor Division print(a X b) # Modulus print(a ** b) # Exponential 1s 5 5e 2.e 2 @ 19800¢ 2. Comparison Operators Compares values and returns true or false y= 23 k = 21 print(y == k) # Equal to print(y I= k) # Not Equal to print(y > k) # Greater than print(y < k) # Lesser than print(y >= k) # Greater or equal to print(y <= k) # Lesser or equal to False True True False True False 3. Logical Operators Used to combine conditional statements localhost B888abitree/Python_Revisioni03_Operatorsjpynd? 18 1516/25, 7:24 PM 03_ Operators True True w= False print(u and v) # Both True (and) print(u and w) print(u or v) # Either one true (or) print(u or w) print(not u) # Negation print(not w) True False True True False True 4, Bitwise Operators Perform bit-level operations a=5 #101 b=3# et print(a & b) # AND Bitwise Operator - 101 8 611 => 146=6;081=0;181=1 print(a | b) # OR Bitwise Operator - 101 / @11=>1/6=1;@/1=1;1]1=1= 1 7 5. Assignment Operators Used to assign the values to variables 1-10 print(1) Lt 5 print(1) L-ss print(1) Less print(1) Liss print(1) f=10 fules print(#) £5 print(#) fees print(#) localhost B888abitree/Python_Revisioni03_Operatorsjpynd? 1516/25, 7:24 PM 18 15 18 5e 10.0 2 2 32 (03_Operators 6. Membership and Identity Operators Checks for presence and object identity list = [1, 2, 3] x=2 print(x in list) # checks for presence print(x not in list) # Checks for absence as? b=7 c= 10 print(a print(a print(a print(a True False True False False True localhost B888abitree/Python_Revisioni03_Operatorsjpynd? is is is b) oS) not b) not c) 1516/25, 7:24 PM 04 Input Taking Input from User x = input("Enter the value of x - ") y = input("Enter the value of y = ") print(x + y) 2123 Aisa isiye hua kyuki inputs by default are always stored in the form of strings In order to store them as integers or any other datatype we must do the following - y = int(input("Enter the value of y - ")) # TypeCasting string to int k = int(input("Enter the value of k - ")) # TypeCasting string to int print(y + k) 44. localhost B888abiree/Python_RevisioniO4_Inputipynb? a ‘516/25, 7:25 PM 05_Operator precedence PEMDAS (Parentheses -> Exponential -> Modulus/Multiplication/Division -> Addition/Subtraction) result = 10+2*3 print (result) 16 result = (10 + 2) * 3 print (result) 36 result = 2 ** 3 ** 2 # Ambiguity of exponentiation goes right to Left while anbguit print (result) 512 localhost 8888abrreelPython_Revilon!05_Operator_precedenceipynb? a 1516725, 7:25 PM Using If-Else-Elif ‘a = int(input("Enter your age - ")) if(a >= 18 and a < 60): print ("You can apply for a driving licens: else: print ("You are not eligible for a driving license") ) You can apply for a driving license p = float(input("Enter your percentage - ")) if(p >= 90): print("0 grade") elif(p >= 80): print("A grade") elif(p >= 70): print("8 grade") elif(p >= 60): print("C grade") elif(p >= 50): print("D grade") else: print ("Better luck next tine. 0 grade localhost B888abiree!Python_Revisioni06_i_elsooynb? a 1516725, 7:25 PM (o7_Functions Functions I def add(a, b): return a +b I add(21, 23) 44 I def avg(a = 0, b = 0): # Setting up default values in case no input is given return (a + b)/2 I avg(21, 23) dut[aa]: 22.8 tn (16): ave(23) but [16]: 11.5 Default arguments last main hi exist krne chahiye Initially hi default arguments set nahi karne None python main ek object hota hai jo yeh denote kme ke liye use hota hai ki kuch bhi return nahi ho rha ha I def greet(): print("Hello World”) I greet() Hello Worle localhost 8888abMree!Pytnon_Revision/O7_Functionsipynb? a 1516725, 7:25 PM (08 Match_Case Match-Case in Python def http_status(code): match code: case 200: return "OK" case 400: return "Bad Request” case 404: return "Not Found" case 500: return “Internal Server Error” : # Underscore acts as a default case return "Unknown Case” print (http_status(260)) print (http_status(5@5)) print (http_status(404)) oK Unknown Case Not Found localhost B888abitree/Python_Revision/08_Match_Case.jpynb? a 51625, 7:26 PM 09 _string_Fermating String Formatting in Python String -> Immutable DataType, and so python provides multiple ways to format strings like ~ format) and f-strings 1. Using format() ane = "Yuvraj" age = 20 print("My name is {} and I am {} years old”.format(name, age)) My name is Yuvraj and I am 2@ years ole print("{@} is learning {1)".format("Yuvraj", “Data Science")) print("{name} is learning {what)".format(nane = "Yuvraj", what = "Data Science")) Yuvraj is learning Data Science Yuvraj is learning Data Science 2. Using f-Strings (Recommended) Provides a cleaner and more readable way to format strings Ae b=10 print(f"sum of {a} and {b) is {a + b}") Sum of 5 and 10 is 15 pi = 3.10159 print(#"pi rounded to 2 decimal places is - {piz.2F}") pi rounded to 2 decimal places is - 3.14 print(f"{'Python' :<19}") # Left-align kardo in a total character width of 10 print(#"{' Python ) # Right-align kardo in a total character width of 10 print(f"{"Python':*1@}") # Center-align kardo in a total character width of 18 Python Python Python localhost B888Habitree/Python_Revisioni03_Sting_Formatingipynb? a 51625, 7:26 PM 10_Loops Loops in Python Python has 2 main loops - for and while 1, For Loop Used to iterate over sequences like lists, tuples and strings fruits = ["apple", "banana", “cherry"] for fruit in fruits: print (fruit) apple banana cherry Using range() for i in range(3): print (i) 2. While Loop Runs as long as condition is True count = @ while(count < 3): print (count) count += 1 3. Loop Control Statements areak -> Exits the loop, continue -> Skips to the next iteration, pass -> Does nothing (used asa placeholder! for i in range(3): Gf(d == 3): localhost 8888abfreytnon_Revision!10_Loopsipynb? 4 51625, 7:26 PM 10_Loops break # Loop breaks at i = 3 print(i) I for item in fruits: pass print ("Using pas: Using pass 2]: for iten in fruits: Af (item == "banana"): continue print (item) apple cherry localhost 8888abfrerPytnon_Revision!10_Loopsipynb? 51625, 7:26 PM tists Python Lists and List Methods A List in python is ordered, mutable collection of elements. It can contain elements of different types. Creating a List my_empty_list = [] # Empty List ny_list_with_same_elements = [1, 2, 3, 4, 5] # List with elements ny_list_with_different_elements = [1, "Yuvraj", 21.23, True] # List with mixed data print(ny_enpty_list) print(ny_list_with_same_elements) print(ny_list_with_different_elenents) a [1, 2, 3, 4 5] [1, ‘Yuvraj’, 21.23, True] Common List Methods 1 = [21, 16, 5, 19] 4 append(x) adds element x to the end of the List [Link](23) print(1) # extend(iterable) extends the List by appending all eLenents from an iterable Leextend([9, 4, 8, 10]) print (1) # insert (index, x) inserts x at specified index Leinsert(S, 21) print(1) # remove(x) removes the first occurence of x in the List [Link](9) print(1) # pop([index]) removes and returns the element at index (Last element if index is n [Link](@) print(1) # index(x) returns the index of the first occurence of x print ([Link](23)) # count(x) returns the number of times x appears in the List print([Link](23.21)) print([Link](5)) # sorted(List) returns a new List which is sorted version of original List localhost 8888abrretPytnon_Revision/tt_Lists/pynb? 1 51625, 7:26 PM Mts print (sorted(1)) print(1) # sort() sorts the List in ascending order Lesort() print(1) # reverse() reverses the order of the List Lereverse() print(1) # copy() returns a shallow copy of the List ni = [Link]() print(nl) # clear() removes all the elenents from the List [Link]() print(1) (21, 16, 5, 19, 23] [21, 16, 5, 19, 23, 9, 4, 8, 10) [21, 16, 5, 19, 23, 21, 9, 4, 8, 10] [21, 16, 5, 19, 23, 21, 4, 8, 10] [16, 5, 19, 23, 21, 4, 8, 10] 3 a 1 [4, 5, 8, 16, 16, 19, 21, 23] [16, 5, 19, 23, 21, 4, 8, 10] [4, 5, 8, 16, 16, 19, 21, 23] (23, 21, 19, 16, 10, 8, 5, 4] (23, 21, 19, 16, 10, 8, 5, 4] a list_of_list = [1, 2, 3, 4, 5, (21, 23]] print (1ist_of_list[5]) print(1ist_of_list(s][1]) (21, 23 23 11 = [5, 16, 21] 12 = [23, 19] print(11 + 12) # List concatenation [5, 16, 21, 23, 19] if(21 in 14): print("Yes") Yes s = "Yuvraj-Sachdeva-Will-Be-The-Greatest-Coder-Of-All-Time” [Link]("-") # Splitting a string to a List localhost 8888abrretPytnon_Revision/tt_Lists/pynb? 1516725, 7:26 PM tits "Yuvraj", *sachdeva' ‘will’ "Be', ‘The’, ‘Greatest’, *coder", ‘oF, ‘all’, "Time’ localhost 8888abrretPytnon_Revision/tt_Lists/pynb? 1516125, 7:27 PM 12 Tuple Python Tuples and Tuple Methods A Tuple is an ordered, immutable (Once created, elements cannot be changed) collection of elements. tis similar to List but once created, its elements cannot be modified. Accessing elements in a tuple is faster than in a list. Since Tuples are immutable, they can be used as «eys in dictionaries Creating a Tuple enpty_tuple = () # Empty Tuple tuple_with_same_elements = (1, 2, 3, 4, 5) # Tuple with elements tuple_with_different_elements = (1, 2, 23.21, "Sachdeva", True) # Tuple with Mixed tuple_with_single_element = (23, ) # Tuple with single element (Conma is necessary) print (empty_tuple) print (tuple with_sane_elenents) print (tuple_with_different_elenents) print (tuple_with_single_elenent) 0 (1, 2, 3, 4 5) (1, 2, 23.21, ‘Sachdeva', True) 3,) Accessing Tuple Elements my_tuple = (10, 20, 30, 40) print(my_tuple[1]) print (my_tuple[@:3]) 28 (10, 28, 30) Tuple Packing And Unpacking person = ("Yuvraj", 21, "Engineer") # Packing name, age, profession = person # Unpacking print (name) print (age) print (profession) Yuvraj 21 Engineer When to Use Tuples ? 1. When you want an unchangeable collection of elements localhost B888abitree/Python_Revision!t2_Tupleipynb? 4. 1516125, 7:27 PM 12 Tuple [Link] you need a faster alternative to lists 3. When storing heterogeneous data localhost B888abitree/Python_Revision!t2_Tupleipynb? 1516125, 7:27 PM [Link] Python Sets And Set Methods A Set in python is an unordered (indexing nahi kar sakte), mutable and unique collection of elements. It doesn't allow duplicate values Creating a Set enpty_set = set() # Empty set - Must use set() and not {} # () >> Yeh ek empty dictionary bana dega numbers = {1, 2, 3, 4, 5} # Set with elements mixed_set = {21, "Yuvraj", 21.23, True} # Set with mixed data types print(empty_set) print (numbers) print(mixed_set) set() {1, 2, 3, 4, 5} {'Yuvraj', True, 21.23, 21) # Creating a Set from a List unique_nunbers = set([1, 2, 3, 4, 4, 5, 6, 7, 7]) print(unique_nunbers) {1, 2, 3, 4, 5, 6, 7) Common Set Methods s = (1, 2, 3, 4, 5} [Link](6) print(s) [Link]([7, 8, 9]) print(s) [Link](9) # Removes the desired element and raises an error if the element not fo print(s) [Link](1@) # Removes the desired element and doesn't raise an error is the elene print(s) 2 = [Link]() # Removes and returns @ random element print(a) print(s) y = [Link]() # Creates a shallow copy of the set print(y) yclear() # Renoves all the elements from the set print(y) localhost 8888abrree!Pytnon_Revision!t3_Setsipynb? 4 1516125, 7:27 PM [Link] {1, 2, 3, 4, 5, 6) {1, 2, 3, 4, 5, 6 7, 8, 9} {1, 2, 3, 4, 5, 6, 7, 8) {1, 2, 3, 4, 5, 6, 7, 8) 1 {2, 3, 4, 5, 6 7, 8) {2, 3, 4 5, 6 7, 8) set() Set Operations set = (1, 2, 3, 4, 5} set2 = (3, 4, 5, 6, 7, 8} set3 = [Link](set2) # Returns a new set with all unique elements from both sets print(set3) seta = [Link](set2) # Returns a set with elements common to both sets print(seta) sets = [Link](set2) # Returns a set with elements in set1 but not in set2 print(sets) set6 = seti.synnetric_difference(set2) # Returns a set with elements in either set print(set6) set7 = (3, 4, 5, 6} print([Link](set2)) # Returns True if set7 is the subset of set2 print([Link](set1)) print([Link](set7)) # Returns True if set is the superset of set7 print([Link](set7)) {1, 2, 3, 4, 5, 6, 7, 8) (3, 4, 5} (1, 2} {1, 2, 6, 7, 8} True False False True seta = (1, 2, 3, 4} sets = (3, 4, 5, 6} print(seta | setB) # Union print(setA & setB) # Intersection print(seta - setB) # Difference print(setA * setB) # Synmetric Difference {1, 2, 3, 4, 5, 6) {3, 4} {1, 2} {1, 2, 5, 6} localhost 8888abrreetPytnon_Revision!13_Setsipynb? 1516125, 7:27 PM localhost B888abitree/Python_Revision!t4_Dictionarosipynb? 14. Dictionaries Python Dictionaries and Dictionary lethods A Dictionary in python is an unordered (3.7 onwards ordered hoti hai and usse pehle unordered), mutable and key-value pair collection. It allows efficient data retrieval and modification Creating a Dictionary enpty_dict = (} # Empty Dictionary student = { "name" : “Yuvraj Sachdeva", "age" : 21, “grade” : "0" } # Dictionary with key-value pairs person = dict(name = "Yuvraj Sachdeva", age = 21, city = "New Delhi") # Using dict( print (enpty_dict) print (student) print(person) tt {'name': ‘Yuvraj Sachdeva', ‘age’: 21, ‘grade’: '0") {'name': ‘Yuvraj Sachdeva', ‘age’: 21, ‘city': ‘New Delhi") Accessing Dictionary Elements print(student["nane"}) # Using keys Using get() -> Avoids KeyError if key doesn't exist print([Link]("age")) print([Link]("college", "Not Found")) # Setting default value Yuvraj Sachdeve 21 Not Found Dictionary Methods print([Link]()) # Returns all keys in the Dictionary print([Link]()) # Returns all values in the Dictionary print([Link]()) # Returns key-value pairs as tuples # get(key, default) -> Returns value for key or default is key not found student_new “junior” : "Rajvir Sachdeva", “age_of_junior" : 11, "grade_of_junior” : 18 1516125, 7:27 PM 14. Dictionaries d student .update(student_new) # Merge student_new into student print (student) a = [Link](“name", "Not Found") # Removes key and returns its value or default print(a) print (person) b= [Link]() # Removes and returns the Last inserted key-value pair print(b) print(person) ¢ = [Link](“city", “Unknown") # Returns value for key, else sets it to print(c) print(student) new_dict = [Link]() # Creates a shallow copy of the dictionary print(new_dict) new_dict.clear() # Removes all items from the Dictionary print(new_dict) dict_keys(['name", ‘age’, ‘grade"]) dict_values(['Yuvraj Sachdeva', 21, '0°]) dict_items([(‘name', "Yuvraj Sachdeva'), (‘age’, 21), (‘grade', ‘0")]) {'nane’: "Yuvraj Sachdeva', ‘age’: 21, ‘grade’: '0', ‘junior’: ‘Rajvir Sachdeva', ge_of_junior': 11, ‘grade_of_junior': ‘0') Yuvraj Sachdeve {'age': 21, ‘city’: 'New Delhi") (city’, ‘New Delhi") {'age': 21) Unknown {'name': "Yuvraj Sachdeva', ‘age’: 21, ge_of_junior’: 11, ‘grade_of_junior’: {'nane’: "Yuvraj Sachdeva", ‘age’: 21 ge_of_junior': 11, 'grade_of junior’ 0 ‘junior’: 'Rajvir Sachdeva’, ‘a “unknown } ‘junior’: 'Rajvir Sachdeva', Unknown" } I for key, value in [Link](): print(key, ":", value) name : Yuvraj Sachdeva age: 21 grade : 0 junior : Rajvir Sachdeve ‘age_of_junior : 11 grade_of_junior : 0 city: Unknown Dictionary Comprehension square = (x: x**2 for x in range(1,6)} for key, value in square. itens(): print(key, ": ", value) localhost B888abitree/Python_Revision!t4_Dictionarosipynb? 1516125, 7:27 PM 14. Dictionaries 6 5 type(square) dict localhost B888abitree/Python_Revision/t4_Dictionarosipynb? 1516125, 7:27 PM 15_Fle_ Handling File Handling In Python Allows python programs to read, write and manipulate files stores on disk. Python provides ouilt-n functions for working with files Opening A File Python uses open() function to open a file. Syntax -> file = open("filename", mode) * filename -> The name of the file to open * mode -> Specifies how the file should be opened File Modes © > Read (default) - Opens files for reading, raises an error ifthe file doesn't exist. * \w'-> Write - Opens files for writing, creates a new file if not found, and overwrites existing content * a'-> Append - Opens file for writing, creates a new file if not found, and appends ntent instead of overwriting. © x’ -> Create - Creates a new file, but fails if the file already exists. © ‘b’-> Binary Mode - Used with rb, wb, ab, etc. for working with non-text files(eg - images, PDFs, etc). ® 't'-> Text Mode - Used for text files(eg - rt, wt, etc.) Reading Files Using read() - Read entire file file = open(*[Link] content = file read print(content) fileclose() # Always close the file after use Using readline() - Read line by line localhost B888abitree!Pytnon_Revision/1§_Fle_ Handling ipynb? 4 1516125, 7:27 PM 15_Fle_ Handling file = open("example.t content = [Link]( # Reads first line print(linet) [Link]() # Always close the file after use Using readlines() - Read all lines as List file = open(*[Link] lines = file.readlines0 # print(ines) fileclose() # Always close the file after use ds all lines into a list Writing to Files Using write() - Overwrites Exi: ing Content file = opent*[Link]’, [Link](*Hello World!") # Writes Content fileclose() # Always close the file after use 'w") # Opens files in write mode Using writelines() - Write multiple lines lines "Hello\n", "My Name is\n", "Yuvraj Sachdeva\n"} file = open("[Link]’, "w’) [Link](lines) # Writes multiple lines [Link]() # Always close the file after use Appending to a File Used to add content to an existing file without erasing previous date file = open(*[Link] [Link](*\nThis is an appended line", fileclose() Using with Statement (Best Practice) localhost B888abitree!Pytnon_Revision/1§_Fle_ Handling ipynb? 24 1516125, 7:27 PM 15 File_ Handling Using with opend ensures the file is automaticaly closed after executior with open("example:txt "r) as file content = filereado) print(content) # No need to manually close the file Checking if a file exists Use the os module to check ifa file exists before opening it import os if [Link] exists("[Link]") print("File exists! else print(*File not found!") Deleting a File Use the os module delete a file import os if [Link]("[Link]") [Link]("[Link]") print("File Deleted.", else print("File does not exist”) Working with Binary Files Binary files (jpg, .png, .pdf, etc.) should be opened in binary mode ('b’) Reading a Binary File with open("image jpg’, “rb") as file data = [Link]) print(data) # Outputs Binary Content localhost B888abitree!Pytnon_Revision/1§_Fle_ Handling ipynb? aa 1516125, 7:27 PM 15 File_ Handling Writing a Binary File with open("new_imagejpg’, “wb*) as file [Link](data) # Writes Binary content to new File with open("[Link]", "n") as file: content = [Link]() print (content) Yuvraj Sachdeva is the best Coder in the world, s = "\nHe's currently doing Data Science” with open("[Link]", "a") as f: [Link](s) with open(“[Link]", "n") as file: content = [Link]() print (content) Yuvraj Sachdeva is the best Coder in the world. He's currently doing Data Science with open("[Link]", “w") as file: [Link]("Yuvraj is doing File Handling using Python.") import os Af os. [Link]("[Link]"): print("File exists!") else: print("File not found!") File exists: localhost B888Habitree/Python_Revision/1§_F Manaingipynb? 4 516725, 7:28 PM 16.JS0N Python json Module - Working with JSON Data JSONUavaScript Object Notation) is a lightweight data format used for data exchange detween servers and applications. It is widely used in APIs, web applications anc configurations. Python provides the json module to work with JSON data Importing the JSON Module import jsor Converting Python Objects to JSON (Serialization) Serialization (also called encoding or dumping) is converting the python object into a JSON- formatted string [Link]() - Converts python object to json String import json data = {"name": "Yuvraj", “age”: 21, "city": "New Delhi") Json_string = [Link](data) print(json_string) print (type(json_string)) {‘name": "Yuvraj", "age": 21, "city": "New Delhi") [Link]( - Writes JSON Data to a file with open(“data. json", "w") as file: [Link](data, file) with open(“data. json", " content = [Link]() print (content) ") as f: {"name": "Yuvraj", "age": 21, "city": "New Delhi"} localhost 8888abfree!Pytnon_Revision!16_JSON joynb? 4. 516725, 7:28 PM 16.JS0N Converting JSON to Python Objects (Deserialization) Deserialization (also called decoding or loading) is converting json formatted data inte Python Objects [Link]() - Converts JSON string to Python Object Json_data = ‘{"name": "Yuvraj", "age": 21, " ‘New Delhi"}" python_obj = json. loads( json_data) print (python_obj) print(type(python_obj)) {'name': "Yuvraj ‘age’: 21, ‘city’: 'New Delhi'} [Link]() - Reads JSON Data from a file with open(“[Link]", "r") as file: python_data = json. load(file) print (python_data) {'name': "Yuvraj", ‘age’: 21, ‘city’: ‘New Delhi*} Formatting JSON Output You can format JSON for better readability using indentation formatted_json = [Link](data, indent=4) print (formatted_json) localhost 8888abfree!Pytnon_Revision!16_JSON joynb? 516725, 7:28 PM sT_00P Object Oriented Programming Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects that contain both data (attributes) and behavior (methods). Key concepts of OOP Class - A blueprint for creating objects Object - An instance of a class with specific data and behavior. Attributes - Variables that store data for an object. Methods - Functions inside a class that define object behavior Encapsulation - Restricting direct access to an object's data Inheritance - Creating a new class from an existing class Polymorphism - Using the same method name for different classes 1. Defining a Class and Creating an Object Creating a Class class Car: def __init_(self, brand, model): [Link] = brand [Link] = model def display_info(self): return f"{[Link]}, {[Link])" # Creating an object (Instance) carl = Car("Mini", "Cooper") print (cart. display_info()) Mini, Cooper 2. Encapsulation (Data Hiding) Encapsulation prevents direct modification of attributes and allows controlled access using getter and setter methods. class BankAccount: def _init_(self, balance): [Link] = balance def get_balance(self): return self. balance localhost B888abitree/Python_Revisionit7_OOPipynb? 48 516725, 7:28 PM sT_00P def deposit(self, anount): if(anount > @): self-balance += amount # Using Encapsulation account = BankAccount(1000) account .deposit (5202) print (account.get_balance()) 6000 Why use encapsulation? It protects data by restricting direct modification, 3. Inheritance (Reusing Code) Inheritance allows a class (child) to inherit attributes and methods from another class (parent) Example of Single Inheritance class Animal: def speak(self): return "Animal makes a sound” class Dog(Animal): # Inheriting from Animal def speak(self): return "Bark" dog = Dog() print (dog. speak()) Bark Why use inheritance? It promotes code reusability and maintains a cleaner code structure. Example of Multiple Inheritance A class can inherit from multiple parent classes class A: def method_a(self): return "Method A" class 8: def method_b(self): return "Method 8" class C(A, 8): # Multiple Inheritance pass obj = C() localhost B888abitree/Python_Revision!t7_OOPipyab? 28 516725, 7:28 PM sT_00P print (obj-method_a()) print(obj-method_b()) Method & Method Why use multiple inheritance? Itallows a class to inherit features from multiple parent classes. 4, Polymorphism (Same Method, Different Behavior) Polymorphism allows different classes to use the same method name Method Overriding Example class Bird: def fly(self): return "Birds can fly" class Penguin(Bird): def fly(self): return "Penguins can't fly” bird = Bird() penguin = Penguin() print (bird. fly()) print (penguin. fly()) Birds can fly Penguins can't fly Why use polymorphism? It provides flexibility by allowing different classes to define the same method differently 5. Abstraction (Hiding Implementation Details) Abstraction is used to define a method without implementing it in the base class. itis achieved using abstract base classes (ABC module). from abc import ABC, abstractmethod # Inporting abstract base classes module class Shape(ABC): @abstractmethod def area(self): pass # No implementation localhost B888abitree/Python_Revision!t7_OOPipyab? ais 516725, 7:28 PM sT_00P class Square(Shape) : def _init_(self, side): [Link] = side def area(self): return [Link] * [Link] # Implemented in child class square = Square(4) print(square-area()) 16 Why use abstraction? It enforces consistent implementation across child classes. 6. Magic Methods (Dunder Methods) Magic methods allow objects to behave like built-in types # Example - _str_() and _Len_() class Book: def _init_(self, title, pages): [Link] = ti [Link] def __str_(self): # String representation return f"Book - {[Link]}” def _len_(self): # Define behaviour for Len() return [Link] book = Book("Object Oriented Programming", 7) print(str(book)) print(1en(book)) Book - Object Oriented Progranming 7 7. Class vs Static Methods Instance Method - Works with instance attributes (Uses self and not cls) Class Method - Works with class attributes (Uses cls and not self, Static Method - Does not use class or instance variables (Uses neither cls nor self) class Example class_var = "I an a class variable" def instance_nethod (self): return “Instance Method" @classmethod localhost B888abitree/Python_Revision!t7_OOPipyab? 46 516725, 7:28 PM sT_00P def class_method(cls): return cls.class_var Q@staticmethod def static_method() return "Static Method" obj = Example() print (obj-instance_method()) print (Example.class_nethod()) print (Example. static_nethod()) Instance Methoc I ama class variable Static Method class Employes company = “Google” def _ init__(self, name, salary): # Creating a constructor [Link] = nane [Link] = salary def printDetails(self): print(f"The conpany of {[Link]} is {[Link]} with salary - {[Link] Q@staticmethod def printTime(): print(f*The time is now") @classmethod def printClassbetails(cls): print(f"The conpany is {[Link])") e = Employee("Yuvraj", 4500000) # Object of Employee class e-printbetails() [Link]() [Link]() The company of Yuvraj is Google with salary - 4500000 The time is now The company is Google localhost B888abitree/Python_Revision!t7_OOPipyab? 55 516725, 7:28 PM 18_List Comprehension List Comprehension In Python Itisa concise and efficient way to create to create Lists in python. It allows you to generate Lists in a single line of code, making your code more readable and Pythonic 1. Basic Syntax [expression for item in iterable] * expression -> The operation to perform on each item ® item -> The variable representing each item in the iterable. ® terable -> The data structure being iterated over (Lis, range, etc) Example - Creating a list of squares squares = [x**2 for x in range(1, 6)] print (squares) [1, 4, 9, 16, 25] 2. Using if condition in List Comprehension Example - Filtering even numbers evens = [x for x in range(1, 11) if x % 2 == 0] print(evens) (2, 4, 6, 8, 1@] 3. Using if-else condition in List Comprehension Example - Replacini even number with "Even" and odd numbers with "Od numbers = ["Even" if x % 2 == @ else “Odd” for x in range(1, 11)] print (numbers) ['Odd", ‘Even’, "Odd", ‘Even’, ‘Odd’, ‘Even’, ‘Odd', 'Even", 'Odd', ‘Even localhost B888abitree!Python_Reviion/18_List_Comprehension pynb? 18 ‘516/25, 7:28 PM 18_List Comprehension 4, Nested Loops in List Comprehension Example - Creating pairs for two Lists pairs = [(x, y) for x in range(2) for y in range(3)] print(pairs) [(@, @), (8 4), (® 2), (1, @), (ty 1), (1, 29) 5. List Comprehension with Functions Example - Converting a List of strings to uppercase words = ["Yuvraj", "Sachdeva", "Google”] upper_words = [[Link]() for word in words] print (upper_words) ['YUVRAI', "SACHDEVA', "GOOGLE" 6. List Comprehension with Nested List Comprehension Example - Flattening a 2D List matrix = [[1, 2], (3, 4], (5, 6]] flattened = [num for row in matrix for num in row] print (Flattened) [1, 2,3, 4, 5, 6 7. List Comprehension with Set and Dictionary Comprehensions Set Comprehension unique_nunbers = {x for x in [1, 2, 2, 3, 4, 4]) print (unique_nunbers) localhost B888abitree!Python_Reviion/t8_List_Comprohension pynb? 28 516725, 7:28 PM 18_List Comprehension {1, 2, 3, 4) Dictionary Comprehension squared_dict = {x: x**2 for x in range(1, 6)) print (squared_dict) {Ar 1, 2: 4, 3:9, 4: 16, 5: 25) When to use List Comprehension? ® When you need to create a List in a single line * When the logics simple and readable ® When you want to improve performance (faster than loops} When to not use List Comprehension? * When the logic is too complex (use a standard loop instead for clarity) Performance Comparison - List Comprehension vs oop import time # Using a for Loop start = [Link]() squares_loop = [] for x in range(10**6): squares_loop. append(x**2) print("Loop Time -> ", ([Link]() - start)) # Using List Comprehension start = [Link]() squares_conp = [x**2 for x in range(19**6)] print("List Comprehension time -> ", ([Link]() - start) Loop Time -> @.40025973320007324 List Comprehension time -> @.23821496963500977 localhost B888abitree!Python_Reviion/18_List_Comprohension pynb? 516725, 7:29 >M 19 _Lambea Lambda Function In Python A lambda function in python is anonymous, single-expression function defined using lambde Keyword to define a lambda functior ® arguments -> Input parameters (comma-separated) ® expression -> The operation performed (must be single expression, not multiple statements) Example - Simple Lambda Function square = lambda x: x**2 print(square(5)) 25 2. Using lambda function with map(), filter() and reduced 2.1 Using map() with lambda Applies a function to each element of an iterable numbers = [1, 2, 3, 4] squared = list(map(lambda x: x**2, numbers)) print (squared) [1, 4, 9, 16] 2.2 Using filter) with lambda Filters elements based on a condition localhost B888abitree!Python_Reviion!18_Lambda ipynb? 13 516725, 7:29 >M 19 _Lambea numbers = [1, 2, 3, 4, 5, 6] evens = list(filter(Lambda x: x % 2 print (evens) [2, 4, 6] 2.3 Using reduce() with lambda Reduces an iterable to a single value (requires [Link]} from functools import reduce numbers = [1, 2, 3, 4] product = reduce(lanbda x, y: xy, numbers) print (product) 24 3. Lambda with multiple Arguments Example - Adding 2 numbers add = lambda x, y: x+y print(add(21, 23)) 4a Example - Finding the Maximum of 2 numbers maximum = lambda x, y: x if x > y else y print (maximum(21, 23)) 4, Lambda in Sorting Functions Sorting a List of Tuples students = [("Yuvraj", 21), ("Rajvir", 16), ("Kashvi", 23)] [Link](key = lambda student: student[1]) # Sorting by birthdate print (students) [CRajvir', 16), (‘Yuvraj', 21), (*Kashvi', 23)] localhost B888abitree!Python_Reviion!18_Lambda ipynb? 516725, 7:29 >M 19 _Lambea When to use Lambda Function? * When the function is short and simple * Used temporarily inside another function (eg. map, filter * To avoid defining the full function with def When to not use Lambda Function? * When the function is complex (use def for better readability) * When multiple operations/statements are needec localhost B888abitree!Python_Reviion!18_Lambda ipynb?

You might also like