To create a function in Python, you can follow these steps:
Start by using the def
keyword, followed by the name of your function. It is common practice to use lowercase letters and underscores for function names.
Add parentheses after the function name, which can optionally contain parameters inside them. Parameters are variables that you pass to the function for it to use in its calculations. If there are no parameters, use empty parentheses.
Add a colon (:
) at the end of the function signature to indicate the start of the function body.
Indent the next lines with four spaces or a tab character. This indentation is necessary for Python to understand which lines of code are part of the function.
Write the code that you want the function to execute. This can include variable assignments, conditionals, loops, and any other valid Python code.
Optionally, use the return
statement to specify the value that the function should output. If you don't use return
, the function will implicitly return None
.
Here is an example of a simple function that adds two numbers and returns the result:
def add_numbers(a, b):
sum = a + b
return sum
Once you define your function, you can call it from other parts of your code by using its name followed by parentheses and the necessary arguments. For example:
result = add_numbers(4, 7)
print(result) # Output: 11