Call a Function
After a function is defined, you can use it from outside the function by calling it's name followed by the parenthesis with necessary input argument values.
function_name(p1_value, p2_value...)`
Actually we've been using this already. When we need to run the code in a function, we need to do function call. Function call contains the name of the function to be executed followed by a list of values, called arguments, which are assigned to the parameters in the function definition.
Using the specified function name anywhere in your program and any number of times, you can run that block of code.
Call the Function directly to run the code in it.
After the function definition, we call the function say_hi()
to run it:
def say_hi():
print('Hi!')
say_hi()
The last line is not indented means this is out of the function already, we simply type the function name with the empty parenthesis since this function has no input arguments. By clicking the run button, we can see the result is displayed in the code console:
Hi!
Call the function in some lines of codes
Let's continue with the above lines,
for t in range(3):
print(t)
say_hi()
Console result:
1
Hi!
2
Hi!
3
Hi!
These few lines of statements use for
loop to call the function say_hi()
3 times: at t=0,1,2
, each time t
is printed out before calling say_hi()
, so the console shows the above message.
We can call the function say_hi()
in another function definition:
# continue with the above lines
def say_morning():
say_hi()
print('Good morning!')
say_morning() # call the function
Here we start to define another function say_morning()
, in this function there are two lines of statements: call function say_hi()
and print another message. no more indented lines after print
, so this is the end of function say_morning()
.
Next we call the function say_morning()
on the last line with no indention, click run
, the codes in the function body first execute another function say_hi()
, then execute next print
statement, see the result in the console:
Hi!
Good morning!
Exercise:
Please define a function, sing()
, call this function to print out a message: Happy birthday to you!
def sing():
print('Happy birthday to you!`)
# call function
sing()