In Python, a function is defined using the def
keyword, followed by the name of the function, and then a set of parentheses ()
. Inside the parentheses, you can specify any input parameters that the function will take (also called arguments or inputs). The code block for the function is then indented underneath the function definition, using a colon :
. Here is an example of a simple function in Python:
def say_hello(name): print("Hello, " + name + "!")
In this example, the function is named say_hello
, and it takes one input parameter name
. The function simply prints out a string that includes the value of the name
parameter.
You can call this function by passing a value to the name parameter like:
say_hello("John")
You can also return a value from a function by using the return
keyword. Here is an example of a function that takes two input parameters and returns their sum:
def add_numbers(a, b):
return a + b
You can call this function by passing two arguments like:
result = add_numbers(2, 3)
The value of the result
variable will be 5
.
Social Plugin