How to Define a Function in Python: Syntax and Examples
In Python, you define a function using the
def keyword followed by the function name and parentheses (). Inside the parentheses, you can add parameters, and the function code is indented below. Use return to send back a result from the function.Syntax
A Python function starts with the def keyword, followed by the function name and parentheses (). Inside the parentheses, you can list parameters separated by commas. The function body is indented and contains the code to run. Optionally, use return to send a value back.
- def: keyword to define a function
- function_name: the name you choose for your function
- parameters: inputs the function can accept (optional)
- :: colon to start the function body
- indented code: the instructions the function performs
- return: sends a result back to the caller (optional)
python
def function_name(parameters): # code block return result
Example
This example defines a function named greet that takes a name parameter and prints a greeting message. It shows how to call the function with an argument.
python
def greet(name): print(f"Hello, {name}!") greet("Alice")
Output
Hello, Alice!
Common Pitfalls
Common mistakes when defining functions include forgetting the colon : after the parentheses, not indenting the function body, or missing parentheses when calling the function. Also, using return incorrectly or forgetting it when you want to send back a value can cause issues.
python
# Wrong: missing colon # def say_hello() # print("Hi") # Correct: def say_hello(): print("Hi") # Wrong: no parentheses when calling # say_hello # Correct: say_hello()
Output
Hi
Quick Reference
Remember these tips when defining functions:
- Always use
defand a colon:. - Indent the function body consistently (usually 4 spaces).
- Use descriptive function names.
- Use
returnto send back values if needed. - Call functions with parentheses, even if no parameters.
Key Takeaways
Use the def keyword followed by the function name and parentheses to define a function.
Indent the function code under the definition and use a colon after the parentheses.
Use return to send a result back from the function if needed.
Always call functions with parentheses, even if they take no parameters.
Avoid common mistakes like missing colons, wrong indentation, or forgetting parentheses.