Python Functions, Modules, and Exceptions PDF
Document Details
The University of Manchester, Alliance Manchester Business School
Tags
Summary
This document provides an introduction to functions in Python. It explains the concept of local vs. global variables, and covers function return statements. It also details using functions as arguments to other functions, and functional programming. Examples are given within the text. Finally it introduces modules and exception handling in Python.
Full Transcript
1.1. Functions Motivation Python has a lot of built-in functions but what if we want to define our own functions? Code reuse beneficial especially for large projects → easier to maintain code 1 Functions...
1.1. Functions Motivation Python has a lot of built-in functions but what if we want to define our own functions? Code reuse beneficial especially for large projects → easier to maintain code 1 Functions def function_name(arguments): indented statement block You must define a function first before calling it 2 Functions Functions can have also zero arguments, e.g. or more than one argument (arguments can be of any type), e.g. 3 1.2. Local vs global variables Function arguments and variables created inside a function cannot be referenced outside of the function’s definition var is a local variable var is a local variable test is a global variable 4 Local vs global variables When you define variables inside a function definition, they are local to this function by default (even if the name is the same) There is an assignment to test, so this is a local variable in that block. The test in function, var 6 in function, test 7 variable outside the block is a 4 global variable. 5 A variable (test in this case) can't be both local and global inside of a function. Use the keyword global to tell Python that you want to use a global variable 6 Quiz 1 What is the output of this code? a) 42 17 4 17 1 15 3 4 b) 42 17 17 4 42 15 4 3 c) 42 17 17 4 1 15 3 4 d) 42 17 4 17 42 15 3 4 7 Quiz 1 What is the output of this code? Local: x = 17, y = 4 Global: a = 42 Local: x = 4, y = 17 Local: b = 17, c = 100 Ans: d) 42 17 4 17 Print global variables 42 15 3 4 More on local vs global variables https://www.python- course.eu/python3_global_vs_local_variables.php 8 1.3. return return statement allows your function to return a value (otherwise it returns the special value None) Once a value from a function is returned, the function stops being executed immediately 9 Examples What is the output of this code? 10 1. What is the highest number this 3. What is the output of this code? code will print? a) [1,2,3,4] c) hello a) 1 c) 11 hello b) 10 d) Error b) [1,2,3,4] d) None 2. What is the output of this code? 4. What is the output of this code? a) 4 c) 10 a) [1,2,3,4] c) None b) 6 d)Error [1,2,3,4] b) None d) [1,2,3,4] None Quiz 211 Quiz 2 1. What is the highest number this code will print? Ans: a) 1 Return when i = 0 2. What is the output of this code? Ans: b) 6 res = 0 + 1 + 2 + 3 = 6 12 Quiz 2 3. What is the output of this code? Ans a): [1,2,3,4] Hello 4. What is the output of this code? Ans d): [1,2,3,4] None 13 1.4. Functions as objects Although created differently from normal variables, functions are like any other kinds of value They can be assigned and re-assigned to variables 14 Functions as objects Functions can also be used as arguments of other functions (Functional Programming) add( add(2,3), add(2,3)) add(5,5) 10 15 1.5. Recursion Recursion: An algorithmic technique where a function, in order to accomplish a task, calls itself with some part of the task. Example: Compute the sum of items in a list What do you notice? No for-loop rec_sum is calling itself Base case Recursive case 16 Recursion Example: Compute the sum of items in a list 17 1. Functions 1.1. Introduction to Function 1.2. Local vs global variables 1.3. return 1.4. Function as objects 1.5. Recursion 2. Modules 3. Exceptions 18 Modules Module: Pieces of code (.py files consisting of functions and values) that someone else has written to do a common task, e.g. mathematical operations https://github.com/python/cpython/blob/3.12/Lib/random.py How to use a module? Add import module_name at the top of your code Use module_name.var to access functions and values with the name var in the module 19 Modules A second way of using modules in case you need certain functions from a module only: Add “from module_name import var” at the top of your code Use var as if it has been defined in your code Use comma separated list to import multiple objects * (e.g. from math import*)imports all objects from a module → Generally discouraged due to confusion of variables. 20 Modules Import modules or objects under a different name using the as keyword Useful if a module or object has a long or confusing name 21 Quiz 3 Question: What is the output of this code? a) 4 b) 16 c) An error occurs 22 Quiz 3 Question: What is the output of this code? Ans: c) An error occurs 23 Three main types of modules in Python 1. Those that are preinstalled with Python: Considered so far. Overview of built-in modules (e.g. math) in the extensive Python Standard Library https://docs.python.org/3.12/library/index.html 2. Those you write yourself: Create a new.py file (consisting of functions and values) with the module name, and then import it using the Python file name (without the.py extension) using the import command. 3. Those you install from external sources: Use third-party Python modules https://www.w3schools.com/python/python_pip.asp 24 Example 25 Examples 1. Write a program that creates a list with n items (n being user-defined), where each item is a random integer between 0 and 10. Use the function randint(a,b)from the random module to generate a random integer between a and b inclusive. 26 Examples 2. Convert this code such that we have a function called random_list to generate a list with n items. The input to the function is n and the output returned by the function is the generated list. Make a call to the function using n = 5. 27 1. Functions 1.1. Introduction to Function 1.2. Local vs global variables 1.3. return 1.4. Function as objects 1.5. Recursion 2. Modules 3. Exceptions 28 Exceptions: Introduction Exceptions occur when something goes wrong due to incorrect code or input Without exception-handling, your program will terminate immediately in case of an exception 29 Exceptions: Types Different exceptions are raised for different reasons Common exceptions include ZeroDivisionError: division by zero ImportError: an import fails IndexError: indexing out-of-range item in a list NameError: unknown variable is used SyntaxError: code cannot be parsed properly (e.g. no “:” after if) TypeError: operation or function is applied to an object of inappropriate type ValueError: an operation or function receives an argument that has the right type but an inappropriate value 30 Example NameError SyntaxError NameError TypeError ValueError IndexError SyntaxErrorr 31 Exception handling To handle exceptions use try and except statements try statement contains code that may throw an exception, except statement defines what to do if a particular exception is thrown try statement can have more than one except clause. At most one except clause will be executed. Use a single except clause with parentheses to capture multiple exceptions at once 32 Exception handling except statement without any exception specified will catch all errors 33 Exception handling Use a finally statement to ensure some code runs regardless if an error occurs or not, and what type the error is 34 Quiz 4 Which number is not printed by this code? a) 3 b) 4 c) 2 d) 2 and 4 35 Quiz 4 Which number is not printed by this code? Ans: c) 2 is not printed out 36 Example Write a program that prompts the user to provide any float number x and then computes and prints out the inverse 1/x. Use exception handling to make sure the program prints out a suitable message if x is not a number or 1/x not possible to compute (i.e. if x = 0). In any case, ensure that the program prints out ”There may or may not have been an exception” after computing the inverse. value” 37 11/1/24, 10:20 PM Review Test Submission: Self-check: Functions, modules and... BMAN73701 Programming in Python for Business Analytics 2024-25 1st Semester Course Content Week 2, Lecture 1 (Xian Yang) - Functions, modules and exceptions in Python Review Test Submission: Self-check: Functions, modules and exceptions Review Test Submission: Self-check: Functions, modules and exceptions User Melissa Hidayat Course BMAN73701 Programming in Python for Business Analytics 2024-25 1st Semester Test Self-check: Functions, modules and exceptions Started 01/11/24 22:17 Submitted 01/11/24 22:20 Status Completed Attempt Score 40 out of 40 points Time Elapsed 2 minutes Self-Test Student answers and score are not visible to the instructor. Results All Answers, Submitted Answers, Correct Answers Displayed Question 1 10 out of 10 points Select the correct answer from below Selected Answer: Modules refer to a file containing Python statement and definitions. Answers: Modules are identical to functions. Modules refer to a file containing Python statement and definitions. Modules are files saved as.txt. Modules are imported using the command load module_name. Question 2 10 out of 10 points What is the output of the code below? https://online.manchester.ac.uk/webapps/assessment/review/review.jsp?attempt_id=_24171428_1&course_id=_83513_1&content_id=_16225320… 1/3 11/1/24, 10:20 PM Review Test Submission: Self-check: Functions, modules and... 3. 4 is maximum Selected Answer: 1. 3 Answers: 2. 4 3. 4 is maximum 4. None of the mentioned Question 3 10 out of 10 points What is the output of the following programme? def mean(a,b): print(a,b) print(c,d) return (a+b)/2 c = 3 d = 5 print(mean(c,d)) Selected 35 Answers: 35 4.0 Answers: Error message because variables c and d are not visible to the function mean() 35 35 4.0 53 53 4.0 https://online.manchester.ac.uk/webapps/assessment/review/review.jsp?attempt_id=_24171428_1&course_id=_83513_1&content_id=_16225320… 2/3 11/1/24, 10:20 PM Review Test Submission: Self-check: Functions, modules and... 35 53 4.0 Question 4 10 out of 10 points What is the output of the following programme? def foo(): try: print(1) finally: print(2) foo() Selected Answers: 1 2 Answers: 1 2 1 2 none of the mentioned Friday, 1 November 2024 22:20:18 o'clock GMT ← OK https://online.manchester.ac.uk/webapps/assessment/review/review.jsp?attempt_id=_24171428_1&course_id=_83513_1&content_id=_16225320… 3/3