Chapter 1 – Introduction to Python with Zumis
1.5 – Functions
Functions are blocks of code that can be given a name and employed multiple times within a program to execute specific operations. They can be beneficial in streamlining code and enhancing the efficiency of debugging. You have already implemented Zumi’s functions by commanding Zumi to move forward or backward. However, did you know that you can create your own custom functions?
Step 1: What is a function?
In programming, a function is a self-contained block of code that can be assigned a name and called upon repeatedly throughout a program to perform specific tasks. Functions help summarize multiple pieces of code into one name. Some functions that we have already been introduced to are zumi.forward() and zumi.reverse(). However we can start making our own.
Step 2: Defining a function
To define a function in Python, first write def, then the name of the function followed by a colon, then write the code that you want to execute. In this case, we are printing a message, and since it is a string, it needs the quotation marks. Also, make sure to include the indentation.
def greet_user():
print("Hello")
Now, we can use the function by calling it as shown.
greet_user() # Call the function
The result will be: Hello
Step 3: Defining functions with parameters
Now to make functions return a different result as needed, such as greeting multiple users where their name is needed, we can pass in parameters.
def greet_user(name):
print("Hello", name)
Calling function:
greet_user("Zumi")
The result will be: Hello Zumi
Now suppose that we pass a number as a parameter
greet_user(1234):
The result will be: Hello 1234
Step 4: Multiple parameters
We can also pass in multiple parameters. Let’s say you want to create a function that adds 2 numbers.
def add(x, y):
print(x+y)
Calling the function:
add(1, 2)
The result will be: 3
Activity
Create a function that drives the Zumi in a square.
Hint
: Import libraries and create the Zumi Object, then define a function called my_square. After writing the code for the function, call the function. Also, when turning, always turn right.
#
#
#
Solution
from zumi.zumi import Zumi
zumi = zumi()
def my_square():
zumi.forward()
zumi.turn_right()
zumi.forward()
zumi.turn_right()
zumi.forward()
zumi.turn_right()
zumi.forward()
zumi.turn_right()
my_square() # calling function
Conclusion:
Congratulations, you can start using Functions in Python!
Demo Video
Questions