Defining Functions
We have already encountered some functions in Python. For example: print()
for output, len()
for the length of an array, str()
for conversion to text, etc. These functions were created for us. We just used them. Now we will look at how to create such a function.
We create (define) a function in Python using the def
keyword, followed by the name of the function, parentheses, and a colon. This is called the function header. For example:
def myFunction():
After the function header, we write the body of the function, which is indented similarly to if
or while
blocks of code. The body of the function contains the statements we want the function to execute. For example:
def myFunction():
print("This is my function")
This creates a function that, when called (or executed), prints This is my function
.
Instructions
Create a function named firstFunction
that in its body prints: "This is my first function!"
.
Start programming for free
2/7