Functions¶
Writing functions are an important aspect of programming. Writing functions helps automate redundant tasks and create more reusable code. Defining functions in python is easy. Let’s write a function that raises a number to a power. (This is unnecessary of course.) Don’t forget the colon.
def pow(x, n = 2):
return x ** n
print(pow(5, 3))125
Note our function has a mandatory arugment, x, and an optional arugment, n, that takes the default value 2. Consider this example
to think about how python evaluates function arguments. These are all the same.
print(pow(3, 2))
print(pow(x = 3, n = 2))
print(pow(n = 2, x = 3))
#pow(n = 2, 3) this returns an error, the second position is n, but it's a named argument too9
9
9
You can look here, https://
def concat(*args, sep="/"):
return sep.join(args)
print(concat("a", "b", "c"))
print(concat("a", "b", "c", sep = ":"))a/b/c
a:b:c
Lambda can be used to create short, unnamed functions. This has a lot of uses that we’ll see later.
f = lambda x: x ** 2
print(f(5))
25
Here’s an example useage where we use lambda to make specific “raise to the power” functions.
def makepow(n):
return lambda x: x ** n
square = makepow(2)
print(square(3))
cube = makepow(3)
print(cube(2))
9
8