CMSC11_Unit2.pdf
Document Details
Uploaded by PanoramicLyric
Tags
Full Transcript
CMSC 11 Unit 2: Functions Function named sequence of statements that performs a computation it is defined by specifying the name and the sequence of statements Example: >>> type(32) Format of calling a Function name_of_function(argument) A function “takes” an...
CMSC 11 Unit 2: Functions Function named sequence of statements that performs a computation it is defined by specifying the name and the sequence of statements Example: >>> type(32) Format of calling a Function name_of_function(argument) A function “takes” an argument and “returns” a result called the return value An argument is an expression that appears between the parentheses of a function call Function Example int() function - converts values into integers - throws an error if it cannot convert value to integer Function Example int() function always rounds down Why Functions? Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug Functions can make a program smaller by eliminating repetitive code Why Functions? Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole Well designed functions are often useful for many programs. Once you write and debug one, you can reuse it Type Conversion Functions int(x) : takes an argument x and converts it into an integer Type Conversion Functions float(x) : takes an argument x and converts it into a float Type Conversion Functions str(x) : takes an argument x and converts it into a string Module package is a file that contains a module collection of related functions classes functions specific task variables objects the module object contains the functions and variables variables defined in the module Module Before using the functions in the module, we first use the import statement to create the module object Example: >>> import math Module After creating the module object, you can access any of its functions or variables by using this general format: module_name.function_name() module_name.variable this is called the dot notation Math Module built-in python module that contains usual mathematical formulas and values >>> import math >>> from math import sqrt >>> math.sqrt(9) >>> sqrt(9) >>> 3.0 >>> 3.0 Math Module some math library functions Composition how variables, expressions, and statements are combined ability of programming languages where small building blocks are taken and composed together Example: argument of a function can be any kind of expression >>> x = math.sin(45/360.0 * 2 * math.pi) Composition You can put an arbitrary expression anywhere except: the left side of an assignment statement (has to be a variable name). any other expression on the left side is a syntax error. Example: Create your own functions A function definition specifies the name of a new function and the sequence of statements that execute when the function is called Function definition General format: name of the function that will be used to call it by def function_name(parameter): body_of_code the expected keyword that arguments that indicates that it will take. Can this is a composition of codes that the be empty function function will do when called definition Example Function name? Parameter? Body? Example You can return values in a function. Keep the return value in a variable Rules for function names Letters, numbers, and underscore are legal, but first character cannot be a number Keywords should not be used as the name of a function Avoid having a variable and a function sharing the same name Flow of Execution Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom. Function definitions do not alter the flow of the program, but statements inside the function are not executed until the function is called. Flow of Execution A function call is like a detour in def print_lyrics(): print(’Baby Baby Baby’) the flow of execution. Instead of print(’Nooooo’) going to the next statement, the flow jumps to the body of the def repeat_lyrics(): function, runs the statements print_lyrics() there, and then comes back to print_lyrics() pick up where it left off. repeat_lyrics() Guess the Flow of Execution name = “Maria” sentence = “ is going to the ball“ result = name + sentence print(result) Guess the Flow of Execution name = “Maria” sentence = “ is going to the ball“ result = name + sentence print(result) Recall Format of calling a Function: name_of_function(argument) Recall general format of a function (with definition): name of the function that will be used to call it by def function_name(parameter): body_of_function keyword that the expected indicates that this arguments that it is a function composition of codes that the will take. Can be definition function will do when called empty Parameter and Arguments Parameter a variable in a function definition a placeholder does not have a concrete value Argument value passed when a function is called Parameter and Arguments def print_cat_name(cat): sentence = “My cat’s name is” print(sentence, cat) What is the parameter? food = ‘Mochi’ best_boy = ‘Shrek’ What are the arguments? print_cat_name(food) print_cat_name(best_boy) Parameter and Arguments Output: Function parameters and variables are local. - meaning they only exist and are accessible inside of the function definition The variable sentence cannot be used outside of the function print_cat_name() another variable named also as sentence has been defined outside the print_cat_name() function Stack Diagrams used to keep track of which variables can be used where show the value of each variable, but they also show the function each variable belongs to each function is represented by a frame a box with the name of a function beside it and the parameter and variables of the function inside it. frames are arranged in a stack that indicates which function called which,and so on. Stack Diagrams Stack Diagram Code Stack Diagrams if an error occurs during a function call, Python prints the names of all the functions involved this is called a traceback Fruitful and Void Functions Fruitful Functions are functions that return results example is the math function return value will cease to exist if it is not assigned to a variable Void Function are functions that perform an action but don’t return a value example is the print_lyrics() functions if assigned to a variable, that variable will hold the special value None Fruitful or Void function? Fruitful or Void function? Void it does not return a result/value Fruitful or Void function? Fruitful or Void function? Fruitful it returns a value Summary We’ve learned what a function is, how to make our own, and how to use them intuitively. Exercises Please do these online exercises during your own time. No submission needed. https://holypython.com/beginner-python-exercises 1 (print() function) to 4 (type conversion) only. Reminders Quiz for units 1 and 2. Next Meeting Unit 3: Conditionals and Recursions