2️⃣

11.2 Defining Functions

Defining Functions

Functions are blocks of code that can be used as many times as you want. They execute certain pieces of code.

When you write code for a function, that’s called defining a function. When you define a function, you need to use the def keyword along with the function name and parameters (if any):

def scoop_ice_cream():
	# write function body here
View this code on GitHub

Remember that indentation matters in Python! Anything that is in the function body should be indented by one level to the right, relative to the function header.

Also, be aware that the flavor parameter is basically a variable that you can use inside of your function. The value of that variable depends on whatever the programmer passes into it.

🚨

However, be careful not to use the flavor variable outside of the function. The scope of the variable is limited to only within the function body. (Scope is a fancy word for the region of the code where the variable can be used.)

Calling Functions

Defining functions is great, but how do you actually use them? In the programming world, we say that we "call" a function when we use it. To call a function, simply use its name and its parameters (which you'll learn later):

# defining the function
def scoop_ice_cream():
	# write function body here

# calling the function
scoop_ice_cream()
View this code on GitHub

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.