User Tools

Site Tools


functions

Functions

  • Today I will do a lesson on 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.txt · Last modified: 2023/11/03 06:27 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki