Summary

This document provides a detailed explanation of functions in Python, including their types, benefits, and how to write and use them within a program.

Full Transcript

FUNCTIONS Instructor: Dr. Sukhjit Singh Sehra A function is a group of statements that exist within a program for the purpose of performing a specific task. Instead of writing a large program as one long sequence of statements, it can be written as several small functions, each one...

FUNCTIONS Instructor: Dr. Sukhjit Singh Sehra A function is a group of statements that exist within a program for the purpose of performing a specific task. Instead of writing a large program as one long sequence of statements, it can be written as several small functions, each one performing a specific part of the task. This is known as the divide and conquer approach. Modularized programs are written with each task in its own function. Benefits of Modularizing a Program with Functions Simpler code: Small functions are easier to read than long sequences of state- ments. Code reuse: You write a function once and reuse it each time you need to perform the task. Better testing: Each function can be individually unit tested. Faster development: Functions can be written once for a common task and be imported into a program that needs them. Easier facilitation of teamwork: Different programmers can write different functions or pieces of the program. Void Functions and Value-Returning Functions Two types of functions: void functions and value-returning functions. Void functions execute statements and terminate, returning no value. Value-returning functions execute statements and return a value back to the statement that called it. Function Names and definitions Function names conform to the same rules as those pertaining to variable names. – No key words – Cannot contain spaces – First character must be a-z, A-Z or an underscore – After the first character, you may use letters, digits, or underscores. – Uppercase and lowercase character are distinct Function Names and definitions Function names should use verbs to describe the action they perform. General format of a function in Python: def function_name(): statement statement 1.... The first line is known as the header. It marks the beginning of a function definition. To execute a function, you must call it i.e., function_name(). Local Variables A local variable is created inside a function and cannot be accessed by state- ments outside the function. A local variable’s scope is the function in which it is created. Scope and Local Variables Scope is the part of the program in which a variable may be accessed. A local variable’s scope is the function in which it is created. Also, a local variable cannot be accessed prior to creation: def bad_function(): print('Hello', name) name = 'Matt' Passing Arguments to Functions An argument is any piece of data that is passed into a function when the function is called. A parameter is a variable that receives an argument passed into a function. A parameter variable’s scope is the function in which the parameter is used. You can pass more than one argument to a function. Python allows you to specify which parameter variable an argument should be passed to using the parameter_name=value format. Here is an example of a function that has a parameter value: def show_double(number): result = number * 2 print(result) Global Variables and Global Constants A global variable is accessible to all functions in a program file. # Used with permission from David Brown x = "Global variable" def func1(): x = "inside func1" print(x) 2 return def func2(): x = "inside func2" print(x) return print(x) func1() print(x) func2() print(x) Global Variables and Global Constants The output of the program is: Global variable inside func1 Global variable inside func2 Global variable It is recommended to create variables locally and pass them as arguments to functions that need them. A global constant is a global name that references a value that cannot be changed. Value-Returning Functions A value-returning function is a function that returns a value back to the part of the program that called it. Python provides a library of prewritten functions that perform commonly needed tasks. To use these functions, you must use the import statement. Writing Your Own Value-Returning Functions A value-returning function has a return statement that returns a value back to the part of the program that called it. def value_returning_function(): statement statement etc return expression Here, expression will be sent back to the variable that is assigned to this function call. 3 Using IPO Charts IPO stands for input, processing, and output, and an IPO Chart describes the input, processing, and output of a function. The following is an IPO chart for this function: def get_regular_price(): price = float(input('Enter the item\'s regular price: ')) return price | **Input** | **Processing** | **Output** | | --------- | ------------------------------------------------- | ------------------------ | | None | Prompts the user to enter an item’s regular price | The item’s regular price | Returning Strings and Boolean Values Functions can be used to return string input from users. def get_name(): return input('Name: ') Boolean functions return True or False. def is_even(number): if (number % 2) == 0: status = True else: status = False return status user_input = int(input('Enter a number: ')) if is_even(user_input): print('Even number') else: print('Odd number') Returning Multiple Values You can return have a function return multiple values with the following for- mat: return expression1, expression2, etc. Here is a function that does so: def get_full_name(): first = input('First name: ') 4 last = input('Last name: ') return first, last first_name, last_name = get_full_name() Storing Functions in Modules A module is a file that contains Python code. Large programs are easier to debug and maintain when they are divided into modules. The process of breaking up programs into individual files, or modules, is called modularization. When creating modules: – Filenames must end in.py – Filenames cannot be Python reserved words (e.g., for) You import your modules using: import Docstring Importance of docstrings in functions and modules in Python: Provides a clear and concise description of the purpose and functionality of the code. Helps other developers understand how to use the code correctly. Serves as a form of self-documentation for future reference. Enables automated tools to generate documentation and help with code anal- ysis. Facilitates collaboration and code maintenance by making it easier to under- stand and modify the code. Docstring """ ------------------------------------------------------- Calculates simple statistics on five numbers. Use: total, average, max_val = stats(no1, no2, no3, no4, no5) ------------------------------------------------------- Parameters: no1, no2, no3, no4, no5 - numbers (float) Returns: total - sum of parameters (float) average - average of parameters (float) max_val - maximum of parameters (float) ------------------------------------------------------- """ 5 References: 1. John Sturtz, A Guide to the Newer Python String Format Techniques. 2. David Brown, Bohr.wlu.ca/cp104/notes 3. Tony Gaddis, Starting Out with Python, 6th Edition 4. MatthewKosloski, https://github.com/MatthewKosloski/starting-out-with- python 6

Use Quizgecko on...
Browser
Browser