Basic Functions
Functions¶
A function takes inputs and then runs some code given these inputs. The format of defining a function is:
def function_name(arguments):
execute code
In our first example we are going to not use any arguments to simply things. Notice we are once again using tabs to denote what is in the function. We start by using the function name of hello_world, and making it so our function just simply prints the string hello world.
#The way to define a function is def followed by a function name with parentheses and a colon
#Then indent anything within the function
def say_hello():
print("Hello World")
Once we have defined a function, we can run it by calling the function followed by parentheses with any arguments. In our first function we do not have arguments so it is simply called like below.
#You can then call it using that same name
say_hello()
Arguments¶
For a function, we can define what arguments need to be passed within the parentheses. In this case, we are now going to name our function say_something, and we will ask for one argument word. Then we can print out this argument word.
#You can also add a argument. In this case we ask for a word then we print the word in the code
def say_something(word):
print(word)
By giving the string "Hi", our function prints out hi.
#So now, we give the argument "Hi" and it gets printed out
say_something("Hi")
With another argument, we get a different result.
#Or give it another argument!
say_something("Something")
You can use more than one argument, so if you want a function which prints out the sum of two arguments a and b, you need to have a followed by a comma and then b in the function definition.
#We can have more than one argument, for example a and b
def add(a, b):
print(a + b)
add(1,2)
Return¶
In a function, return acts as a way to get the value back from the function. When return is called in a function it will end that function even if there is more code after it. Below we change the print statement to be a return of the sum. Then we can capture the return value in a variable c
#Using return gives back the sum
def add(a, b):
return a + b
#Run the add function and capture the value in c
c = add(1, 2)
#Print the value for c
print(c)
Example¶
Combining if statements with a function we can build a function to compare which of two values is greater.
#Example: A function to print out which number is greater
def greater(a, b):
if a > b:
print("a is greater than b")
elif b > a:
print("b is greater than a")
else:
print("a and b are equal")
#Run the function with different arguments
greater(1,2)
greater(3,2)
greater(2,2)