Intro to Python
Copy doc
Learn Python
Functions
This section covers:
Functions
A
function
is a group of statements that together do a particular task. Functions help to organize, reuse, and clarify our code.

Syntax of a function

def double(number):
doubled = number * 2
return doubled

the
def
keyword marks the beginning of a function definition
double
is the name of the function, which must be unique within the program
number
is the function’s parameter; functions can have any number of parameters (including none)
the indented statements are the body of the function

Calling a function

After you define a function, you can use it by calling it, which requires the function name with the correct number of parameters.
x = 10
y = double(x)

Return statement

If a
return
statement is reached when evaluating a function, then the function ends. Optionally, the
return
statement can specify an expression.

In the example above,
return doubled
is specifying the variable
doubled
as its return expression. When the
double
function is called, it will evaluate to that return expression.

If there’s no return expression, then the function call will return
None
.
def deposit_money(amount):
if amount <= 0:
return
print("Depositing $" + str(amount))

deposit_money(100)
deposit_money(-10)
Task
Status
1
Learn about functions
Not Started
No results from filter

Next Section ➡️


Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.