Create a Function With Python 3

Writing code is all about efficiency and adoption of DRY (don’t repeat yourself), and functions are essential components to these concepts.

With Python, we can create functions that take variables and functions that doesn’t take variables, as you will see shortly.

In the following code example, we will create two functions. The first takes two variables and print them (you can do anything with them). The second function doesn’t take variables and print text (again, we can do anything inside the function).

Note: When creating a function, we need to ident the code with four spaces after the function definition (def).

# Function with variables 
def myfunction (x, y):
    print(f"Var 1 is: {x} and var 2 is: {y}")

# Function without variables
def myfunction2():
    print ("Just a function without variables")

# Call the functions
myfunction (20,10 )

To test the functions, save the file and run it:


The output should look like this:

Var 1 is: 20 and var 2 is: 10
Just a function without variables

Leave a comment

Your email address will not be published.