Python Functions
Learn all about Python Functions in this comprehensive tutorial.
- •A function is a block of code which only runs when it is called.
- •In Python, a function is defined using the def keyword, followed by a function name and parentheses:
- •To call a function, write its name followed by parentheses:
- •Function names follow the same rules as variable names in Python:
- •Imagine you need to convert temperatures from Fahrenheit to Celsius several times in your program.
- •Functions can send data back to the code that called them using the return statement.
- •Function definitions cannot be empty.
Python Functions
A function is a block of code which only runs when it is called.
A function can return data as a result.
A function helps avoiding code repetition.
Creating a Function
In Python, a function is defined using the def keyword, followed by a function name and parentheses:
This creates a function named my_function that prints "Hello from a function" when called.
Calling a Function
To call a function, write its name followed by parentheses:
You can call the same function multiple times:
Function Names
Function names follow the same rules as variable names in Python:
- A function name must start with a letter or underscore
- A function name can only contain letters, numbers, and underscores
- Function names are case-sensitive (myFunction and myfunction are different)
Why Use Functions?
Imagine you need to convert temperatures from Fahrenheit to Celsius several times in your program. Without functions, you would have to write the same calculation code repeatedly:
With functions, you write the code once and reuse it:
Return Values
Functions can send data back to the code that called them using the return statement.
When a function reaches a return statement, it stops executing and sends the result back:
You can use the returned value directly:
The pass Statement
Function definitions cannot be empty. If you need to create a function placeholder without any code, use the pass statement:
The pass statement is often used when developing, allowing you to define the structure first and implement details later.
Module quiz
2 questionsWhich of the following is true about Python Functions?
What is the most common pitfall when working with Python Functions?
Answer all questions to submit.