Lecture 5 - Functions [Python] PDF

Document Details

RoomierCommonsense

Uploaded by RoomierCommonsense

Ontario Tech University

Samaneh Mazaheri

Tags

Python programming functions programming computer science

Summary

This document is a lecture on functions in Python, for an Introduction to Programming course. It covers topics like defining functions, using functions to divide up tasks, passing arguments to functions and using the math module. It also contains exercises.

Full Transcript

INFR 1101u Introduction to Programming (Python) Lecture 5: Functions Samaneh Mazaheri Email: [email protected] 1 Topics • Introduction to Functions • Defining and Calling a Void Function • Local Variables • Passing Arguments to Functions • Global Variables and Global Constants •...

INFR 1101u Introduction to Programming (Python) Lecture 5: Functions Samaneh Mazaheri Email: [email protected] 1 Topics • Introduction to Functions • Defining and Calling a Void Function • Local Variables • Passing Arguments to Functions • Global Variables and Global Constants • Introduction to Value-Returning Functions • The math Module 2 Introduction to Functions • Function: group of statements within a program that perform a specific task. ▪ Usually, one task of a large program • Functions can be executed to perform overall program task ▪ Known as divide and conquer approach • Modularized program: program wherein each task within the program is in its own function. 3 Using functions to divide and conquer a large task 4 Modularizing a Program with Functions • The benefits of using functions or modularizing a program with functions include: ▪ Simpler code ▪ Code reuse • write the code once and call it multiple times ▪ Better testing and debugging • Can test and debug each function individually ▪ Faster development ▪ Easier facilitation of teamwork • Different team members can write different functions 5 Defining and Calling a Function • Functions are given names. • Function naming rules: • Cannot use key words as a function name • Cannot contain spaces • First character must be a letter or underscore • All other characters must be a letter, number or underscore • Uppercase and lowercase characters are distinct 6 Defining and Calling a Function • Function name should be descriptive of the task carried out by the function. ▪ Often includes a verb Function Header Block • Function header: first line of function – Includes keyword def and function name, followed by parentheses and colon • Block: set of statements that belong together as a group – Example: the statements included in a function 7 Defining and Calling a Function • Function definition/implementation: specifies what function does • Call a function to execute it • When a function is called: ➢Interpreter jumps to the function and executes statements in the block ➢Interpreter jumps back to part of program that called the function ▪Known as function return 8 Void Functions and Value-Returning Functions • A void function:  Simply executes the statements it contains and then terminates. • A value-returning function:  Executes the statements it contains, and then it returns a value back to the statement that called it. • The input, int, and float functions are examples of value-returning functions. 9 Indentation in Python • Each block must be indented ▪ Lines in block must begin with the same number of spaces •Use tabs or spaces to indent lines in a block, but not both as this can confuse the Python interpreter ▪ Blank lines that appear in a block are ignored 10 Exercise A. Write function hello() that: ▪ takes a name (i.e., a string) as input ▪ prints the following personalized welcome message ▪ Note that the function does not return anything hello(‘Sam’) Welcome Sam, to the world of Python! B. Write a Python function called calculate_rectangle_area that calculates the area of a rectangle, getting its length and width as parameters from user. The formula to calculate the area of a rectangle is: 𝐴𝑟𝑒𝑎 = 𝑙𝑒𝑛𝑔𝑡ℎ × 𝑤𝑖𝑑𝑡ℎ 11 Local Variables • Local variable: variable that is assigned a value inside a function. ▪ Belongs to the function in which it was created. • Only statements inside that function can access it, error will occur if another function tries to access the variable. • Scope: the part of a program in which a variable may be accessed. ▪ For local variable: function in which created. • Local variable cannot be accessed by statements inside its function which precede its creation. • Different functions may have local variables with the same name. ▪ Each function does not see the other function’s local variables, so no confusion 12 Passing Arguments to Functions • Argument: piece of data that is sent into a function ▪ Function can use argument in calculations ▪ When calling the function, the argument is placed in parentheses following the function name. The value variable is passed as an argument 13 Passing Multiple Arguments • Python allows writing a function that accepts multiple arguments ▪ Parameter list replaces single parameter • Parameter list items separated by comma • Arguments are passed by position to corresponding parameters ▪ First parameter receives value of first argument, second parameter receives value of second argument, etc. 14 Writing Value-Returning Functions • To write a value-returning function, you write a simple function and add one or more return statements ▪ Format: return expression •The value for expression will be returned to the part of the program that called the function ▪ The expression in the return statement can be a complex expression, such as a sum of two variables or the result of another value-returning function 15 Writing Value-Returning Functions 16 How to Use Value-Returning Functions • Value-returning function can be useful in specific situations ▪ Example: have function prompt user for input and return the user’s input ▪ Simplify mathematical expressions ▪ Complex calculations that need to be repeated throughout the program • Use the returned value ▪ Assign it to a variable or use as an argument in another function 17 Exercise 2 Write a function that returns smallest value of three arguments and provide a program to test it. def smallest(x, y, z) 18 The main Function • When defining and using functions in Python, it is good programming practice to place all statements into functions, and to specify one function as the starting point. • Any legal name can be used for the starting point, but we chose ‘𝑚𝑎𝑖𝑛’ since it is the required function name used by other common languages. • Of course, we must have one statement in the program that calls the main function. • main function: called when the program starts ▪ Calls other functions when they are needed ▪ Defines the mainline logic of the program 19 Volume of a cube - Exercise Write a function that returns volume of a cube (side length will be sent to the function as an argument). Volume of a cube : V = a3 20 Syntax: The main Function 21 Returning Values • Returning Strings: ▪ We can write functions that return strings. • Returning Boolean Values: • Boolean function: returns either True or False ▪ Use to test a condition such as for decision and repetition structures • Common calculations, such as whether a number is even, can be easily repeated by calling a function ▪ Use to simplify complex input validation code 22 Function Comments • Whenever you write a function, you should comment its behavior • Remember, comments are for human readers, not compilers ## Computes the volume of a cube. # @param sideLength the length of a side of the cube # @return the volume of the cube # def cubeVolume(sideLength) : volume = sideLength ** 3 return volume Function comments explain the purpose of the function, the meaning of the parameter variables and the return value, as well as any special requirements 23 Exercise 3 Write a function that returns true, if three arguments are all the same, and provide a program to test it. def allTheSame(x, y, z) 24 Exercise 4 Write a function that returns true, if three arguments are all different, and provide a program to test it. def allDifferent(x, y, z) 25 Exercise 5 Write a function that returns true, if all three arguments are sorted, with the smallest one coming first and provide a program to test it. def sorted(x, y, z) 26 Quiz 9 27 Returning Multiple Values •In Python, a function can return multiple values ▪ Specified after the return statement separated by commas • Format: return expression1, expression2, etc. ▪ When you call such a function in an assignment statement, you need a separate variable on the left side of the = operator to receive each returned value. 28 Exercise • Write a function in Python that takes in two arguments (a and b) and returns three values (a + b, a - b, and a * b). 29 Global Variables • Global variable: created by assignment statement written outside all the functions. ▪ Can be accessed by any statement in the program file, including from within a function. ▪ If a function needs to assign a value to the global variable, the global variable must be redeclared within the function. • General syntax: global variable_name 30 Global Variables • Reasons to avoid using global variables: ▪ Global variables making debugging difficult •Many locations in the code could be causing a wrong variable value ▪ Functions that use global variables are usually dependent on those variables •Makes function hard to transfer to another program ▪ Global variables make a program hard to understand 31 Global Constants • Global constant: global name that references a value that cannot be changed ▪ Permissible to use global constants in a program ▪ To simulate global constant in Python, create global variable and do not re-declare it within functions 32 Exercise 6 Write a function that returns average of three arguments and provide a program to test it. def average(x, y, z) 33 Comments and Docstrings Python programs should be documented. • So, the developer who writes/maintains the code understands it • So, the user knows what the program does Comments def f(x): res = x**2 + 10 return res # compute result # and return it Docstring def f(x): 'returns x**2 + 10' res = x**2 + 10 # compute result return res # and return it 34 Standard Library Functions • Standard library: library of pre-written functions that comes with Python. ▪ Library functions perform tasks that programmers commonly need. • Viewed by programmers as a “black box”. • Some library functions built into Python interpreter. ▪ To use, just call the function. 35 Standard Library Functions • Modules: files that stores functions of the standard library. ▪ Help organize library functions, not built into the interpreter. ▪ Copied to computer when you install Python. • To call a function stored in a module, need to write an import statement. ▪ Written at the top of the program: ▪ Format: import module_name • Dot notation: notation for calling a function belonging to a module ▪ Format: module_name.function_name() 36 The math Module •math module: part of standard library that contains functions that are useful for performing mathematical calculations.  Typically accept one or more values as arguments, perform mathematical operation, and return the result.  Use of module requires an import math statement. 37 The math Module 38 The math Module  The math module defines variables pi and e, which are assigned the mathematical values for 𝜋 and 𝑒.  Can be used in equations that require these values, to get more accurate results.  Variables must also be called using the dot notation. 39 Exercise 7 • Using math module, write a function that calculates circle area. 40 Exercise 8 Write a function to count the number of the words in a sentence. You need to get the sentence from user. Period (dot) shows the end of the sentence. 41 Quiz 10 42 Summary • This chapter covered: ▪ The advantages of using functions ▪ The syntax for defining and calling a function ▪ Methods for designing a program to use functions ▪ Use of local variables and their scope ▪ Syntax and limitations of passing arguments to functions ▪ Global variables, global constants, and their advantages and disadvantages ▪ Value-returning functions ▪ Using library functions and the import statement 43 Feedback Let me know about your thoughts: It can be related to the course, the instructor (me), TAs, etc. https://form.jotform.com/222434547170048 You can share your thoughts anonymously! Any feedback, comments, suggestions, critics, etc. I appreciate your time! 44 Questions? Suggested Reading: ▪ Chapter 6 from textbook 45

Use Quizgecko on...
Browser
Browser