functions
This is an old revision of the document!
Table of Contents
Functions
- Today I will do a lesson on functions.
Note: This lesson might even be skipped, given that pyhang does not require functions.
Functions
- What is a function?
- Benefits of functions?
- How are functions used?
- How to make a function (see examples below)
Code Example
- Here is an example:
def main(): x = 5 y = 12 z = add(x, y) print(z) def add(a, b): c = a + b return c if __name__ == "__main__": main()
- There are three parts.
- One, “def main()” creates the main() function.
- Two, “def add(a, b)” creates a function with two arguments, or, parameters.
- Three, “if name == main….” means, to run the “main” function first.
So you see, you can use the add() function to add numbers.
Homework
- Classwork/Hommework: Students must:
- Write a function to multiply two numbers.
- Write a function to divide two numbers.
- Write a function to subtract two numbers.
- Test the program! (How do you test? use print() to show the answer.)
Advanced
Is this too easy? Here are some more challenging questions:
- Write a function that returns a random number.
- Write a function that returns a random fruit name.
or maybe,
- Write a function that prints “even” or “odd” if the number is even or odd.
Example answer!
def isEven(a): x = a // 2 #NOTE: / always returns a float. // always returns the lowest integer! if a == x: return "even" else: return "odd"
There are many, many ways to do this. The students should be able to think of at least this:
Example answer 2!
def isEven(a): while a >= 2: a = a - 2 if a == 0: print("even") else: print("odd")
If this challenge is too easy, they can always write a function that determines if a number is prime.
functions.1722211759.txt.gz · Last modified: 2024/07/29 00:09 by appledog