Python/Functions
< Python
Objective![]()
|
LessonFunctionsA function is a way of reusing a block of code so that it can be used more than once. Functions give the programmer the ability to reduce code redundancy and eliminate hours of wasted work. It also allows the code to be centralized, where one change to the function will effect everything that depends on it. Functions can be used to divide and conquer tasks that would seem otherwise impossible to accomplish! Creating A FunctionTo create a function, it must be defined with the def hello():
print("Hello, world!")
The code above assigns and creates the function called Now that you've created the function nothing should visibly happen. To actually invoke or call the function, you'll need to use the function's name followed by the followed by the parentheses like demonstrated in the script below. def hello():
print("Hello, world!")
hello()
The output should be: Hello, world! Adding the command Function ParametersAt this point, you might be wondering why we need to have those pointless parentheses when we call the function. Wouldn't def square(x):
print(x**2)
square(2)
square(3)
square(4)
The following output should be: 4 9 16
def square(x):
print(x**2)
square(2)
square(3)
square(4)
print(x) # x doesn't exist outside of square!
A function can take multiple arguments, each separated by a comma if more than one exists as demonstrated in the next example. def somemath(x, y):
print((x**2)+y)
square(2, 3)
square(3, 2)
The following output should be: 7 11 Default ParametersHaving parameters is great, but it can be repetitive to continue to use them over and over, again. We can define a default value for a parameter by setting its value when you define the parameter. Take the script below for example. def woof(x=0):
print(x)
woof(1)
woof()
woof(23)
The output should be: 1 0 23 Did you see the second time we called Returning A ValueIf we wanted to use the value that the square function gives us, we would rewrite it make use of the return command. >>> def square(x):
... return x**2
...
Which can then be used to do such fun things as: >>> print(square(3))
9
or >>> print(square(square(3)))
81
or even in statements such as: >>> 10 + square(2)
14
and >>> y = square(10)
>>> y
100
|
Assignments![]() |
|