More Functions
Table of Contents
yeah this is just functions… but more.
1. other stuff to know
- incremental development
- function stubs = function definitions that haven’t been implemented yet.
- useful when outlining your program and figuring out what sort of functions you want to use.
- use the pass keyword, which doesn’t do anything except act as a placeholder until you implement a function.
- here are a few examples of function stubs:
# function stub: def greeting(): pass # can still have multiple arguments in function stub: def another_greeting(hello, world): pass # doesn't do anything when called: greeting() another_greeting(0, 1)
- functions are objects.
- technically everything is an object, but you’ll learn more about that later.
2. typing, but dynamic
- example: adding together different types.
- adding two numbers.
- concatenating two strings.
- polymorphism = an operation/method/function that can be used on different data types.
- here is an example that demonstrates polymorphism:
# add function demonstrates polymorphism: def add(x, y): return x + y print(add(1, 2)) print(add("Hello ", "World!"))
3 Hello World!
- Python uses dynamic typing.
- dynamic typing = when interpreter figures out data types of objects during runtime.
- static typing = when variables and function parameters must have type definitions so that the compiler can figure out valid tasks during compile time.
- C, C++, and Java make use of static typing.
3. more arguments
- keyword arguments = mapping arguments to parameters by name when calling a function.
- allow for better readability and clarity if your function requires many arguments.
- if mixed with positional arguments, then keyword arguments must come last.
- An error occurs if all positional or keyword arguments aren’t listed in the function call.
- here is an example of using keyword arguments:
def print_student(name, age, major): print(f"{name} is {age} years old and their major is {major}.") # keyword arguments can be in order: print_student(name="Alice", age=20, major="Psychology") # or out of order: print_student(name="Bob", age=19, major="Computer Science") # not supplying all positional or keyword arguments results in a TypeError: try: print_student("Alice", 21) except TypeError as te: print(f"Error: {te}")
Alice is 20 years old and their major is Psychology. Bob is 19 years old and their major is Computer Science. Error: print_student() missing 1 required positional argument: 'major'
- default parameter values = allows programmer to specify a default value if an argument is not passed to the parameter.
- the function call doesn’t need to have this argument, and if so, the default value will be assigned to the parameter instead.
- should not have a mutable object (such as a list) as a default parameter.
- the same mutable object will continue to be modified for every call to the function rather than a separate copy being generated for each function call.
- here are a few examples of using default parameter values:
# default parameter value: def greeting(name, greeting_word="Hello"): print(f"{greeting_word}, {name}!") # can call the function with all arguments. greeting("Alice", "Good evening") # only required arguments, using "Hello" as the default greeting word greeting("Bob")
Good evening, Alice! Hello, Bob!
# using mutable object as default parameter def add_item(item, a_list=[]): a_list.append(item) return a_list # if a new list were created each time, we would expect the output to be: # ["apples"] # ["bananas"] # ["carrots"] print(add_item("apples")) print(add_item("bananas")) print(add_item("carrots")) # instead, a different output is produced because each # item is appended to the same default list.
['apples'] ['apples', 'bananas'] ['apples', 'bananas', 'carrots']
- *args parameter = takes optional positional parameters and passes them into the function as an arbitrary argument list.
- useful when you may not know how many arguments a function needs.
- here is an example of using the *args parameter:
# function with args # calculates the sum of an arbitrary number of number arguments. def numbers_sum(*args): result = 0 for num in args: result += num return result print(numbers_sum(1, 2, 3)) print(numbers_sum(100, 200, 300, 400, 500)) print(numbers_sum())
6 1500 0
- **kwargs parameter = similar to *args, takes optional keyword arguments and passes them into the function as a dictionary.
- the keys are the parameter names and the values are the values assigned to each of the parameter names.
- here is an example of using the **kwargs parameter:
# function with kwargs # prints out the keys and values of an arbitrary number of keyword arguments. def print_dict(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_dict(name="Alice", age=100, major="English") # separator for clarity: print("-------------------------------------------") print_dict(a="1", b="2", c="3", d="4", e="5")
name: Alice age: 100 major: English ------------------------------------------- a: 1 b: 2 c: 3 d: 4 e: 5
- the asterisks (* and **) are necessary, but they don’t have to be named “args” and “kwargs”
- you can use any variable names, but the typical convention is to use “args” and “kwargs” for arbitrary optional arguments and keyword arguments, respectively.
- aside: unpacking
- allows you to assign multiple variables to values in a tuple or list.
- typically used if your function returns a tuple of values and you want to assign each value to a different variable.
- here are a few unpacking examples:
# can unpack a tuple coordinates = (3, 4, 5) x, y, z = coordinates print(x, y, z) # or a list colors = ["red", "yellow", "blue"] color1, color2, color3 = colors print(color1, color2, color3) # can use unpacking to simultaneously swap the values of two variables # (very useful for sorting a list with a for loop) a = 100 b = 200 a, b = b, a # a = 200 # b = 100 print(a, b)
3 4 5 red yellow blue 200 100
# you can also unpack a function if it returns multiple values in a tuple or list: def alices_personal_info(): return "Alice", 200, "Undeclared" name, age, major = alices_personal_info() print(name) print(age) print(major)
Alice 200 Undeclared
4. asserts, but post-condition
- expected output after providing certain inputs.
- should provide just enough post-condition asserts to cover all the output possibilities.
- can be used for test-driven development.
- here’s an example of using post-condition asserts (alongside pre-condition asserts) in a function:
# post-condition asserts def rectangle_area(length, width): assert type(length) in (int, float), "length must be type int or float" assert type(width) in (int, float), "width must be type int or float" assert length > 0, "length must be positive" assert width > 0, "width must be positive" area = length * width # before returning the area to the user, we can use post-condition # asserts to verify that the output is correct. assert area > 0, "area must be positive" assert area == length * width, "area was calculated incorrectly" return area # works as intended print(rectangle_area(5, 10)) # this will raise an AssertionError since one of the arguments is negative try: print(rectangle_area(2, -3)) except AssertionError as ae: print(f"Error: {ae}")
50 Error: width must be positive
5. exception handling
- used to handle unexpected errors during execution.
- code that may cause an exception/error is placed in a try block.
- if the code raises a specific exception, then the except block is executed.
- you’ve already seen some try-except blocks throughout this reading, but here’s another example:
# exception handling using try-except blocks def divide(top, bottom): try: result = top / bottom print(result) except ZeroDivisionError: print("Error: cannot divide by 0") except TypeError: print("Error: invalid input type for division") # valid divide(10, 2) # invalid divide(5, 0) # invalid divide("hello", "world")
5.0 Error: cannot divide by 0 Error: invalid input type for division