Python #4: User-defined Functions

Last post we went over built-in functions like ‘print’, ‘len’, and ‘min’. There are also user-defined functions we can use to do what we want.

def f(x):
    result = x+2
    return result

print(f(1))
print(f(2))
print(f(10))

Output: 
3
4
12

So the ‘def’ is the keyword for ‘define’. After you define the function and assign it to a parameter (the x), you can pair the function with any value you want like you see in the 3 prints.

That parameter ‘x’ is the variable of a function, but not the exact same as a regular variable like we went over. They are both used to store values. I know it’s not strictly used for that but it seems like a parameter’s main purpose is to save you from constantly redefining a regular variable.

def h(a, b):
    result = a + b
    return result

print(h(1, 2))
print(h(5, 7))

Output:
3
12

In this code we use ‘h’ as the function. It doesn’t have to be ‘f’, it’s just formal to do it like that.

Again, the ‘a’ and ‘b’ are parameters of this function, and the result will add them together. Just how you see in the prints, you can assign any values to that ‘a’ and ‘b’ and the function will do the adding for you. This is much more efficient than like we did for the first ever variable I showed yall:

whatever = 25
print(whatever)

That’s cool for that one number, but if I wanted to redefine that, I’d have to write it again to override it. This gets time-consuming when dealing with complex code.

def h(a, b):
    result = a + b
    return result
    print("word")

print(h(1, 2))
print(h(5, 7))

Output:
3
12

Back to the functions. The ‘result’ and ‘return’ are indented to tell the system they’re a part of the function. The ‘print’ at the end isn’t necessary, but I put it there to show that it wouldn’t show in the output because it’s under the ‘return’. The code follows an order of execution. It will not acknowledge anything that comes after that return. So keep that in mind as you go on.

And to clear this up, ‘print’ is only meant to directly show a value on the screen. ‘Return’ closes out the function and tells it to store those values as is. You see I still have to print the function despite having the return.

I’ll have to come back over this to understand functions better. It’s getting tough but I can’t just glaze over it.

Leave a comment