Your browser does not support JavaScript!
Upvotes Anonymous 1 User 0

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
Was this helpful?

Tags

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License