Presentation is loading. Please wait.

Presentation is loading. Please wait.

CISC101 Reminders Assn 3 due Friday, this week.

Similar presentations


Presentation on theme: "CISC101 Reminders Assn 3 due Friday, this week."— Presentation transcript:

1 CISC101 Reminders Assn 3 due Friday, this week.
Winter 2018 CISC101 11/13/2018 CISC101 Reminders Assn 3 due Friday, this week. Quiz 3 next week. Topics on next slide. Winter 2018 CISC101 - Prof. McLeod Prof. Alan McLeod

2 Quiz 3 Topics Functions – using and writing. Lists: Loops – still!
operators used with lists. keywords used with lists. BIF’s used with lists. list methods. Loops – still! Conditionals – still! File I/O, catching Exceptions. Exercises 1 to 6. Sets not on quiz. Winter 2017 CISC101 - Prof. McLeod

3 Today Building Functions, Cont.: Another module example.
Why are functions better? Functional Decomposition. Go over function syntax in more detail. Winter 2018 CISC101 - Prof. McLeod

4 Aside - Two Ways to Use import
To tell the interpreter that we wish to use module functions, you need to import the module as in: import math But, if you don’t want to have to say math.sqrt() (ie. you don’t want to have to name the module all the time), you can use a different kind of import statement: from math import * Or, to just import the sqrt() function for example: from math import sqrt Winter 2018 CISC101 - Prof. McLeod

5 Module Functions, Cont. If you have used from math import *, for example, then you can invoke any of the math functions directly: print(sqrt(2)) Instead of: print(math.sqrt(2)) Winter 2018 CISC101 - Prof. McLeod

6 Example – The myInput Module
Put our robust input function in a code module and import it into other programs, just like we have been doing with the turtle and math modules. Create myInput.py, which contains only the getInt() and getFloat() functions and does not need to have a main() function. In another program use “import myInput”. Note the creation of a byte code version (*.pyc) of the new module… See myInput.py and FunctionalMortgageCalculatorV2.py. Winter 2018 CISC101 - Prof. McLeod

7 Designing a Function A function should only do one thing. If you describe the function and need to use the word “and”, then it is probably doing more than one thing. Try to keep the parameter list short – 3 or fewer parameters, if possible. Or take advantage of default arguments (more on this later). The function should be short: in the range of 1 to 15 lines ideally. Be prepared to re-structure a working program to get a better design. Winter 2018 CISC101 - Prof. McLeod

8 Designing a Function, Cont.
Choose good, descriptive function and parameter names, so it is obvious what the function is doing. If you only need to add a bit more code to make your function more universally applicable – do it! Try to always check all your parameter values for legality. What would happen if the arguments supplied to our myInput functions are not of the expected type? Winter 2018 CISC101 - Prof. McLeod

9 Designing a Function, Cont.
Try to get your function to return something rather than print something. Often main() will have to worry about all the console output. By convention, main() should always be the starting point of your program. Winter 2018 CISC101 - Prof. McLeod

10 Program Construction You can start from a functional decomposition of the problem. Write function headers and add parameters. Put the return value in a comment for now. Choose function names that describe what the function does. Make sure each function does one thing only. You may find a need for additional functions as you fill in the code for each function. Don’t be afraid to further decompose a function if it is getting too big or doing too many things. Winter 2018 CISC101 - Prof. McLeod

11 Testing and Debugging How can you test a one function program? In this case you need to wait until the entire program is complete before you can start testing! Or, you can choose to test one function at a time by: Putting a pass command in other empty (for the moment) functions. Add temporary code to main() to invoke your test function with test values and then display its return value. You know a failure is from the function under test! Small functions are much easier to debug!! Winter 2018 CISC101 - Prof. McLeod

12 You Decide! Multi-function PROs: CONs: Easier to design.
CISC101 You Decide! Multi-function PROs: Easier to design. Easier to construct. Easier to read. Requires fewer comments. Easier to test and fix. Easier to re-use. CONs: Longer program overall. Slower? (not much…) Winter 2018 CISC101 - Prof. McLeod Prof. Alan McLeod

13 Functional Decomposition
A common-sense idea: break a large problem down into smaller pieces! Keep breaking down the pieces until they are small enough to solve. Each piece will represent a function if the problem is a programming problem. Winter 2018 CISC101 - Prof. McLeod

14 Example – Washing Machine Control
Top-most level: Connect wasther to 110V AC, hot/cold water supply and drain. Place clothes and soap in washer. Washer removes dirt from clothes. Remove clothes containing a minimal amount of water and dirt. We are interested in step 3. Winter 2018 CISC101 - Prof. McLeod

15 Example, Cont. – Second Level
Step 3 on the previous slide decomposed: Agitate clothes in soapy water. Remove soapy water. Rinse with water. Remove as much water as possible from clothes. Winter 2018 CISC101 - Prof. McLeod

16 Example, Cont. – Third Level
Step 1 (only) from the previous slide: Lock washer door. Fill machine with water of specified temperature. Activate agitator motor to specified rate. Agitate for specified time period. Winter 2018 CISC101 - Prof. McLeod

17 Example, Cont. – Fourth Level
Step 2 (only) from the previous slide: Query front panel settings for water temperature. Depending on settings, open cold valve only, hot valve only or both. If water is not flowing activate alarm. Close water input valves when level sensor indicates desired water level has been obtained. Winter 2018 CISC101 - Prof. McLeod

18 Example, Cont. – Fourth Level, Pseudocode
desiredTemp = getTempSetting(frontpanel) if desiredTemp == hot openValve(hot) else if desiredTemp == cold openValve(cold) else if not waterFlowing() sendAlarm(waterError) while not waterFull(desiredLevel) if waterFull(desiredLevel) closeValves() Winter 2018 CISC101 - Prof. McLeod

19 Example, Cont. And so on… Continue the process until you have sufficient detail to write pseudocode. Put together a list of functions. List: The name of the function. The return type, if any. The required parameters. What the function does. What the function does if input is illegal. Winter 2018 CISC101 - Prof. McLeod

20 Invoking Functions - Review
Name the function and then use round brackets. The brackets can be empty or have one or more arguments inside. For example: print() Displays a linefeed on the console. print("Hello") Displays the string Hello on the console. print("Hello", "Alan") Displays Hello and then Alan, separated by a space on the console. Winter 2018 CISC101 - Prof. McLeod

21 Invoking Functions, Cont.
Arguments are separated by commas. Arguments can be: Literal values. Variables. Expressions. In the case of a variable or an expression, it is first evaluated to come up with the resulting value before it is fed into the function. Winter 2018 CISC101 - Prof. McLeod

22 Aside - Keyword Arguments
The previous print() examples used positional arguments. We have also done things like: print("Hello", "Alan", sep="\n") The two strings will be on different lines this time. The sep="\n" thing is called a keyword argument. We will learn more about keyword arguments and default arguments later! Winter 2018 CISC101 - Prof. McLeod

23 Function Returns A function may return something.
Functions that don’t return anything (like print(), for example) are sometimes called procedures or void functions. Can you think of some functions that return something? input() float() str() len() sorted() Winter 2018 CISC101 - Prof. McLeod

24 Function Returns This “thing” that is returned can be any Python type such as a string, a list, an int, a float, etc. It is also possible to return multiple things in Python: a, b, c = someFunction(arg1, arg2) But, is the a, b, c part three “things” or just one thing really? What type is it? Winter 2018 CISC101 - Prof. McLeod

25 A Function with Parameters
Here is a (useless) function that displays the higher of two numbers: def showHighest(num1, num2) : if num1 > num2 : print(num1, "is higher.") else : print(num2, "is higher.") Winter 2018 CISC101 - Prof. McLeod

26 A Function with Parameters, Cont.
So, when you invoke this (completely useless) function from within some other function (main() perhaps…), you need to supply two things for the parameters - you supply two arguments: showHighest(3.4, 6.7) The code in showHighest() runs and the larger number is displayed. Within showHighest(), num1 has the value 3.4 and num2 has the value 6.7 Winter 2018 CISC101 - Prof. McLeod

27 A Function with Parameters, Cont.
To put it another way: The positional arguments 3.4 and 6.7 have been mapped into the parameters num1 and num2. num1 and num2 are variables that have been created in the function’s parameter list and are local to the function. Winter 2018 CISC101 - Prof. McLeod

28 Functions Returning a Value
How can showHighest() be changed to return the highest number instead of printing it out? (It is kind of tacky to have functions print things instead of returning them - let main() do the printing!) def getHighest(num1, num2) : if num1 > num2 : return num1 else : return num2 Winter 2018 CISC101 - Prof. McLeod

29 Functions Returning a Value, Cont.
Or: def getHighest(num1, num2) : if num1 > num2 : return num1 return num2 Winter 2018 CISC101 - Prof. McLeod

30 Returning Values So, here are a few things you need to know about returning things: You can have as many return statements as you want in a function. If you don’t have a return statement, then your function does not return anything. It is invoked without expecting any value to come out of the function (no assignment required when invoking). Execution of a function stops as soon as you execute the return statement, even if there is code after the return statement. Winter 2018 CISC101 - Prof. McLeod

31 Jazzing Up the Parameter List
When using a function, you might not always need or wish to supply all possible parameters. Or, you might not want to have to worry about the order of the arguments supplied. The use of keyword (when invoking) and default (when defining) arguments allows you to enhance the flexibility of how your function is used. Winter 2018 CISC101 - Prof. McLeod

32 parameterName=argument
CISC101 Keyword Arguments Suppose you have a function with several parameters, but you don’t want to worry about supplying values in the matching order. You can use keyword arguments to supply the arguments in any order with the syntax: parameterName=argument in the parameter list. See KeywordArgumentsDemo.py Winter 2018 CISC101 - Prof. McLeod Prof. Alan McLeod

33 Keyword Arguments, Cont.
All positional arguments must come before keyword arguments. But, the keyword arguments can be in any order. Unless the function has default arguments, you must still supply arguments for each parameter. Style note: No spaces on either side of the equals sign. Winter 2018 CISC101 - Prof. McLeod

34 Default Arguments You can make a function a great deal more flexible by making it optional for the user to supply all the arguments. You do this by creating default arguments in your function definition statement. Default arguments must come after all positional parameters. The same syntax as for Keyword Arguments, but this time it is used in the def line instead of the invoking line. See DefaultArgumentsDemo.py Winter 2018 CISC101 - Prof. McLeod

35 Default Arguments, Cont.
You must decide which parameters are optional, if any. Then you must make assumptions to come up with values for those optional parameters. Supplying an argument value for a default argument replaces the default value. We will see quite a bit of this stuff when using Tkinter! Reduces the need for multiple function versions. Winter 2018 CISC101 - Prof. McLeod

36 Example: The print() BIF
We know that print() can have any number of positional arguments. It also has sep= and end= default arguments. They have been defaulted as sep=" " and end="\n" In other words the default separator between printed items is a space and a linefeed will be added to the output after the last item has been printed. You can only change these values using the keyword arguments. Winter 2018 CISC101 - Prof. McLeod


Download ppt "CISC101 Reminders Assn 3 due Friday, this week."

Similar presentations


Ads by Google