Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
Functions
What are Functions?
Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code.
How do you write functions in Python?
As we have seen on previous tutorials, Python makes use of blocks.
A block is a area of code of written in the format of:
Where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while".
Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
Functions may also receive arguments (variables passed from the caller to the function). For example:
Functions may return a value to the caller, using the keyword- 'return' . For example:
How do you call functions in Python?
Simply write the function's name followed by (), placing any required arguments within the brackets. For example, lets call the functions written above (in the previous example):
Exercise
In this exercise you'll use an existing function, and while adding your own to create a fully functional program.
-
Add a function named
list_benefits()
that returns the following list of strings: "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together" -
Add a function named
build_sentence(info)
which receives a single argument containing a string and returns a sentence starting with the given string and ending with the string " is a benefit of functions!" -
Run and see all the functions work together!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
