What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar.

Slides:



Advertisements
Similar presentations
Introduction to Python
Advertisements

Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Introduction to Computer Programming
ProgLan Python Session 4. Functions are a convenient way to divide your code into useful blocks, allowing us to: order our code, make it more readable,
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 6 Functions The Tic-Tac-Toe Game. Chapter Content In this chapter you will learn to do the following: 0 Write your own functions 0 Accept values.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Chapter 9: Value-Returning Functions
User-Written Functions
Topics Introduction to Functions Defining and Calling a Void Function
Introduction to Programming
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Introduction to Python
Formatting Output.
COMPSCI 107 Computer Science Fundamentals
Python: Control Structures
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
Functions.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Functions Inputs Output
CHAPTER FOUR Functions.
More Selections BIS1523 – Lecture 9.
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
Chapter 6 Methods: A Deeper Look
Chapter 4 void Functions
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Functions.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Introduction to Programming
Programming in C# CHAPTER - 7
5. Functions Rocky K. C. Chang 30 October 2018
Topics Introduction to Functions Defining and Calling a Void Function
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Introduction to Value-Returning Functions: Generating Random Numbers
Lesson #6 Modular Programming and Functions.
CISC101 Reminders All assignments are now posted.
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
COMPUTER PROGRAMMING SKILLS
Introduction to Computer Science
Text Copyright (c) 2017 by Dr. E. Horvath
Introduction to Programming
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Copyright (c) 2017 by Dr. E. Horvath
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
def-ining a function A function as an execution control structure
Functions, Procedures, and Abstraction
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Data Types and Expressions
Using Modules.
Presentation transcript:

What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar to mathematical functions

Why Use Functions? Functions make code more manageable: Can reuse code. Makes code more readable. Enables programmer to break complicated projects down into simpler parts.

The Structure of Functions A function is defined as follows def my_function(): …. Do processing ….. return A function definition is indicated by the keyword, def, followed by the name of the function, parameters if any, and a colon. Code that is part of the function is indented. This function ends with a return statement.

The Structure of Functions cont'd In the example on the previous slide, no arguments are accepted by the function and no value is returned. Since no value is returned, it is not necessary to end the function with a return statement. The end of the function definition is indicated by the first line of code that is not indented. Functions are invoked by the function statements. Compare the two simple function definitions and their invocation. def my_function_a(): print('Inside my_function_a') return def my_function_b(): print('Inside my_function_b') print('After my_function_a and my_function_b') my_function_a() my_function_b()

Passing Parameters to Functions In the following function we pass a floating point number to the function. The function returns a floating point. import math def calculate_sphere_volume(r): vol = 4 * math.pi * 3 / r**3 return vol radius = float(input('Input a radius ')) vol = calculate_sphere_volume(radius) print('The volume is ' + str(vol)) We've imported the math package so we could use pi. Also, the function input always returns a string value which is why we had to explicitly cast the input as a float. Also, we had to explicitly cast the vol variable to a string in the print statement.

Passing Parameters to Functions: Better Error Handling This is the same code as on the previous slide, except that we've incorporated error handling via a try-except block. The user might not enter a number, so the try-except enables the code to exit gracefully. import math def calculate_sphere_volume(radius): vol = 4 * math.pi * 3 / radius**3 return vol try: radius = float(input('Input a radius ')) vol = calculate_sphere_volume(radius) print('The volume is ' + str(vol)) except Exception: print('You did not enter a number!')

Passing Parameters to Functions: Better Error Handling Page 2 Notice that the try-except block only encloses the input statement, the function invocation, and the print volume statement. If the user failed to enter a number then no further statements in the try suite of code will be executed and the print error statement in the except suite of code will be executed. By including the function invocation and the print volume statements in the try suite of code, we guarantee that those statements will not be executed if the user enters invalid data. And that is what we want. As you write more complicated pieces of code, the possibility of different exceptions occurring will arise, and you the programmer would likely wish to handle those exceptions differently. Change the word Exception to the word ValueError, which is the specific kind of error thrown when a user fails to input a number.

Passing Parameters to Functions: Another Example In the following function we pass an integer and a float to the function. The function returns a floating point. def my_series(x,n): sum = 0 for i in range(0,n+1): sum += (-x)**i return sum x = float(input('Input a floating point number between 0 and 1: ')) n = int(input('Enter an integer between 1 and 10')) answer = my_series(x,n) print('The answer is ' + str(answer)) In the function definition, we wish to iterate from i = 0 up to i = n. If we had written (0,n), the for-loop would have iterated only from 0 up to n-1. Notice too, the casting of variables.

Passing Parameters to Functions: Better Error Handling This code calculates the same series as on the previous slide, only now we've included error handling. Notice what code is placed inside of try-except block. def my_series(x,n): sum = 0 for i in range(0,n+1): sum += (-x)**i return sum try: x = float(input('Input a floating point number between 0 and 1: ')) n = int(input('Enter an integer between 1 and 10')) answer = my_series(x,n) print('The answer is ' + str(answer)) except Exception: print('You did not enter a number')

Default Parameters When you define a function, you might want to give the user of option to either provide values for parameters or to use default parameters. You've already used a function that has default parameters and that is the show_message method of the SenseHat object. Let's revisit the show_message method. from sense_hat import SenseHat sense = SenseHat() sense.show_message('Good day') The Sense Hat displays the message, Good day, with the default scroll speed of 0.1, the default text color of white, and the default background color of black. In case you don't recall the arguments of the show_message function, if you pause after typing sense.show_message( in the Python shell, Python will display the parameters, including default values.

Default Parameters Here are other ways of using the show_message method: sense.show_message('Good day',scroll_speed=0.2) sense.show_message('Good day',scroll_speed=0.05, text_colour=[100,255,0]) sense.show_message('Good day',scroll_speed=0.08,text_colour=[100,255,0], back_colour=[255,255,255]) Notice that the British spelling of the word color must be used. Also, colors are given as lists of red, green, and blue components, and possible values of each range from 0 to 255.

More on Default Parameters The show_message method can also be invoked without explicitly entering the words scroll_speed, text_colour, and back_colour: sense.show_message('Good day',0.08,[0,0,255],[255,0,0]) Notice that the British spelling of the word color must be used. Also, colors are given as lists of red, green, and blue components, and possible values of each range from 0 to 255. If you do not explicitly enter the words scroll_speed, text_colour, and back_colour, the values you enter must be entered in order.

A Default Parameter Example Consider a function that has default values for two arguments: def my_function(s='Good day', x = 9.8): print('s = ' + s) print('x = ' + str(x)) Type in the following function invocations to see what is printed out. my_function() my_function(s='Bon Jour',x=3.5) my_function(x=2.14, s='Buenos Dias') my_function('Willkommen',10)

Functions that Return More than One Value Functions can return more than one value. Consider the following very simple function that returns two values, an integer and a string. In order to retrieve the values, you type in two variable names separated by a comma, and both of which are followed by the function invocation. def my_function(): return 35, 'Grocery List' value, s = my_function() print('value = '+str(value)) print('s = '+s)

Scope of Variables: A Preliminary Discussion If a variable is assigned a value within a function then that variable is not accessible from other parts of the code. That variable has local scope. def do_calculation(): x = 4.5 y = 3.2 tri = (x**2 + y**2)/5.0 return tri result = do_calculation() print(‘result = ' + str(result)) The above code is correct; the print statement prints out the value of the variable, returned from the function.

Scope of Variables: A Preliminary Discussion Continued The following code is NOT correct because the print statement is outside the function. The variable, tri, is defined only within the function, so an error will occur if you attempt to access the variable outside. def do_calculation(): x = 4.5 y = 3.2 tri = (x**2 + y**2)/5.0 return do_calculation() print('tri = ' + str(tri))

Documentation def compute_area(height:float,width:float)->float: """This function was written by your name to compute the area of a triangle. ""“ pass print(compute_area.__doc__) # prints the document indicated in the ""“ double-quotes print(compute_area.__annotations__) # prints the parameters and the returned values print(compute_area.__str__) # prints all of the information about the function

Function Design Do not read in values within a function, unless the function is a main function or the function’s only task is to read in value. Do not print out values within a function, unless the function is a main function or the function’s only task is to write out value. The input and output tasks should be kept separate from the tasks of the function. You will need to pass in data as an argument to the parameters of the function.

Function Design Example def my_series(x,n): sum = 0 for i in range(0,n+1): sum += (-x)**i return sum def main(): try: x = float(input('Input a floating point number between 0 and 1: ')) n = int(input('Enter an integer between 1 and 10')) answer = my_series(x,n) print('The answer is ' + str(answer)) except Exception: print('You did not enter a number') main()