0% found this document useful (0 votes)
40 views19 pages

Python Sec C

Chapter 6 focuses on functions in Python, covering their definition, calling, and the concepts of local and global variables, recursion, and iteration. It explains how to create reusable code blocks, pass parameters, return values, and the differences between iterative and recursive approaches. The chapter also discusses best practices for using functions and includes examples of recursive functions like calculating factorials and Fibonacci sequences.

Uploaded by

12gurkaran
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)
40 views19 pages

Python Sec C

Chapter 6 focuses on functions in Python, covering their definition, calling, and the concepts of local and global variables, recursion, and iteration. It explains how to create reusable code blocks, pass parameters, return values, and the differences between iterative and recursive approaches. The chapter also discusses best practices for using functions and includes examples of recursive functions like calculating factorials and Fibonacci sequences.

Uploaded by

12gurkaran
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
| CHAPTER 6 FUNCTIONS _« Defining and Calling Function ie Passing and Returning Value + Local and Global Variables + Recursive Functions + Iteration vs. Recursion In the realm of Programming, functions are fundamental buildi sulate specific tasks, making code modular, reusable, ling blocks that encap- and easier to understand. This | chapter will delve into the intricacies of defining and calling functions in Python, ex- ' ploring concepts such as parameter passing, return and iteration. values, variable Scope, recursion, Defining and Calling Functions tions are reusable blocks of code designed to perform specific tasks. They help ze your code, improve readability, and promote reusability. In Python, functions defined using the def keyword and called by their name. 119 120 CHAPTER 6. yy, ; yt pePINING AND CALLING FUNCTIONS Functions can take parameters as input to make them more dynamic. Py, They can also return values to the caller using the return statement, Pyzy,, 1g) built-in functions (like print() and len()) as well a8 user-defined function, “En, use of functions eilhances modular programming and debugsing eficieney, ” Py, rn statement etum value: Optional I the function returns a vale, use the revue Tt + Wr specify it. Ifo value is returned, Python defaults to returning, ‘No 12 Calling Functions 6 7 spas funtion, You simply wit ite name followed by parenthess containing any arguments. ef 8 Greets the user with a personalized message a i ‘Hello, ' ame ye Functions Poot ("Avzal’) ic 7 yutput Figure 6.1: Python Function Types alo» Ayr! Code 6.2: Example of function 6.1.1 Defining Functions To define a function, you use the following syntax: ——__| 41.3 Parameters and Arguments 1 def function_name( parameters): . """Docstring: A brief description of the function" + Parameters: Variables defined within the function's parentheses. They act as 2 # Function body (code to be executed) placeholders for the values that will be passed to the function when it’s called. «return value # Optional: Returns @ value + Arguments: ‘The actual values that you pass to the function when you call it. Code 6.1: Syntax to define function — ‘They correspond to the parameters defined in the function's definition. sdef add(x, y): + fanctionName: The name you choose for the function. It should be desriti|, '** Adds two numbers and returns the sum and follow Python’s naming conventions. > result =x+y Pann . «print (result) Sars eae ee the function can accept. You can #4455)" 4 he argumente 8 and 5 are passed to the function multiple parameters separated by commas. | ii + docstring : A triple-quoted string that provides a brief description of the fusti#} + Output : It’s optional but highly recommended for documentation purposes. oe sbcssasesesessenssesoreseeee + function body: The code that the function will execute when it’s call | Code 6.3: Example of Parameters and Arg contains the logic to perform the desired operation. 122 CHAPTER 6, 123 Moy Default Arguments 4 ‘You can assign default values to parameters in a function definition, Dred whe he fanny cel the def le wl be vg” 1 def greet (name, greeting=" Hello"): SY 2 "Greets the user with a personalized message .,. 2 Print (greeting + ', ' + name + '!*) *« Breet ("Gursean") * Breet('Charlie', "Hi") + Outpat: * Hello, Gursean! pBFINING AND CALLING FUNCTIONS 6s variables 5 ‘Defined within function: Local variables are declared inside a function 8 ae es, |. scope: Theit scope is limited to the function where they are declared. uifetime: They exist only while the function is executing. 4, Cannot be accessed outside: You cannot directly access local variables f satsde the fonction, ‘rint ("Inside the function:*, x) > function () Code 6.4; Example of Default Argumente Berton # This would raise a NameError: name ’x’ is not |" “gefined 64-4 Returning Values | ——— ae ‘output: : Functions can return values using the return statement, ‘This allows you yy, + inside_the function: 10 iy ‘sult of the function in other parts of your code. — Code 6.6: Example of Local variables + def calculate_area(length, width): ot > "'"Calculates the area of a rectangle. . return length « width é + Defined outside any function: Global variables are declared outside of any funo- «area = calculate_area(4, 5) a tion, * print(‘Area:", area) 2 They can be thou snywharetn the + Lifetime: They exist throughout the entire program's execution. + Can be modified from anywhere: You can change the value of a globel variable Global Variables a Code 6.5: Example of Returning value from function from any part of your code. ry = 20 6X5 Local and Global Variables +def another_function(): : print(‘Inside another function:", y) different scopes, which determine their visbily# « another function () ; - There are two main types of variables: ‘print(*Outside the funetion:', y) CHAPTER 6, py erg 7 Output * Inside another function + Outside the function: 20 aeeae Code 6.7. Example of Global variables : 20 6.1.6 Modifying Global Variables from Within a Pung... To modify a global variable from within a function, you need to use the glob: This explicitly indicates that you're referring to the global variable, not salar with the same name. 12 = 30 2 def modify_global(): 2 global z «2 =40 « modify_global () « print (‘Modified global variable 2) + Output: * Modified global variable: 40 Code 6.8: Example of Modifying Global variable in fuction \ Best Practices + Use local variables whenever possible: This helps to keep your code organi! and avoid unintended side effects. © Use global variables sparingly: Overusing global variables can make your co harder to understand and maintain. aa 125 ApouRSIVE FUNCTIONS 6h ; /fecursive Functions 6. ‘They are i indirectly. sssi¥? directly Or an into smallet> ful en down 1 swe ion is often used in tasks like caleulating factorials, generating Fibonscct 9° ial to stop the re cutee be less efficient ue Rata wna prevent inne a iterative ones, but they simplify complex problems. sg foursve unetons Woe _ Psecae: A scusive function must hve base cae that stops the reeurion ‘phis is usually a condition that retums a value without making further recursive calls. , and solving tree traversal problems. A base case is exsenti ive solutions can sometimes ve case: The recursive case calls the function itself with a smaller input, self with a smaller inpu ‘working towards the base case. | example: Factorial Function practosiel unctoas ‘The factorial of a non-negative integer n is the product of all positive integers less than. or equal ton. We can calculate the factorial using recursion. 3 Aa4x3x2xl=Ae Blab x4x3x2x1=120 Gl a6x5x4x3x2K1= 720 + Be cautious when modifying global variables: If you need to modify a global ™* able from within a function, use the global keyword explicitly to avoid consequences. yo “ pEcURSIVE FUNCTION . sci (n): 12 + def factorial(n) Peror + if m= 0: # Base case (rE me cane _ * : return 1 ae + else: # Recursive case sen Recurive ean return fibonacei(y — 1) + fibonacci(n — 2 . return n + factorial(n ~ 1) * result = factorial (5) 7 Print (result) + Output: 1 120 Code 6.9: Example of Recursive function Explanation + Ifnis 0, the function returns 1 (base case). + If nis greater than 0, the function calculates n multiplied by the 1 (recursive case). Example: Fibonacci Sequence The Fibonacci soquence is series of numbers where each number isthe sum o {wo preceding ones, starting from 0 and 1. We can calculate the Fibonacci see, using recursion. foctria i, 1,1,2,3,5,8, 13, 21, 34, 55, 89, 144, 233, 377... 1+1=2 13+21=34 142=3 21434=55 24+3=5 34455 =89 34+5=8 55489 = 144 54+8=13 894144 = 233 8+13=21 1444233 = 377 It ve(result) ee — Code 6.10: Example of Recursive z fibonacci (6) seplanation: «ifn is 0 or 1, the function returns n (base cass). «fm is greater than 1, the function calculates the sum of the Fibonacci mubers for n- Land n- 2 (recursive case), ‘This process continues recursively until the base cases are Ky Pints: + Recursive functions can be elegant and concise for certain problems. + Be careful to avoid infinite recursion, which can lad to stack oreiow enor + For some problems, iterative solutions might be more efficient. + Tail recursion optimization can be used in some programming languages to im Prove performance, Whefi to Use Recursive Functions: + Problems that can be naturally divided into smaller, similar subproblems - * Problems involving tree-like structures (¢.g., tree ‘traversals). 4 CHAPTE: 12g R 6, "ey, yressed in terms of the ss + Problems where the solution can be exPE Solution ty instances of the problem. 6.2.1 Iteration vs. Recursion Iteration and recursion are two common programming techniques used to ey tions, While they serve a similar purpose, they have distinct approaches ang i Key Differences Control flow: Iteration uses loops to control the repetition, while Tettia function calls. + Stack usage: Recursive functions can lead to deeper call stacks, which ey tentially cause stack overflows for large input sizes. Uy + Readability: Iteration is often more intuitive and easier to understand forty ners. + Performance: The performance of iteration vs. recursion can vary dee on the specific problem and implementation. Tail-call optimization can i mitigate stack overflow issues in some cases. Choosing the Right Approach + Iteration : Generally preferred for simple, iterative tasks or when performann critical and stack overflow is a concern. + Recursion: Can be elegant and concise for problems that can be naturally div into smaller, similar subproblems , such as tree traversals or divide-and-oome| algorithms. Following code provides a more structured and modular approech to managing tui) information, using functions to encapsulate specific tasks and if-else conditions tom decisions based on the calculated average marks. SPasedon the calculated average marks, student (students): 2 mame = input (‘Enter student name: *) 3 marks = [] ‘ num_courses = int (input (*Enter amber of courses: *)) pBCURSIVE FUNCTIONS 129 i im range (num _courses) mark = float (input (f* Ente, ee marks for course {141}: *)) students append (name, marks)) jisplay—students (students) for student in students print (f*Name: (student (0)} +) for i, mark in enumerate (student print(f* Course {i}: tun} » qaloulate_average (marks): return sum(marks) / len (marks) theck pass_fail(avg_marks) if ave_marks >= 60: return "Passed for else! return ‘Failed* main() = students = [] while True: print ("\nStudent Management System") print (‘1. Add Student") print (‘2. Display Students") print(‘3. Calculate Average Marks and Pass/Fail Status") print("4. Exit") choice = int(input(*Enter your choice: *)) if choice = 1: add_student (students) elif choice = 2: display_students(students) elif choice student_name = ) for student in students: ‘t[0] — student_name f otudent (] = areulate_ average student 1}) xs for {student_name}:{ input("Enter student name to calu average avg_marks print (f*Avg math 130 re marts:.2)°) a cgepane/ Pall Statue: avg_marks)}") 2) rea jot found.") els print ("Student ® “ elif choice = 4: « break else: ; print(*Invalid choice x: Output: s2 Student Management System ws 1. Add Student u 2. Display Students s 3. Calculate Average Marks and Pass/Fail Status w 4. Exit s Enter your choice: 1 Enter student name: Ayzal w Enter number of courses: 3 Enter marks for course 1: 80 « Enter marks for course 2: 90 « Enter marks for course 3: 70 « Student Management System a1. Add Student «© 2. Display Students «3. Calculate Average Marks and Pass/Fail Status or 4. Exit « Enter your choice: 2 Name: Ayzal Course 1: 80.0 Course 2: 90.0 m Course 3: 70.0 rs Student Management System 0 n Please try again.') if name = *_msin_'? «© main() mm RECURSIVE FUNCTIONS BL tudent Calculate Average Macks and Pass/Fail Status 4, Bxit yer your choice: 3 Ayzal Kerage marks for Ayzal: 80.00 pase/ Foil, Status: Passed fodent Management System 1. Add Student 9, Display Students 5, Calculate Average Marks and Pass/Fail Status 4. Exit pater your choice: 4 ee Code 6.11: Detailed Example of "functions" + Functions 1, add _student: Adds a new student to the students list, taking input for name and marks, 2. display_students: Prints the details of all students in the list. 3. caleulate_average: Calculates the average of a list of marks. 4. check _pass_fail: Determines the pass/fail status based on the average marks + Main Function: 1. Initializes an empty students list. 2. Displays a menu with options. 3. Based on the user's choice, calls the appropriate function: 4. add_student: Adds a new student. 5. display_students: Displays student information. Ty vYMOUS FUNCT: 132 CHAPTER 6. Puy _, ANON ONS (LAMBDA py Cry) lambda WNCTIONS) : ats about lambda Functions, 133 6. calculate_average and check pass fail: Calculates the average rang | sf aa a determines the pass/fail status for & specific student. y concise: Lambda functions provide ; + OM in8 YOUT COME Shorter and mone Me + IfBlse and Loops: » a an ression: 1. The if-else conditions are used to control the flow of the program eg single an only contain a single ‘user input and calculated values. | 7 . eed with Higher-Order Function: Open 2. The for lop iterates over the students it to process each studewy, | + Opie, and ‘teu, enabling mation. 7 siques- : nited Functionality: Best suited for 6.3 Anonymous Functions (Lambda Functions) . amended fae mpage apn soso ops, init ‘Anonymous functions, or lambda functions, are small, unnamed functions in defined using the lambda keyword. ‘They are often used for simple operating don't require a fullfedged function definition. Lambda functions are common in situations where a short, throwaway function is needed, such as in map), a or sorted() operations. . — : lambda arguments: expression Code 6.12: Syntax of lambda function + lambda: Keyword to define an anonymous function, often used for simple, ha functions without a name. + arguments: One or more arguments, separated by commas, that the function accept as input. These are similar to parameters in regular functions. «+ expression: A single expression that is evaluated and returned, which can bea __valid expression in Python, such as arithmetic operations or logical compar \ 1#A lambda function to square a number \ a square = lambda x: xee2 2 # Using the lambda function Presult = square(5) pring(result) # Output: 25 \ Code 6. Example of lambda function oon 11. 12. 13. 14. 15. . What keyword is used to define a function in Python? . Explain the structure of a function in Python. / . What is the role of parameters in a function, and how are they different What is the purpose of using functions in Python programming? from arguments? . What is the difference between a function’s parameters and arguments? Explain with an example? . What is a default argument in a function, and how is it used in Python? Provide an example. . . How do you return a value from a function in Python? Give an example. . What is the difference between local and global variables in Python? . How can you modify a global variable from within a function in Python? 10. What are the best practices for using local and global variables in Python functions? eae ag get ae What is a recursive function? Explain with an example. How does recursion work in Python, and what are the two main compo- nents of a recursive function? fue Write the Python code for calculating the factorial of a number using recursion. Dae How does the Fibonacci sequence relate to recursion? Write the Python code to generate the Fibonacci sequence recursively, What are the key differences between iteration and recursion, and when should each be used? CHAPTER 7 I ODULES IN PYTHON oo Pe a ee ME] « Purpose and Usage ¢ The Import Statement + Creating and Importing Modules + Standard Library Modules In the dynamic realm of Python programming, modules serve as the building blocks for organizing and reusing code. They encapsulate functions, classes, and variables, making your code more modular, efficient, and maintainable. By using modules, you can avoid redundancy and enhance collaboration in larger projects. 7.1 What is a Module? code that you can include in other Python programs. A module is a file with Python cam ont functions, veils, and lame thas OS® cular task. Modules are great because they let you organize your code hoppereie files and reuse it in multiple programs. For example, Python has builtin modules for working with math, dates, file handling, and more. 135 ULi ete a Netra eee Prt, WHAT ISA MODULE? a Why Use Modules? 137 e-Feusability : Modules can be imported and used in different script, code duplication. Organization: Breaking down large programs into smaller, modular oom, “ ee improves code readability and maintainability € porting «2Kamespace Management: Modules create separate namespaces, Prev | s5839008® re a from the module, but can ka ve A conflicts between different parts of your code. se generally St ” le_name import « Andard Library: Python comes with a rich standard brary of modu. jrom_moduletane imports Code 7.5: imports all elements of module namespace pollution, so Provide various functionalities suchas ie 1/0, network programming, aj 7.1.1 The import Statement 11.2 VGreating Your Own M The import statement is used to import modules into your Python script. Thess, co seme = yon scrip + Create a New mn File: Create a new Python file with a .py extension. several ways to import modules: New Prthon Fi new Python fle with a py extension. + Define Functions, Classes, and Variables: Write your desired functions, classes, a. Simple Import and variables in the fle. : import module_name | + Import the Module: In another Python script, use the import statement to Code 7.1: Syntax to import module import Your module. : je Example a ‘This imports the entire module. ‘To access its elements, use the dot notation: Fie*&me: [Link] » module_name. function_name() —_—_— 2 module_name. variable_name sdef greet (name) ope 7 ——————_+— ed Ssérrint "Hello, " + name + °F Code 7.2: access its elements module sdef add(x, y): ‘ Teturn’x + y Import Specific Elements using ‘from’ statement. { Code 7.6: Defining Own Module 2, This imports specific elements from the module. You can then use them directly + from module_name import elementi, elementd File Name: [Link] - a < ‘Syntax ‘Import: modulel Code 7.3; import Specific ule! a * Elements *modulel. greet (* Ayzal') YAfenaming Imported Elements: *Tesult = [Link](5, 3) , i “YW * Print (result) * Output: 7 Hello, Ayzal! +8 — Code 7.7: Import Own Module in Program LS The _-main__ Attribute in Python In Python, the __main__ attribute is a special variable that indicates the execution cont@xt ofa Python seip, It's primarily used to distinguish betwee a script directly and importing it as a module. ny sdef greet(mme): SSS 2 print(‘Hello, * + name + oif __name_ x «name = input(* a s greet (name) > Output: s Enter your name: Gurshabad » Hello, Gurshabad! Code 7.8: ‘main’ Attribute in Python In this example: Le The greet function ia defined, which can be used both within the script and ¥#| the script is imported as a module. ee + The if __name_ main__': block ensures that the greet function s a only when the script is run directly, not when it’s imported. ie 7 dard Lil phy SO PTary Mocueg 139 pn Hc Mbrary that int ao wes mortules for jp anaths Mathematical function random: Random number sentation 4 os: Operating system interactions dotetime: Date and time manipulation si 598: System-specific parameters and functions —_ gp se # standard library module, Spy impor ip jmport math oo result = math. sqrt (16) | print (result) Code 7.9: Import standard library module By effectively using modules, you can write well-organized, reusable, and maintainable Python code, 7.144-The dir() Function and Python Modules In Python, the dir() function is a built-in function that returns alist tid sstbates and methods ofan object. When applied to a module, it provides a comprehensi ofnames defined within that module. ‘import math * print (dir (math) ) «Output: : Mo, ol —H_*, *_toader__*, ap + ‘acos’, *acosh?, ‘asin’ ao fata i atanh’, ‘cbrt*, ‘ceil’, ‘comb’, ‘copysigm’s ‘cos’, oc, ‘degrees’, ‘dist’, 'e’, ‘erf’, ‘erfe’s "exp, Vexpa> | expml’, fabs', ‘factorial’, ‘floor’, ‘fmod’, ‘frexps foum’,"‘gmma’! ‘ged’, *hypot?, ‘inf?, ‘isclose', vigt *, Tisinf’, ‘isnan’, ’isqrt’, ‘lem’, "Idexp’, "Ilgammas “ite log’, ‘log10’, *logip’, ‘log2’, ‘modf’, "nan’, 'nextagt ‘perm’, *pi’, ‘pow’, ‘prod’, ‘radians’, ’remainder? ,°"’, » ‘sinh’, ‘sqrt’, ‘sumprod’, "tan’, ‘tanh’, "tau, 94, Ue” isk] a 7a Code 7.10: dir() function Tips for Creating and Using Modules + Organize logically: Group related functions and variables together in a 1, ee + Use comments: Explain each function and its purpose to make the modula, to understand. + Avoid conflicts: When naming functions and variables, try to avoid names ty might conflict with Python's built-in functions. «+ init__.py File: This file is essential for Python to recognize the directory as a package. It can be empty or contain initialization code. Importing Packages You can import modules from a package using the dot notation: vimport my package. modulel Code 7.11: Syntax to import Package 7.2 Packages In Python, @ package is a collection of modules organized in a hierarchical dit structure. It provides a way to group related modules together, making your os ‘more modular, organized, and reusable. Packages can also include sub-packages xi additional resources like data files or configurations. To create a package, you needy include an__init__ py file in the directory, which can be empty or contain initialization. code for the package. Structure of a Package: A package typically consists of the following: r, you can import specific attributes from the module: :ftom my_package.modulel import function_1 Code 7.12: Syntax to import specific Package me, variable_name Benefits of Using Packages: * Organization: Packages help you organize your code into logical units, makix ky, it easier to manage and understand THE etruCtuTe SAND yyy, in pxcwkaces maintenance in large projects ‘liog fe — “A agate 9): 3 in different project te, Tita of Soeur x+y redundancy and accelerates deve i jubtract (x, y): nodular design, allowing you to break aot Fyeurmn x — + Modularity: Packages promote » ere pendent components. MOdUIRE syste, "toy | Caden 8 ax Code 7.18) ean re 7.13: Module plex systems into smaller, ‘ ple goometty PY: to debug, test, and extend Packages help avoid naming conflicts ‘ jos space, ensuring clear expan ¥ jrea_of_circle (radius), —— oy d°F Poeun 3.14159 + radiue « rag; * radios Standard Library: Python's extensive standard library provides ‘These built-in packages save time and id ¢ perimeter_of_rectangle(| or iy aof Plgurn 2 * (length + eae width) packages for various tasks: ing ready-to-use solutions. Code 7.14: Module geometry -euse code from packages + Reusability: You can Jopment time: + Namespace Management: ules. Each package creates its own names Example: A Simple Package Let's create a simple package named my_math with two modules: acim sng the Packages geometry (Figure?.2): joport my_math. arithmetic as arith import MY. math. geometry as geo pesultl = arith add(5, 3) Meult2 = ge0-area_of_circle(5) wint(result1) # Output: 8 result2) # Output: 78.5975 Code 7.15: Module geometry print ( pyeffctively using package, you can write well-structured reusable, and maintains Python code. | “Feature __[ Module Package Dainition | A single Python file con- callection of modules organized in taining code directory structure ; | “Purpose To organize code into "To group related modules and provid | sraller reusable units | 8 hierarchical structure ‘import package name module name . te ; ' ct Figure 7.2: Example of Simple package Directory structure Tat inp anak ne | pO SS A Module [Link]: Bw nw . What is a module in Python, and why are they useful? . List and explain the four different ways to import modules in Python. - What does the ’from’ import statement do in Python? Provide an example, . Why is it generally discouraged to import all elements from a module using . What is the purpose of the __main__ attribute in Python, and how is it . Explain the role of the if _name__ == '__main__': block in a Python . What are some of the commonly used standard library modules in Python? . Mention some best practices for creating and using Python modules? the ‘import *’ syntax? How do you create your own Python module, and how can you import it into another script? used? script. Provide examples of their usage. How does the dir() function help when working with Python modules? Give an example using the math module. Pcp HANDLING + Understanding Exceptions ¢ Try-Except + The 'with" Statement + Catching All Exceptions ¢ Error and Debugging + Debugging Techniques Exors are a part of programming! In Python, there are several tools to handle errors gracefully, making your code robust and easy to troubleshoot. In this post, we'll cover the basics of try-except for error handling and common debugging techniques. We’ll also explore scenarios where errors occur and anticipate them in your ‘de. Examples and practical tips will help you write error-resistant Python programs. 81 (Understanding Errors in Python Errors in Python are called exceptions. Common exceptions include (Figure 8. 1): 145 CHAPTER 8 EXCEPTION Hay, Ny (oatingPoiterro) (xpceptioncrou) Figure 8.1: Common exceptions in Python 9 ZeroDivisionError : Dividing by zero, which is mathematically undefined ay halts execution, + ValueError : Using the wrong type of value, such as passing a string to a functia| expecting a number. ecting a number + FileNotFoundError : Attempting to open a file that doesn’t exist, often duete incorrect file paths. + TypeError : Trying to use an operation on the wrong type (e.g, adding a st trig to a number), which is not supported. + NameError : Raised when a variable or function name is not found, tpi due to typos or undefined variables. + IndexError : Raised when a sequence gubscript is out of range, such 9s #54) an invalid index in a list or tuple. = w) __ + KeyError : Raised when a dictionary key is not found, typically caused") ~»eessing a non-existent key. NN ~ When an cerr0F Occurs, it stops your ; lows you €0 Use TY-EXCEDE Blocks to “cated Som runnin Fol Hos to ‘This tothe user instead of abruptly washing 8.2 Try-Except Blocks ‘The try-except block is the fundamental construct for It works as follows: y, TRY-EXCEPT BLOCKS + 10Brror + Raised when an 1/0 : oo ation (i fae to potmission oF hardware isgigg i file reading or arn i crim rho "OF writing) fail, often « Import Bros: Raised ven an npr ey aes import path atement fails, Usually due to a miseis a missing + Syataxrror : Raised when the parser ters tor, often invalid Python code structure, == oa python code struc 6 To prevent this, Python ‘hese errors and handle them or and handle them gracefully ‘continue ‘exception handling in Python. ‘exception is placed inside the try + Try Block: The code that might raise an block. This allows the program to attempt iisky operati crashing YY operations without immediately. a + Except Block: If an exception occurs within the try block, the control is trans- ferred to the except block, You can handle the exception there, log it, or display an error message to OOS ) ")) numl = int(input(*Enter the first number num? = int(input('Enter the second number result = numl / num? Print(*Result:", result) ‘xcept. ZeroDivisionError: Print (*Error: Division by zero") “cept: ValueBrror : Print (Error: Invalid input’) eee 148 CHAPTER 8. EXCEPTION jy, ND ; USING THE FINALLY Bloc, » Output , fi ee Enter the first number: 34 35 Using the finally Block «Enter the second number: 0 ally block is optional ana ning « Error: Division by zero poe fF : Tegardless of eae yy BETO for cleanup tasks like closing 4 ‘whether an exception occurs. It' Code 81 Example of Try-Except Block ee ere wt . pum = int (input ("Enter a number. 5) In this example: If the user enters a non-numericvalue, a ValueEtror i rig, " result = 10 / mum user enters 0 as the second number, a ZeroDivisionError: is raised print ({"The result is {resut}) xcept ZeroDivisionError: e print ("Error You can't divide by zero!*) 85° The with Statement me , nally? The with statement is often sae fo resus manage especially when print ("Execution completed, with or without an error.") with les. It ensures that resourles are propery elena, even if an exceptongg'|— . a Outeut with open(‘m ) as file: oe number: 0 prror: You can’t divide by zero! execution completed, with or without an error Code 8.4: Example of Finally Block content = [Link]() sprint (content) Code 8.2: Example ‘with’ Statement Example-2 of try-except-clge-finally block def divide(x, y): try: result =x / y print (*Result:", result) except ZeroDivisionErr: print (*Error: Div! 1 else: | print (‘Division successful’) In this example, the with statement automatically closes the file when the block regardless of whether an exception occury 8.4 Catching All Exceptions You can also catch all exceptions with Exception, although it’s generally best to ecific about which errors you want to handle, ion by zet0") s try: 2 Some code that might throw an error \ finally: ekce be ester ceeantel | print ("This block always executes") A print(f"An error occurred: {e}*) # Example usage = tivide(10, 2) Code 8.3: Syntax of catch all exceptions divide (10, 0) CHAPTER 8. 150 = Output: ful, Thi gion successful, This blog ws # Output: Result: 5.0, Divis' " ork alyy executes block . zero, This » # Output: Error: Division by zero, THS © — 3.5: Example of Finally Block Code 26 Errors and debugging Jommon Errors in Python’ f the code, such as miss; + Syntax Exors : Errors in the structure of Ne be or incorrect indentation. These errors aie detected before the code pee and must be corrected to run the program. + Runtime Errors : Errors that occur during program execution, such a Runtime Exrp ee ‘wy zero or accessing an index out of range. These errors Titerrupt the p> Pr ee execution and often require exception handling. + Logical Errors : Errors in the logic of the code, leading to incorrect ems errors do not stop the program but require debugging to identify and fx BT Debugging Techniques + Print Statements: Insert print statements to check the values of varabls different points in the code. ~~ 1 def divide(a, b) Gee eprint (Gas a > return a / b : «result = divide(10, 0) #¢ Th . b) # debugging line will raise an error Code 8.6: Example of debug using Print Statement a 1 pEBUGGING TECHNION ., Python Debugger (pay. ra . inbles, and bab jpspect Variables, and set Jmport pdb —— i — to ~? 82” thouth yon code tne by tine, “get divide(a, b) a _ : pdb. set_trace() return a/b * Pass the Program here * result = divide(io, 9) _ Moasing: Use the logging module to rec | your Program, neu eres nd wring a HOM heaton of i eB. import logging ee logging - basicConfig(levelcioggs jdef divide(a, b); geing DEBUG) 1 logging. debug(f" Dividin return a/b & {a} by {b}*) etry: 1 result = divide(10, 9) sexeept ZeroDivisionError: + ___logging-error(‘Attempted to divide by zero.

You might also like