To create a function in Python, use the def
keyword followed by the function name and parameter(s) within parentheses. The code block within the function will be executed when the function is called.
Here's an example:
main.py106 chars6 lines
Output:
main.py31 chars2 lines
In this example, greet
is the name of the function and name
is the parameter passed into the function. When the function is called with greet("John")
, the value "John"
is passed as an argument to the name
parameter, and the code block within the function is executed, printing "Hello, John. Nice to meet you!".
You can also return a value from a function using the return
keyword:
main.py88 chars7 lines
Output:
main.py2 chars2 lines
In this example, the add
function takes two parameters, x
and y
, and returns their sum. When the function is called with add(3, 5)
, the return
statement returns the value 8
, which is then assigned to result
and printed.
gistlibby LogSnag