Partial preview of the text
Download Python Complete Handwritten Notes: Basics, OOP, Functions, File Handling & NumPy/Pandas and more Study notes Computer Science in PDF only on Docsity!
7 PYTHON NOTES $ (pron sass if . | Python is a high - level , interpreted, general-purpose programming | language. It is easy to learn and has a simple syntax. I | NS Ee ete, ee ee =) 1. Features OF PYTHON HELLO WORLD PROGRAM . Easy to learn and readable # Sap: a ae © Interpreted and Interactive print (“Hello, World !”) e High - level language e Dynamically typed | * Object - oriented Output : Hello, World ! ° Large standard library ° Platform independent ( Write once, run anywhere) 2. SYNTAX + Python syntax is simple and similar to English. > Common DATA TYPES = e Statements are written in a new line. Data Type Description int Intege bers 3. VARIABLES AND DATA TYPES ee float Decimal numbers e A variable is used to store data. str String of characters * No need to declare the type, bool Tes one Ealee Python infers it automatically list Ordered, mutable collection Example : tuple Ordered, immutable collection name = “Abhi” # string set Unordered collection of age = 22 # integer Unique items height = 5.8 # float dict Key-value pairs is_student = True # boolean 4, BASIC OPERATORS DB: TYPE CONVERSION Operator Name Example Result ant tO, ) + Addition 5 +2 7 ch >| float = Subtraction 5-2 3 I es | fe * Multiplication | 5 * 2 10 ae int / Division 5/2 2:5 wvisi Example we | Exponentiation | See 2 | 25 oh “fi ele eg i ¢ = str(a) type(c) > str 6. INPUT AND OUTPUT pe eee xample : Exampl * Output : print() function is used to display output. name = input (“Enter your name : ”) * Input : input() function is used to take input print (“Hello,”, name) from the user. 4° Topic 2 : FUNCTIONS },+ pcos ee = Why Functions ? A function is a block of code that performs a specific task. It helps in code reusability and makes the program modular and easier to understand. *. SYNTAX r >) def function_name ( parameters ) :-7—> Function header * Improves readability * Reusability of code * Reduces complexity * Easier testing and debugging ' | i i ! | i 1 1 { i | l 2. EXAMPLE # Program to add two numbers def add(a, b): sum = ath return sum x = add (5, 7) print(“Sum =", x) # Output : Sum = 12 4. PARAMETERS AND ARGUMENTS # statements —> Body return value > Return L statement 3. TYPES OF FUNCTIONS Type Description Example Built-in Predefined functions in | print (), len(), type(), Python. input (6) User-defined | Functions created by | def my func() : the programmer. pass Anonymous Funetions without a | lambda x: x*x name (using lambda). Recursive || Functions thet call |/deP fact (n)): themselves. fact (n-1) 5. RETURN STATEMENT + return is used to send a result back from the function. + The function stops executing when return is encountered. Example : def square(n): return n#n Fe )- If return is not used, the function returns None by ¢ Parameters are the variables listed in the function definition. * Arguments are the actual values passed during the function call. Example : def greet (name) : # parameter print (“Hello,”, name) greet (“Abhi”) # argument Types of Arguments : Positional, Keyword , t Default , Variable-length ( *args, **kwargs) Paes [yf Agee: tin, o> 6. Flow oF FUNCTION EXECUTION Function Call <--- Execute statements in body return statement (if any) print (square (6)) # Output : 36 default . Return control to caller Note ! Good function names are meaningful and follow snake case (c¢.9., calculate sum). > 1 | ! | | | 1 1 | 1 | i | > Topic 4 : FILE HANDLING > File handling allows a program to read from a file or write data to a file. Python provides built-in functions to create, read, update and delete files. 1. OPENING A FILE © open() function is used to open a file. # Syntax : (# = open( filename, mode) } filename > name of the file (with path if needed) mode —> mode in which file is opened Common Modes : | Why File Handling ? | ee es 1 | de To store data permanently | | ® To handle large amount of data | | To share data between programs | To log events / information | ce 2. READING FROM A FILE © Common methods : Method Description Reads specified number of characters. If size omitted, reads entire file. Reads a line from the file. read (size) readline (size) Mets Besevipeion veadlines() | Reads all. lines and returns ta Read. (default). File must exist. as a list. w | Write. Creates new file or trencates exist eau a Append. Adds data at the end of file. Create. Fails if file already exists. Binary mode. Text mode (default). +]rlo|x Read and write. 3. WRITING To A FILE © Common methods : Method Description write (string) Writes string to the file. voritelines (list) | Writes a list of strings to file. Example : f = fi write ("Hello Python!\n”) f.write("File handling is easy.”) f.close() # close file open ( “sample. txt”, "w") i open in write mode 6. WITH STATEMENT (RECOMMENDED) © Automatically closes the file. © Better way to handle files. Example : with open(“sample.txt”, "r") as f: data = f.read() print (data) # file closed automatically © SUMMARY) 7. Use open() to open a file with proper mode. a Use read(), readline(), readlines() fo read data. % Use write(), writelines() to write date. Use ‘a! mode to append data % Always close the file or use with statement. * f = open( “sample. txt”, "r”) data = f.read() print (data) f. close () # open file # read entire file # display content # close file 4. APPENDING TO A FILE * Uses ‘a’ mode to add data at the end. Example : f = open(“sample.txt”, "2”) # open in append mode f write ("\nThis line is appended.” ) f. close () # close fi 5. CLOSING A FILE « close() method is used to close the file. © It is important to close the file to free resources. Note : Always close the file after completing operations . 4. FILE POINTER © File pointer keeps track of the current position. + Methods : Method Description tell () Returns current position of pointer. seek (offset) Moves pointer to given position seek (0) Moves pointer to start of file. Example : f = open("sample.txt”, "r") print ("Current position :", f. tell ()) f.seek(0) # go to beginning data = f.read(5) # read first 5 chars print (data) f.close() = Topic 5: EXCEPTIONS = An exception is an error that occurs during the execution of a program. & Why Exceptions ? © To handle runtime errors. * To prevent abnormal termination of program. © To maintain normal flow of the program . 1. CommMoN EXCEPTIONS Exception Description em DiVictar eral acoso emmeee ect ce modulo by zero occurs. Raised! ihen a variable Name ace a is not found. Tape eetoe Raised when wrong type of operand is used. Raised when a function Value Error gets correct type but invalid value. TRE oe Raised when index is out of range. KeyError Raised shen a key is not found in dictionary. : | Raised when specified N FileNotFoundError | file is not fond. 2. SYNTAX OF EXCEPTION HANDLING [ try: # code which may raise exception except ExceptionType ! # code to handle exception else: # code if no exception occurs finally : # code which always executes 3. EXAMPLE bry: a = int(input(“Enter a number: ")) b=10/a print (Result: ", b) except ZeroDivisionError: print (“Cannot divide by zero!") except ValueError: print (“Invalid input! Please enter a number.) else: Output (if user enters 0) Enter a number: 0 ; i print ("Division suecessful.”) Gann: deel. zera! finally : Execution completed print (“Execution completed.”) 4. Flow oF EXCEPTION HANDLING try block (risky code) Exception occurred ? No else block (no exception) finally block (always executes) 5. RAISING EXCEPTIONS + We can raise an exception manually using the raise keyword. © Useful to stop the program when a specific condition oceurs. Example : age = int (input ("Enter your age:”)) if age < 18: raise ValueError (“Age must be 18 or above!”) print ("Access granted.") Output (if user enters 15): Enter your age: 15 Traceback (most recent call last): File “program.py", line 3, in raise ValueErrer (“Age mast be 18 or above !”) ValueError: Age must be 18 or above! 6. TRY WITH MULTIPLE EXCEPTIONS A Ree ee x = int (input ("Enter a number: ")) y= 10/ x except (ZeroDivisionError, ValueError) as e+ print ("“Error:", e) else = print ("Result:", y) Note : %* Always handle specific exceptions rather than’ using except: (catch all). % Use finally block to release resources like files, connections, etc, = ToPic 7: NUMPY < NumPy (Numerical Python ) is a library used. for working with arrays , matrices and mathematical functions . 1. IMPORTING NuMPY import numpy as np # np is an alias | 2. CREATING ARRAYS Function Description np.array() | Create an array from a. list np.zeros() | Create array of all zeros np. ones () Create array of all ones np.arange() | Create array with range of values. np. linspace() | Create evenly spaced values. Fast and efficient | | 1 ! | dimensional. “arrays | | i % Supports large multi- * Many mathematical functions & Used in data science, ML, etc 4. INDEXING AND SLICING + Indexing (Accessing elements) arr = np.array([10, 20, 30, 40, 50]) print (arr [0] ) # 10 print (arr [2]) # 30 print (arr (-1]) # 50 (last element) * Slicing print(arr [1:4]) # [20 30 40] print(arr [:3]) # [10 20 30] print (arr [::2]) # [40 30 50] 2D Array Indexing a = np.orray ([[4, 2,3], Examples : (4,5, 61, (78,971), a = np.array([1,2,3,4]) # 1D array print(af0, 10) 09 b = np.zeres((2, 3)) # 2x3 array of zeros vale) eae c = np.ones((3, 2)) # 3x2 array of ones print(al:, 2]) # [3 6 9] d = np.arange(Q, 10, 2) # [0,2,4,6,8] = np. li 05 P05" # (0.,0.25,0.5,0.75,1. eo Sspalissrare OH 2) ig J} 5. Basrc OPERATIONS 3. ARRAY PROPERTIES Operation Example Attribute Description Addition Oey dim Number of dimensions Suirapon cm shape Size of array (rows, cols, ...) Mate 252 size Total number of elements Dino at Element wi i dtype Data type of elements ete Applied. element by element itemsize Size (in bytes) of each element a, overle'g a = np. array ([1,2, 3]) po-tnn== 5 a = np.array ([[1,2, 3],[4,5,6]]) b = np. array ([4,5, 6]) | tH is wsed | print(a.ndim) #2 prit(a +b) # [579] tee | print (a. shape ) # (2,3) nla SE) aie ‘(square in | print (a. size) #6 > | this case). | print (a. dtype) # inté4 print(a *# 2) # [14 9) \-=----- - print(a.itemsize) # 8 (bytes) 6. COMMON FUNCTIONS 7. ARRAY SHAPES VISUAL i tl Example nincti eed as 1D Array 2D Array 3D Array Ap slin( ar) Starter YAU clawcenis I (ap an 2) Manatees ae (5) Hapel2.3) Vans G22) ap. min (arr) Minimum value np.min(a) # 1 ¢ x np. max (arr) Maximum value np.max(a) #5 2)3]4 5 t)2 3] np. mean (arr) Mean (average) np.mean(a) # 3.0 1/2 \s& np. std (arr) Standard deviation | np.std(a) # 1.414... #1516 alleles np. reshape(arr, shape) | Reshape the array np. reshape(a,(3,2)) makes numerical calculations fast, easy and memory efficient . Why Pandas ? Easy data manipulation Handles missing data Powerful data analysis Works well with NumPy Read/urite various file formats = Topic 8: PANDAS < Pandas is a powerful Python library used for data manipulation and analysis. It provides data structures like Series and DataFrame. Mob ob 1. IMPORTING PANDAS 4. SELECTING DATA sepeth pentiaa ies ep veda ox eas Operation Code / Syntax Example Seleet collate |) PUT Agee] Se ee 2. PANDAS DATA STRUCTURES 2 et at £. ae Select multiple Ts DataFrame with © Series : One-dimensional labeled array columns APU Mame se CRIT Vt ‘cola Example : gent bere fee df. loel1] Row with dadeeed s = pd. Series([10, 20, 30], i = é Select rom by | 4p. iloe [1] Row a patilion 4 print (s) a : Sipe af[t:3] a Sees tod * Dataframe : Two-dimensional labeled data structure RESET ibith rook Gnd Goliene Condition af laf(*Age’]>21] | : Example : 5. DATA MANIPULATION data = {*Name":[*Aman", "Neha", “Ravi'], ee ee "Age ":[ 22, 24, 23], Operation Code / Syntax Deseription “City "+ [“Lucknow", “Delhi”, “Kanpur” ]} Add column | df [*Score’] = (40,85, 95] Add new column ap = pt Detalrime (dete) Drop column | df..drop( ‘City’, axis 1) Remove. column print (df ) ; Drop row df.drop(1) fee rented: Ne A Cit eo a he “d Rename column | 4f-rename(columns={"Age": "Years’},| poe column 0 Aman 22 Lucknow inplace = Tree ) 4 Neha 24 Delhi Sort values | #f-sort—values (“Age’, Sort by Age = ascending = False ) 2 ee 2 See Filter rows | df [ef [Score’] > =90] Filter condition 3. BASIC OPERATIONS ON DATAFRAME 6. HANDLING MIssING DATA Operation Code / Syntax Description © Check missing values ae. af..head (a) ee ae df. isnull() # Returns True for missing values ee # Count missing values per column Tail af. tail(a) (defoult 5) af. isnull ( ). sum) Info af. info() Summary of df * Handle missing values Describe | df-deseribe() | Hatisical senmary af deme # Drop rows with ony mising value Shape df. shape (rows, columns) af, fillna (0) # Replace missing with 0 ae afield Catamas df. fillna (df.mean()) # Replace missing with column mean Index df. index Row labels (index) 8. Basic EXAMPLE F. READ / WRITE FiLes import pandas as pd Operation Code / Syntax Description aa ee ae ‘Ravi'), Read CSV | pd.readnesv( “file. csv’) Read CSV file *Seore”:[88, 92, 75]} Read Excel | pd.read_excel( “file. xlsx’ ) Read Excel file a) ee ee Write CSV | df.to-csv("file.csv’, index=False) Save df to CSV print (df Caf [ "Score”] > 80]) Write Excel | df.toexcel(‘file.xlse’, index=False) | Save df to Excel Output : = df df [af [“Score"] > 80] Name _| Pages| score Name | Age | Score | ak index=False: is used to avoid writing row index in file. 0 | Aman | 22 | 38 | _» jo Pandas works very well with NamPy and Matplottib for data ! 1 Neha at 42 H analysis and visualization. * | 2| Roi | 23 | 35 1| Neha | 21 | 92 0 | Aman | 22 | 98 Ye Pandas makes data handling easy, fast and efficient! We