0% found this document useful (0 votes)
3 views7 pages

Functions

The document explains the concept of functions in programming, emphasizing the DRY principle to avoid code repetition. It covers how to define and call functions, the difference between parameters and arguments, and the use of the return keyword for output. Additionally, it discusses variable scope, distinguishing between local and global variables.

Uploaded by

pearlthuli5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Functions

The document explains the concept of functions in programming, emphasizing the DRY principle to avoid code repetition. It covers how to define and call functions, the difference between parameters and arguments, and the use of the return keyword for output. Additionally, it discusses variable scope, distinguishing between local and global variables.

Uploaded by

pearlthuli5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# Functions

As our code gets longer and longer, you might find yourself copying and pasting a particular
code block in different parts of the program. That's no good!

“Don't Repeat Yourself” (DRY) is a principle in software development aimed at reducing


repetition and writing good clean code. Functions play a big part.

A function is a reusable block of code that performs a specific task. To execute this block of
code, you just need to write the function's name, followed by a pair of parenthesis ( ).

Whether the task is five or twenty lines of code, you can throw it in a function and use it
later anywhere in your program. It takes a little more effort initially but will save you a lot of
time in the long term.

Plot twist! In this course, we have been using functions all along.

Built-in functions are 68 functions that come with the Python interpreter available for use.
Here are some that you might recognize:

• print()

• input()

• len()

We've used them before, but didn't get into how they work behind the scenes.
And that's okay! This is the beautiful part about built-in functions. Like a car, you don't need
to know what's underneath the hood to operate it.

Let's look at some built-in Python functions!

# Define a Function

So how do we create a function from scratch?

User-defined functions are functions we define ourselves to do a specific task, and it's a two-
step process: 1️) define and 2️) call.

To define a function, we need a function definition. A function definition begins with


the def keyword, followed by the function name, a set of parentheses, and a colon, in that
order.

Here’s what a function definition looks like:

def name():

# The code inside

• The def keyword.

• The function name, followed by a pair of parentheses ().

• The colon :.

The code inside the function is called the body of the function. And just like if statements
and while loops, the code inside a function must be indented.

Note: The common naming convention for functions is snake_case.

Suppose we want to create a function named say_hello():

def say_hello():

print('Howdy! ')

print('How are you?')

We just defined a function that prints out two greetings!

Defining a function creates the function, and it's the first step, but it doesn't mean that
Python will automatically run the code inside its body. How do we convey to Python that we
want the function body executed?

We need to call the function!

# Call a Function
To call a function, we use the function name followed by parentheses somewhere in the
code:

def say_hello():

print('Howdy! ')

print('How are you?')

say_hello()

This executes the say_hello() function once!

So the output would be:

Howdy!

How are you?

We can also call a function numerous times. For example:

def say_hello():

print('Howdy! ')

print('How are you?')

say_hello()

say_hello()

say_hello()

This executes the say_hello() function three times!

So the output would be:

Howdy!

How are you?

Howdy!

How are you?

Howdy!

How are you?

Now it’s your turn to define and call a function in a program!


# Parameters and Arguments

So far, the functions we've created don't take in any input(s), which means they do the same
thing each time they get called. A function can be far more useful than that!

Sometimes, we want our functions to perform a specific task, but the task varies depending
on different input(s). And that's where parameters come in.

Parameters are just a fancy word for input. They are variables that a functions takes in. They
go inside the parentheses in the function definition and are used inside the function.

For example, suppose we define and call a happy_birthday() function like so:

def happy_birthday():

print('Happy birthday to you')

print('Happy birthday to you')

print('Happy birthday dear friend')

print('Happy birthday to you')

happy_birthday()

This prints out the same thing every time.

Let's say we want to make the song more personalized. For example, say the person's name
instead of just “dear friend”, then we can do this:

def happy_birthday(name):

print('Happy birthday to you')

print('Happy birthday to you')

print('Happy birthday dear ' + name )

print('Happy birthday to you')

Here, we gave the happy_birthday() function a name parameter for the function to take in.
So we can use the name variable within the function body.

And later in the program, when we call the happy_birthday() function, we can add an
argument in the call.

An argument is the value sent to the function when the function is called.

happy_birthday('Lillian')

The output would be:


Happy birthday to you

Happy birthday to you

Happy birthday dear Lillian

Happy birthday to you

So what's the difference between a parameter and an argument? Why are there two words
for what seems like the same thing?

• The parameter is the variable listed inside the parenthesis in the function definition
(when we define the function).

• The argument is the value sent to the function (when we call the function).

In the example above, the variable name is the parameter, and the value 'Lillian' is the
argument.

By the way, we’ve already been using arguments all along, when calling the print() function
for instance. In a print('Yo!'), the 'Yo!' is the argument.

# Return Value

We learned that functions can take in inputs, but did you know that functions can also have
outputs? In fact, every Python function has an output!

The return keyword is used to terminate a function and output a value:

def function_name():

# The code inside

return value

When we don't add it, Python will implicitly return the default value, None, as the return
value.

When we do want to be explicit:

def add(x, y):

answer = x + y

return answer

So a return keyword is added, plus the variable we want to output.

Now when we call the function, there will be an output that we can play with:

total = add(4.99, 9.99) # total is 1️4.98

This means that we can actually print out a function call!


print(add(3, 4)) # Same thing as print(7)

print(add(1️, 5)) # Same thing as print(6)

print(add(5, 3)) # Same thing as print(8)

Here, the add() function is returning a value and that returned value is an argument for
the print() function.

The output would be:

Note: When a return statement is reached, Python will stop the execution of the current
function, sending a value out to where the function was called.

# Print vs. Return

Now you might wonder, why are we returning values instead of printing them?

Well, print() functions can be anywhere in the program — inside or outside of a function,
whereas return is the output of a function; you don't need to print out whatever you are
returning.

As a rule of thumb:

• Use return in a function when you want to send value(s) from one point in the code
to another.

• Use print() in a function when you want to display some text to the user.

# Scope

Suppose we created a variable inside the body of a function. Can we use it outside of the
function? Well, let's see.

Define a function named add() and print the variable answer outside of it:

def add(x, y):

answer = x + y

return answer

print(answer)

When we run this code, we will get an error:


NameError: name 'answer' is not defined

This is due to something called scope.

Scope determines where in the program a variable is visible and can be used.

Here are two types of scope:

• The scope of the answer variable is only inside the add() function. It is a local
variable that belongs to the local scope of the add() function.

• Now, a variable created outside of a function is called a global variable and belongs
to the global scope, meaning that they can be used by every function.

Let's try setting the answer variable as a global variable (outside the function):

answer = 0

def add(x, y):

answer = x + y

return answer

add(3, 4)

print(answer)

The output won't be an error anymore!

Notice that answer is not 7. It's still 0 because if we create a variable with the same name
inside a function, it will be a local variable and can only be used inside the function. The
global variable with the same name will remain global and with the original value.

You might also like