create a function in python

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.py
def greet(name):
    print("Hello, " + name + ". Nice to meet you!")

#calling the function
greet("John")
106 chars
6 lines

Output:

main.py
Hello, John. Nice to meet you!
31 chars
2 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.py
def add(x, y):
    return x + y

#calling the function
result = add(3, 5)
print(result)
88 chars
7 lines

Output:

main.py
8
2 chars
2 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