Functions in Python

A function is a simple way to tell a computer what to do. Here's an example:

print('hello')

When we call (run) the print function above, we see:

hello

printed to the screen.

Let's Create A Function

We can define (create) our own functions in Python. Here's an example:

def print_animals():
    print('dog')
    print('cat')
    print('fish')

Now that we've defined the function, let's call it twice:

print_animals()
print_animals()

The result is:

dog
cat
fish
dog
cat
fish

What is a Parameter?

Let's create a function and send it numbers to print:

def print_number(num):
    print(num)

print_number(1)
print_number(2)
print_number(3)

Above, num is a parameter. A parameter is a value we send to the function.

The result is:

1
2
3

What is a Return Value?

We can send values to functions, and functions can send values back:

def addnumbers(x, y):
    return x + y

num = addnumbers(1,2)
print(num)

The result of running this is:

3

Next: Classes in Python

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.