User Tools

Site Tools


functions

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)

Part 1: What's a function? Making functions

Start Code

Show this to the students. Does it work? What do we need to do?

x = 5
y = 3

a = add(x, y)
s = sub(x. y)
m = mul(x, y)
d = div(x, y)

print(a, s, m, d)

Mid Code

Writing the four functions

End Code

adding idiv(), irem()

Part 2: Refactoring a rot13 program

Start Code

We start here, and the journey is to refine the code and learn about functions as we move towards the end code.

a = "hello"

for c in a:
    i = ord(c)

    # upper case
    if i >= 65 and i <= 90:
        i = i + 13
        if i > 90:
            i = i - 26
            
    # lower case
    if i >= 96 and i <= 122:
        i = i + 13
        if i > 122:
            i = i - 26

    print(b, end='')

End Code

def main():
    a = input("Enter the code: ")

    while a != "end":
        print(rot13(a))

        print("")
        a = input("Enter the next code: ")

def rot13(a):
    r = ""
    for c in a:
        r += rot13_letter(c)

    return r

def rot13_letter(c):
    i = ord(c)

    # capital letters
    if is_letter(c):
        i = i + 13
        if not is_letter(chr(i)):
            i = i - 26

    return  chr(i)

def is_letter(c):
    i = ord(c)
    if i >=65 and i <= 90:
        return True

    elif i >= 96 and i <= 122:
        return True

    else:
        return False

if __name__ == '__main__':
    main()
    

Part 3: 3n+1 example

Now the students must do things on their own.

Start Code


n = 10

while n > 1:

    if n % 2 == 0:
        # Even
        n = n // 2
    else:
        # Odd
        n = 3 * n + 1

        print(str(n))

if __name__ == '__main__':
    main()

End Code

def main():
    n = input("Please enter a number: ")
    n = int(n)
    c = 0

    print("Start: " + str(n), end = '')

    while n > 1:
        print(', ', end = '')
        c = c + 1
        if c % 10 == 0:
            print("")

        if n % 2 == 0:
            n = n // 2      # Even
        else:
            n = 3 * n + 1   # Odd

        print(str(n), end = '')

    print(".")
    print(f"There were {c} numbers.")

if __name__ == '__main__':
    main()
functions.txt · Last modified: 2024/10/20 07:45 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki