Skip to content
Snippets Groups Projects
Commit de164606 authored by msyamkumar's avatar msyamkumar
Browse files

lec-06 clean up

parent b43e5be5
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Creating Functions
%% Cell type:markdown id: tags:
### Review - pre-installed modules
### Two ways of importing functions from a module
1. import \<module\>
- requires you to use attribute operator: `.`
- \<module\>.\<function\>
2. from \<module\> import \<function\>
- function can be called just with its name
Let's learn about time module
%% Cell type:code id: tags:
``` python
# Add all your import statements to this cell
# TODO: import time module using import style of import
import time
# TODO: use from style of import to import log10 function from math module
from math import log10
# Bad style to import everything from a module
# Not recommended to do
#from math import *
# If you want to import everything, you need to
# follow import style of import
import math
```
%% Cell type:markdown id: tags:
time module time function shows the current time in seconds since epoch.
What is epoch? epoch is January 1, 1970. **FUN FACT:** epoch is considered beginning of time for computers.
%% Cell type:code id: tags:
``` python
start_time = time.time()
x = 2 ** 1000000000 # some large computation
end_time = time.time()
# TODO: change the line below to compute difference
difference = (end_time - start_time)
# TODO: add a separator of '\n'
print(start_time, end_time, difference, sep = "\n")
# TODO: discuss - how can you use time() function to time your project code?
```
%% Output
1644107903.650124
1644107909.54414
5.8940160274505615
%% Cell type:code id: tags:
``` python
# TODO: call log10 function to determine log base 10 of 1000
print(log10(1000))
# Recall that you cannot use math. when you use from style of import
# print(math.log10(1000)) #doesn't work
```
%% Output
3.0
%% Cell type:code id: tags:
``` python
# TODO: can you access pi variable inside math module?
#pi # TODO: discuss why this didn't work
# TODO: go back to the import cell and import math
# TODO: fix line 2, so that you are now able to access pi inside math module
math.pi
```
%% Output
3.141592653589793
%% Cell type:markdown id: tags:
## Learning Objectives
- Explain the syntax of a function header:
- def, ( ), :, tabbing, return
- Write a function with:
- correct header and indentation
- a return value (fruitful function) or without (void function)
- parameters that have default values
- Write a function knowing the difference in outcomes of print and return statements
- Explain how positional, keyword, and default arguments are copied into parameters
- Make function calls using positional, keyword, and default arguments and determine the result.
- Trace function invocations to determine control flow
%% Cell type:markdown id: tags:
## Example 1: Cube of a number
- Input: number (to be cubed)
- Output: cubed number
%% Cell type:code id: tags:
``` python
# TODO: Let's define the cube function
def cube(side):
return side ** 3
```
%% Cell type:code id: tags:
``` python
# Let's call cube function
print(cube(5))
# TODO: discuss what is different about the below line of code
print(cube(cube(2)))
```
%% Output
125
512
%% Cell type:code id: tags:
``` python
# TODO: compute 4 cube + -3 cube
# version 1
print(cube(4) + cube(-3))
# version 2
cube_of_4 = cube(4)
cube_of_minus_3 = cube(-3)
print(cube_of_4 + cube_of_minus_3)
```
%% Output
37
37
%% Cell type:code id: tags:
``` python
# TODO: compute 4 cube * -3 cube
# Now which one of the above two versions is better?
print(cube_of_4 * cube_of_minus_3)
```
%% Output
-1728
%% Cell type:code id: tags:
``` python
# Whenever you think you are going to reuse a function call's
# output, save it in a variable
# Rookie programmer mistake: calling the same function with the
# same arguments will always give the same return value
# Running the same function call twice takes twice the time
```
%% Cell type:markdown id: tags:
`return` vs `print`
- `return` enables us to send output from a function to the calling place
- default `return` value is `None`
- that means, when you don't have a `return` statement, `None` will be returned
- `print` function simply displays / prints something
- it cannot enable you to produce output from a function
%% Cell type:code id: tags:
``` python
# TODO: Go back to cube function defintion, change return to print
# Run the above function call cells to see what happens
```
%% Cell type:markdown id: tags:
## Tracing function invocations
- PythonTutor is a great tool to learn control flow
- Let's use PythonTutor to trace cube function invocation
- TODO: Copy-paste cube function defintion into PythonTutor (course website > tools > PythonTutor)
%% Cell type:markdown id: tags:
## Example 2: is_between(lower, num, upper)
- Purpose: check whether number is within the range of lower and upper (inclusive)
- Input: lower bound, number, upper bound
- Output: boolean value (`True` or `False`)
- Keyword: `pass`:
- placeholder statement
- you cannot run a cell with an empty function definition
%% Cell type:code id: tags:
``` python
def is_between(lower, num, upper):
#pass # TODO: remove this and try to run this cell
# version 1
return lower <= num <= upper
# version 2
#return lower <= num and num <= upper
# you can call a function in the same cell that you defined it
print(is_between(3, 7, 21))
print(is_between(2, 14, 5))
print(is_between(100, cube(5), 200))
```
%% Output
True
False
True
%% Cell type:markdown id: tags:
## Types of arguments
- positional
- keyword
- default
Python fills arguments in this order: positional, keyword,
%% Cell type:code id: tags:
``` python
def add3(x, y = 100, z = 100):
"""adds three numbers""" #documentation string
print ("x = " + str(x))
print ("y = " + str(y))
print ("z = " + str(z))
return x + y + z
sum = add3(100, 10, 5)
# TODO: 1. sum is a bad variable, discuss: why. What would be a better variable name?
# TODO: 2. what type of arguments are 100, 10, and 5? Positional
total = add3(100, 10, 5)
total
```
%% Output
x = 100
y = 10
z = 5
x = 100
y = 10
z = 5
115
%% Cell type:code id: tags:
``` python
print(add3(x = 1, z = 2, y = 5)) #TODO: what type of arguments are these? Keyword
```
%% Output
x = 1
y = 5
z = 2
8
%% Cell type:code id: tags:
``` python
add3(5, 6) # TODO: what type of argument gets filled for the parameter z? Default value
```
%% Output
x = 5
y = 6
z = 100
111
%% Cell type:markdown id: tags:
Positional arguments need to be specified before keyword arguments.
%% Cell type:code id: tags:
``` python
# Incorrect function call
add3(z = 5, 2, 7)
# TODO: what category of error is this?
```
%% Output
File "/var/folders/k6/kcy8b4f57hx9f1wh4sbs8mn40000gn/T/ipykernel_49460/1597961864.py", line 2
add3(z = 5, 2, 7)
^
SyntaxError: positional argument follows keyword argument
%% Cell type:markdown id: tags:
Similarly, parameters with default values should be defined after parameters without default values.
%% Cell type:code id: tags:
``` python
# Incorrect function definition
def add3_bad_version(x = 10, y, z):
"""adds three numbers""" #documentation string
return x + y + z
```
%% Output
File "/var/folders/k6/kcy8b4f57hx9f1wh4sbs8mn40000gn/T/ipykernel_49460/1367324985.py", line 2
def add3_bad_version(x = 10, y, z):
^
SyntaxError: non-default argument follows default argument
%% Cell type:markdown id: tags:
Python expects exactly same number of arguments as parameters.
%% Cell type:code id: tags:
``` python
# Incorrect function call
add3(5, 3, 10, x = 4)
# TODO: what category of error is this?
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/var/folders/k6/kcy8b4f57hx9f1wh4sbs8mn40000gn/T/ipykernel_49460/100225854.py in <module>
1 # Incorrect function call
----> 2 add3(5, 3, 10, x = 4)
3 # TODO: what category of error is this?
TypeError: add3() got multiple values for argument 'x'
%% Cell type:code id: tags:
``` python
# TODO: will this function call work?
add3(y = 5, z = 10)
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/var/folders/k6/kcy8b4f57hx9f1wh4sbs8mn40000gn/T/ipykernel_49460/2441706151.py in <module>
1 # TODO: will this function call work?
----> 2 add3(y = 5, z = 10)
TypeError: add3() missing 1 required positional argument: 'x'
%% Cell type:code id: tags:
``` python
# TODO: will this function call work?
add3()
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/var/folders/k6/kcy8b4f57hx9f1wh4sbs8mn40000gn/T/ipykernel_49460/2146538074.py in <module>
1 # TODO: will this function call work?
----> 2 add3()
TypeError: add3() missing 1 required positional argument: 'x'
%% Cell type:markdown id: tags:
## Example 3: Generate a height x width grid
- Input: width, height, grid symbol, title of the grid
- Output: string containing title, a newline, and the grid
- Pseudocode steps:
1. Generate a single row of symb (width dimension). What string operator do you need?
2. Capture single row into a variable
3. Add newline to single row variable.
4. Generate multiple rows (height dimension). What string operator do you need?
5. Generate the output string to be returned by adding title with a newline with the output from step 4.
%% Cell type:code id: tags:
``` python
# TODO: how many parameters have default values in the below function?
def get_grid(width, height, symb = '#', title = 'My Grid:'):
row = symb * width
grid = (row + '\n') * height
return title + '\n' + grid
```
%% Cell type:code id: tags:
``` python
# TODO: generate various sized grids, by exploring
# three types of arguments
# Here is one example
print(get_grid(10, 8))
```
%% Output
My Grid:
##########
##########
##########
##########
##########
##########
##########
##########
%% Cell type:code id: tags:
``` python
# TODO: use PythonTutor to trace get_grid function call
```
%% Cell type:code id: tags:
``` python
print(get_grid(5, 4, symb = "@"))
```
%% Output
My Grid:
@@@@@
@@@@@
@@@@@
@@@@@
%% Cell type:code id: tags:
``` python
print(get_grid(2, 3, ".", "Some Grid:"))
```
%% Output
Some Grid:
..
..
..
%% Cell type:code id: tags:
``` python
print(get_grid(width = 4, height = 7, symb = "^", title = "Some other grid:"))
```
%% Output
Some other grid:
^^^^
^^^^
^^^^
^^^^
^^^^
^^^^
^^^^
%% Cell type:markdown id: tags:
### Revisiting `print` function
- Let's look at `help(print)` to learn about print's parameters
- Default value for `sep` is space, that is: " "
- Default value for `end` is newline, that is: "\n"
%% Cell type:code id: tags:
``` python
help(print)
```
%% Output
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
%% Cell type:code id: tags:
``` python
# TODO: predict output, then run to validate your prediction
print(3 + 4, 3 < 4, "3" + "4", end = "....\n" ) # sep default is " "
print(3 + 4, 3 < 4, "3" + "4", sep = "\t" ) # end default is "\n"
```
%% Output
7 True 34....
7 True 34
%% Cell type:markdown id: tags:
## fruitful function versus void function
- fruitful function: returns something
- ex: add3
- void function: doesn't return anything
- ex: bad_add3_v1
%% Cell type:code id: tags:
``` python
# Example of void function
def bad_add3_v1(x, y, z):
print(x + y + z)
print(bad_add3_v1(4, 2, 1))
```
%% Output
7
None
%% Cell type:code id: tags:
``` python
print(bad_add3_v1(4, 2, 1) ** 2) # Cannot apply mathematical operator to None
```
%% Output
7
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/var/folders/k6/kcy8b4f57hx9f1wh4sbs8mn40000gn/T/ipykernel_49460/1070455296.py in <module>
----> 1 print(bad_add3_v1(4, 2, 1) ** 2) # Cannot apply operations to None
TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int'
%% Cell type:markdown id: tags:
### `return` statement is final
- exactly *one* `return` statement gets executed for a function call
- immediately after encountering `return`, function execution terminates
%% Cell type:code id: tags:
``` python
def bad_add3_v2(x, y, z):
return x
return x + y + z # will never execute
bad_add3_v2(50, 60, 70)
```
%% Output
50
%% Cell type:markdown id: tags:
Default return type from a function is None.
None is a special type in Python (similar to null in Java).
%% Cell type:markdown id: tags:
### Trace this example
- manually
- then use PythonTutor
%% Cell type:code id: tags:
``` python
def func_c():
print("C")
def func_b():
print("B1")
func_c()
print("B2")
def func_a():
print("A1")
func_b()
print("A2")
func_a()
```
%% Output
A1
B1
C
B2
A2
%% Cell type:markdown id: tags:
## Correction from last lecture
- In Python, you *can* convert float value to int. Ex: int(10.56).
- In Python, you *cannot* convert a str with a float value into an int. Ex: int('10.56') will not work.
%% Cell type:code id: tags:
``` python
# Try it out
# int(10.56)
```
%% Cell type:code id: tags:
``` python
# Try it out
# int('10.56')
```
%% Cell type:markdown id: tags:
## Absolute of a number
%% Cell type:code id: tags:
``` python
abs(-10)
```
%% Cell type:code id: tags:
``` python
abs(10)
```
%% Cell type:markdown id: tags:
Let's define our own absolute function.
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
To use a function, you need to call / invoke it.
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## Square root of a number
%% Cell type:code id: tags:
``` python
# sqrt(16) # wouldn't work because module was not imported!
```
%% Cell type:markdown id: tags:
Let's import sqrt the math module.
Keywords: from, import
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
Modules are collections of similar functions and variables.
math module also contains a variable called 'pi'.
%% Cell type:code id: tags:
``` python
pi # doesn't work, because we haven't imported pi yet
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
Let's define our own square root function.
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
Square root of a negative number gives you an imaginary number.
We won't be talking about imaginary numbers in this course.
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## Power: raising x to the power y
%% Cell type:code id: tags:
``` python
pow(2, 3)
```
%% Cell type:markdown id: tags:
Let's define our own power function.
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
power(2, 3) # 2 goes into base and 3 goes into exp; these are examples of positional arguments
```
%% Cell type:code id: tags:
``` python
power(base = 2, exp = 3) # example of named keyword arguments
```
%% Cell type:code id: tags:
``` python
power(exp = 3, base = 2) # with named keyword arguments, you could switch the order of the parameters!
```
%% Cell type:code id: tags:
``` python
power(10) # 10 goes into base (positional arugment) and exp gets default argument as 2
```
%% Cell type:code id: tags:
``` python
power(exp = 3, 2) # wouldn't work because positional arguments should come before keyword arguments
```
%% Cell type:markdown id: tags:
## Let's play with a dog
%% Cell type:code id: tags:
``` python
from dog import *
```
%% Cell type:code id: tags:
``` python
speak()
```
%% Cell type:code id: tags:
``` python
fetch()
```
%% Cell type:markdown id: tags:
Let's capture return value of speak and fetch functions.
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
Default return type from a function is None.
None is a special type in Python (similar to null in Java).
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## Let's play with the cat, by creating it
%% Cell type:code id: tags:
``` python
from cat import *
```
%% Cell type:markdown id: tags:
Now cat functions replaced dog functions :(
%% Cell type:code id: tags:
``` python
speak()
```
%% Cell type:markdown id: tags:
Fetch is still from the dog module.
%% Cell type:code id: tags:
``` python
fetch()
```
%% Cell type:markdown id: tags:
## Two ways of importing functions from a module
1. from \<module\> import *
2. import module
- requires you to use attribute operator: “.”
- \<module\>.\<function\>
%% Cell type:markdown id: tags:
Let's try second style of import with dog and cat.
%% Cell type:code id: tags:
``` python
import cat
import dog
cat.speak()
dog.speak()
```
%% Cell type:markdown id: tags:
## Getting details about module
- Try type(module) and type(function)
- dir(module): gives you a list of the functions defined inside the module
- \<module\>.\<function\>.__doc__: gives you documentation about the function
%% Cell type:code id: tags:
``` python
type(dog)
```
%% Cell type:code id: tags:
``` python
type(dog.speak)
```
%% Cell type:code id: tags:
``` python
dir(dog)
```
%% Cell type:code id: tags:
``` python
dir(cat)
```
%% Cell type:code id: tags:
``` python
dir(math) # doesn't work because dir works only with second style of import
```
%% Cell type:markdown id: tags:
Let's import the math module.
%% Cell type:code id: tags:
``` python
import math
```
%% Cell type:code id: tags:
``` python
dir(math)
```
%% Cell type:code id: tags:
``` python
math.ceil
```
%% Cell type:code id: tags:
``` python
type(math.ceil)
```
%% Cell type:code id: tags:
``` python
math.ceil(3.1)
```
%% Cell type:code id: tags:
``` python
print(math.ceil.__doc__)
```
%% Cell type:code id: tags:
``` python
dog.speak.__doc__
```
%% Cell type:markdown id: tags:
## Let's learn how to write documentation for the cat module
- After you have imported a module, if you want to make changes, you have to run the input cell with import again!
- Easier way: Kernel > Restart & Run All.
%% Cell type:code id: tags:
``` python
cat.speak.__doc__
```
%% Cell type:markdown id: tags:
## Time module
%% Cell type:code id: tags:
``` python
from time import time
```
%% Cell type:code id: tags:
``` python
time()
```
%% Cell type:code id: tags:
``` python
start_time = time()
print("We're about to time how fast Python prints things!")
end_time = time()
print("Printing took", end_time - start_time, "seconds.")
#You could use time() function to time your project code.
#In an initial cell, initialize start_time
#In the last cell, initialize end_time
```
%% Cell type:markdown id: tags:
## Random module
%% Cell type:code id: tags:
``` python
from random import randint
print(randint(1, 10))
```
%% Cell type:markdown id: tags:
## Print versus return
- return statement is final in a function execution!
- Let's do this demo in Python Tutor
%% Cell type:code id: tags:
``` python
def sequence_v1():
print(1)
print(2)
print(3)
sequence_v1()
```
%% Cell type:code id: tags:
``` python
# once you return, no other statements get executed
def sequence_v2():
return (1)
return (2)
return (3)
seq_val = sequence_v2()
print(seq_val)
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
# Creating Functions
%% Cell type:markdown id: tags:
### Review - pre-installed modules
### Two ways of importing functions from a module
1. import \<module\>
- requires you to use attribute operator: `.`
- \<module\>.\<function\>
2. from \<module\> import \<function\>
- function can be called just with its name
Let's learn about time module
%% Cell type:code id: tags:
``` python
# Add all your import statements to this cell
# TODO: import time module using import style of import
# TODO: use from style of import to import log10 function from math module
# Bad style to import everything from a module
# Not recommended to do
#from math import *
# If you want to import everything, you need to
# follow import style of import
```
%% Cell type:markdown id: tags:
time module time function shows the current time in seconds since epoch.
What is epoch? epoch is January 1, 1970. **FUN FACT:** epoch is considered beginning of time for computers.
%% Cell type:code id: tags:
``` python
start_time = time.time()
x = 2 ** 1000000000 # some large computation
end_time = time.time()
# TODO: change the line below to compute difference
difference = ???
# TODO: add a separator of '\n'
print(start_time, end_time, difference, ???)
# TODO: discuss - how can you use time() function to time your project code?
```
%% Cell type:code id: tags:
``` python
# TODO: call log10 function to determine log base 10 of 1000
# Recall that you cannot use math. when you use from style of import
# print(math.log10(1000)) #doesn't work
```
%% Cell type:code id: tags:
``` python
# TODO: can you access pi variable inside math module?
pi # TODO: discuss why this didn't work
# TODO: go back to the import cell and import math
# TODO: fix line 2, so that you are now able to access pi inside math module
```
%% Cell type:markdown id: tags:
## Learning Objectives
- Explain the syntax of a function header:
- def, ( ), :, tabbing, return
- Write a function with:
- correct header and indentation
- a return value (fruitful function) or without (void function)
- parameters that have default values
- Write a function knowing the difference in outcomes of print and return statements
- Explain how positional, keyword, and default arguments are copied into parameters
- Make function calls using positional, keyword, and default arguments and determine the result.
- Trace function invocations to determine control flow
%% Cell type:markdown id: tags:
## Example 1: Cube of a number
- Input: number (to be cubed)
- Output: cubed number
%% Cell type:code id: tags:
``` python
# TODO: Let's define the cube function
```
%% Cell type:code id: tags:
``` python
# Let's call cube function
print(cube(5))
# TODO: discuss what is different about the below line of code
print(cube(cube(2)))
```
%% Cell type:code id: tags:
``` python
# TODO: compute 4 cube + -3 cube
# version 1
# version 2
```
%% Cell type:code id: tags:
``` python
# TODO: compute 4 cube * -3 cube
# Now which one of the above two versions is better?
```
%% Cell type:code id: tags:
``` python
# Whenever you think you are going to reuse a function call's
# output, save it in a variable
# Rookie programmer mistake: calling the same function with the
# same arguments will always give the same return value
# Running the same function call twice takes twice the time
```
%% Cell type:markdown id: tags:
`return` vs `print`
- `return` enables us to send output from a function to the calling place
- default `return` value is `None`
- that means, when you don't have a `return` statement, `None` will be returned
- `print` function simply displays / prints something
- it cannot enable you to produce output from a function
%% Cell type:code id: tags:
``` python
# TODO: Go back to cube function defintion, change return to print
# Run the above function call cells to see what happens
```
%% Cell type:markdown id: tags:
## Tracing function invocations
- PythonTutor is a great tool to learn control flow
- Let's use PythonTutor to trace cube function invocation
- TODO: Copy-paste cube function defintion into PythonTutor (course website > tools > PythonTutor)
%% Cell type:markdown id: tags:
## Example 2: is_between(lower, num, upper)
- Purpose: check whether number is within the range of lower and upper (inclusive)
- Input: lower bound, number, upper bound
- Output: boolean value (`True` or `False`)
- Keyword: `pass`:
- placeholder statement
- you cannot run a cell with an empty function definition
%% Cell type:code id: tags:
``` python
def is_between(lower, num, upper):
pass
# you can call a function in the same cell that you defined it
print(is_between(3, 7, 21))
print(is_between(2, 14, 5))
print(is_between(100, cube(5), 200))
```
%% Cell type:markdown id: tags:
## Types of arguments
- positional
- keyword
- default
Python fills arguments in this order: positional, keyword,
%% Cell type:code id: tags:
``` python
def add3(x, y = 100, z = 100):
"""adds three numbers""" #documentation string
print ("x = " + str(x))
print ("y = " + str(y))
print ("z = " + str(z))
return x + y + z
sum = add3(100, 10, 5)
# TODO: 1. sum is a bad variable, discuss: why. What would be a better variable name?
# TODO: 2. what type of arguments are 100, 10, and 5?
```
%% Cell type:code id: tags:
``` python
print(add3(x = 1, z = 2, y = 5)) #TODO: what type of arguments are these?
```
%% Cell type:code id: tags:
``` python
add3(5, 6) # TODO: what type of argument gets filled for the parameter z?
```
%% Cell type:markdown id: tags:
Positional arguments need to be specified before keyword arguments.
%% Cell type:code id: tags:
``` python
# Incorrect function call
add3(z = 5, 2, 7)
# TODO: what category of error is this?
```
%% Cell type:markdown id: tags:
Similarly, parameters with default values should be defined after parameters without default values.
%% Cell type:code id: tags:
``` python
# Incorrect function definition
def add3_bad_version(x = 10, y, z):
"""adds three numbers""" #documentation string
print ("y = " + str(y))
return x + y + z
```
%% Cell type:markdown id: tags:
Python expects exactly same number of arguments as parameters.
%% Cell type:code id: tags:
``` python
# Incorrect function call
add3(5, 3, 10, x = 4)
# TODO: what category of error is this?
```
%% Cell type:code id: tags:
``` python
# TODO: will this function call work?
add3(y = 5, z = 10)
```
%% Cell type:code id: tags:
``` python
# TODO: will this function call work?
add3()
```
%% Cell type:markdown id: tags:
## Example 3: Generate a height x width grid
- Input: width, height, grid symbol, title of the grid
- Output: string containing title, a newline, and the grid
- Pseudocode steps:
1. Generate a single row of symb (width dimension). What string operator do you need?
2. Capture single row into a variable
3. Add newline to single row variable.
4. Generate multiple rows (height dimension). What string operator do you need?
5. Generate the output string to be returned by adding title with a newline with the output from step 4.
%% Cell type:code id: tags:
``` python
# TODO: how many parameters have default values in the below function?
def get_grid(width, height, symb = '#', title = 'My Grid:'):
row = symb * width
grid = (row + '\n') * height
return title + '\n' + grid
```
%% Cell type:code id: tags:
``` python
# TODO: generate various sized grids, by exploring
# three types of arguments
# Here is one example
print(get_grid(10, 8))
```
%% Cell type:code id: tags:
``` python
# TODO: use PythonTutor to trace get_grid function call
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
When you use keyword arguments, the order of the arguments need not match with the parameters.
This is because we tie the arguments to the parameters, by explicitly saying parameter = argument.
%% Cell type:code id: tags:
``` python
# TODO: Try using all keyword arguments and use different order than the order of the parameters.
```
%% Cell type:markdown id: tags:
### Revisiting `print` function
- Let's look at `help(print)` to learn about print's parameters
- Default value for `sep` is space, that is: " "
- Default value for `end` is newline, that is: "\n"
%% Cell type:code id: tags:
``` python
help(print)
```
%% Cell type:code id: tags:
``` python
# TODO: predict output, then run to validate your prediction
print(3 + 4, 3 < 4, "3" + "4", end = "....\n" ) # sep default is " "
print(3 + 4, 3 < 4, "3" + "4", sep = "\t" ) # end default is "\n"
```
%% Cell type:markdown id: tags:
## fruitful function versus void function
- fruitful function: returns something
- ex: add3
- void function: doesn't return anything
- ex: bad_add3_v1
%% Cell type:code id: tags:
``` python
# Example of void function
def bad_add3_v1(x, y, z):
pass
print(bad_add3_v1(4, 2, 1))
```
%% Cell type:code id: tags:
``` python
print(bad_add3_v1(4, 2, 1) ** 2) # Cannot apply mathematical operator to None
```
%% Cell type:markdown id: tags:
### `return` statement is final
- exactly *one* `return` statement gets executed for a function call
- immediately after encountering `return`, function execution terminates
%% Cell type:code id: tags:
``` python
def bad_add3_v2(x, y, z):
return x
return x + y + z # will never execute
bad_add3_v2(50, 60, 70)
```
%% Cell type:markdown id: tags:
Default return type from a function is None.
None is a special type in Python (similar to null in Java).
%% Cell type:markdown id: tags:
### Trace this example
- manually
- then use PythonTutor
%% Cell type:code id: tags:
``` python
def func_c():
print("C")
def func_b():
print("B1")
func_c()
print("B2")
def func_a():
print("A1")
func_b()
print("A2")
func_a()
```
File deleted
File deleted
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment