0% found this document useful (0 votes)
2 views6 pages

day-06 Introduction to Functions

The document introduces functions in Python, explaining how to define and use them to avoid code repetition and improve efficiency. It covers the syntax for defining functions, calling them with arguments, and the advantages of using functions, such as reducing errors and simplifying code maintenance. Additionally, it discusses returning values from functions and provides examples to illustrate these concepts.

Uploaded by

hatim
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)
2 views6 pages

day-06 Introduction to Functions

The document introduces functions in Python, explaining how to define and use them to avoid code repetition and improve efficiency. It covers the syntax for defining functions, calling them with arguments, and the advantages of using functions, such as reducing errors and simplifying code maintenance. Additionally, it discusses returning values from functions and provides examples to illustrate these concepts.

Uploaded by

hatim
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
You are on page 1/ 6

1/7/22, 3:49 PM 07 Introduction to Functions 1/7/22, 3:49 PM 07 Introduction to Functions

This code will not run, but it shows how functions are used in general.

Day-6
Defining a function

Introducing Functions Give the keyword def , which tells Python that you are about to define a function.
Give your function a name. A variable name tells you what kind of value the variable contains; a
function name should tell you what the function does.
One of the core principles of any programming language is, "Don't Repeat Yourself". If you have an action that Give names for each value the function needs in order to do its work.
should occur many times, you can define that action once and then call that code whenever you need to carry These are basically variable names, but they are only used in the function.
out that action. They can be different names than what you use in the rest of your program.
These are called the function's arguments.
We are already repeating ourselves in our code, so this is a good time to introduce simple functions. Functions Make sure the function definition line ends with a colon.
mean less work for us as programmers, and effective use of functions results in code that is less error-prone. Inside the function, write whatever code you need to make the function do its work.

Using your function


Contents To call your function, write its name followed by parentheses.
What are functions? Inside the parentheses, give the values you want the function to work with.
General Syntax These can be variables such as current_name and current_age , or they can be actual values
Examples such as 'eric' and 5.
Returning a Value
Exercises
Challenges top

What are functions? Basic Examples


Functions are a set of actions that we group together, and give a name to. You have already used a number of For a simple first example, we will look at a program that compliments people. Let's look at the example, and
functions from the core Python language, such as string.title() and list.sort(). We can define our own functions, then try to understand the code. First we will look at a version of this program as we would have written it earlier,
which allows us to "teach" Python new behavior. with no functions.

General Syntax
A general function looks something like this:

In [ ]: # Let's define a function.


def function_name(argument_1, argument_2):
# Do whatever we want this function to do,
# using argument_1 and argument_2

# Use function_name to call the function.


function_name(value_1, value_2)

file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 1/12 file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 2/12


1/7/22, 3:49 PM 07 Introduction to Functions 1/7/22, 3:49 PM 07 Introduction to Functions

In [2]: print("You are doing good work, Adriana!")


print("Thank you very much for your efforts on this project.") To use a function we give the function's name, and then put any values the function needs in order to do its work.
In this case we call the function three times, each time passing it a different name.
print("\nYou are doing good work, Billy!")
print("Thank you very much for your efforts on this project.")

print("\nYou are doing good work, Caroline!")


print("Thank you very much for your efforts on this project.") A common error
You are doing good work, Adriana!
A function must be defined before you use it in your program. For example, putting the function at the end of the
Thank you very much for your efforts on this project.
program would not work.
You are doing good work, Billy!
Thank you very much for your efforts on this project. In [1]: thank_you('Adriana')
thank_you('Billy')
You are doing good work, Caroline! thank_you('Caroline')
Thank you very much for your efforts on this project.
def thank_you(name):
# This function prints a two-line personalized thank you message.
Functions take repeated code, put it in one place, and then you call that code when you want to use it. Here's print("\nYou are doing good work, %s!" % name)
what the same program looks like with a function. print("Thank you very much for your efforts on this project.")

---------------------------------------------------------------------------
In [4]: def thank_you(name): NameError Traceback (most recent call last)
# This function prints a two-line personalized thank you message. <ipython-input-1-a1b6b8373f44> in <module>()
print("\nYou are doing good work, %s!" % name) ----> 1 thank_you('Adriana')
print("Thank you very much for your efforts on this project.") 2 thank_you('Billy')
3 thank_you('Caroline')
thank_you('Adriana') 4
thank_you('Billy') 5 def thank_you(name):
thank_you('Caroline')
NameError: name 'thank_you' is not defined
You are doing good work, Adriana!
Thank you very much for your efforts on this project.
On the first line we ask Python to run the function thank_you(), but Python does not yet know how to do this
You are doing good work, Billy!
Thank you very much for your efforts on this project. function. We define our functions at the beginning of our programs, and then we can use them when we need to.

You are doing good work, Caroline!


Thank you very much for your efforts on this project.
A second example
In our original code, each pair of print statements was run three times, and the only difference was the name of When we introduced the different methods for sorting a list
the person being thanked. When you see repetition like this, you can usually make your program more efficient (http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/lists_tuples.ipynb
by defining a function. our code got very repetitive. It takes two lines of code to print a list using a for loop, so these two lines are
repeated whenever you want to print out the contents of a list. This is the perfect opportunity to use a function, so
let's see how the code looks with a function.
The keyword def tells Python that we are about to define a function. We give our function a name, thank_you() in
First, let's see the code we had without a function:
this case. A variable's name should tell us what kind of information it holds; a function's name should tell us what
the variable does. We then put parentheses. Inside these parenthese we create variable names for any variable
the function will need to be given in order to do its job. In this case the function will need a name to include in the
thank you message. The variable name will hold the value that is passed into the function thank_you().

file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 3/12 file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 4/12


1/7/22, 3:49 PM 07 Introduction to Functions 1/7/22, 3:49 PM 07 Introduction to Functions

In [3]: students = ['bernice', 'aaron', 'cody'] In [9]: def show_students(students, message):


# Print out a message, and then the list of students
# Put students in alphabetical order. print(message)
students.sort() for student in students:
print(student.title())
# Display the list in its current order.
print("Our students are currently in alphabetical order.") students = ['bernice', 'aaron', 'cody']
for student in students:
print(student.title()) # Put students in alphabetical order.
students.sort()
# Put students in reverse alphabetical order. show_students(students, "Our students are currently in alphabetical order.")
students.sort(reverse=True)
#Put students in reverse alphabetical order.
# Display the list in its current order. students.sort(reverse=True)
print("\nOur students are now in reverse alphabetical order.") show_students(students, "\nOur students are now in reverse alphabetical orde
for student in students: r.")
print(student.title())
Our students are currently in alphabetical order.
Aaron
Our students are currently in alphabetical order. Bernice
Aaron Cody
Bernice
Cody Our students are now in reverse alphabetical order.
Cody
Our students are now in reverse alphabetical order. Bernice
Cody Aaron
Bernice
Aaron
This is much cleaner code. We have an action we want to take, which is to show the students in our list along
with a message. We give this action a name, show_students().
Here's what the same code looks like, using a function to print out the list:
This function needs two pieces of information to do its work, the list of students and a message to display. Inside
the function, the code for printing the message and looping through the list is exactly as it was in the non-function
code.

Now the rest of our program is cleaner, because it gets to focus on the things we are changing in the list, rather
than having code for printing the list. We define the list, then we sort it and call our function to print the list. We
sort it again, and then call the printing function a second time, with a different message. This is much more
readable code.

Advantages of using functions


You might be able to see some advantages of using functions, through this example:

We write a set of instructions once. We save some work in this simple example, and we save even more
work in larger programs.

file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 5/12 file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 6/12


1/7/22, 3:49 PM 07 Introduction to Functions 1/7/22, 3:49 PM 07 Introduction to Functions

When our function works, we don't have to worry about that code anymore. Every time you repeat code in
your program, you introduce an opportunity to make a mistake. Writing a function means there is one place Returning a Value
to fix mistakes, and when those bugs are fixed, we can be confident that this function will continue to work
Each function you create can return a value. This can be in addition to the primary work the function does, or it
correctly.
can be the function's main job. The following function takes in a number, and returns the corresponding word for
that number:

In [3]: def get_number_word(number):


# Takes in a numerical value, and returns
We can modify our function's behavior, and that change takes effect every time the function is called. This is # the word corresponding to that number.
if number == 1:
much better than deciding we need some new behavior, and then having to change code in many different
return 'one'
places in our program. elif number == 2:
return 'two'
elif number == 3:
return 'three'
For a quick example, let's say we decide our printed output would look better with some form of a bulleted list. # ...
Without functions, we'd have to change each print statement. With a function, we change just the print statement
in the function: # Let's try out our function.
for current_number in range(0,4):
number_word = get_number_word(current_number)
In [10]: def show_students(students, message):
print(current_number, number_word)
# Print out a message, and then the list of students
print(message) 0 None
for student in students: 1 one
print("- " + student.title()) 2 two
3 three
students = ['bernice', 'aaron', 'cody']

# Put students in alphabetical order.


students.sort() It's helpful sometimes to see programs that don't quite work as they are supposed to, and then see how those
show_students(students, "Our students are currently in alphabetical order.") programs can be improved. In this case, there are no Python errors; all of the code has proper Python syntax.
But there is a logical error, in the first line of the output.
#Put students in reverse alphabetical order.
students.sort(reverse=True)
show_students(students, "\nOur students are now in reverse alphabetical orde
We want to either not include 0 in the range we send to the function, or have the function return something other
r.")
than None when it receives a value that it doesn't know. Let's teach our function the word 'zero', but let's also
Our students are currently in alphabetical order. add an else clause that returns a more informative message for numbers that are not in the if-chain.m
- Aaron
- Bernice
- Cody

Our students are now in reverse alphabetical order.


- Cody
- Bernice
- Aaron

You can think of functions as a way to "teach" Python some new behavior. In this case, we taught Python how to
create a list of students using hyphens; now we can tell Python to do this with our students whenever we want to.

file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 7/12 file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 8/12


1/7/22, 3:49 PM 07 Introduction to Functions 1/7/22, 3:49 PM 07 Introduction to Functions

In [5]: def get_number_word(number): In [7]: def get_number_word(number):


# Takes in a numerical value, and returns # Takes in a numerical value, and returns
# the word corresponding to that number. # the word corresponding to that number.
if number == 0: if number == 0:
return 'zero' return 'zero'
elif number == 1: elif number == 1:
return 'one' return 'one'
elif number == 2: elif number == 2:
return 'two' return 'two'
elif number == 3: elif number == 3:
return 'three' return 'three'
else: else:
return "I'm sorry, I don't know that number." return "I'm sorry, I don't know that number."

# Let's try out our function. # This line will never execute, because the function has already
for current_number in range(0,6): # returned a value and stopped executing.
number_word = get_number_word(current_number) print("This message will never be printed.")
print(current_number, number_word)
# Let's try out our function.
for current_number in range(0,6):
0 zero
number_word = get_number_word(current_number)
1 one
print(current_number, number_word)
2 two
3 three 0 zero
4 I'm sorry, I don't know that number. 1 one
5 I'm sorry, I don't know that number. 2 two
3 three
4 I'm sorry, I don't know that number.
If you use a return statement in one of your functions, keep in mind that the function stops executing as soon as 5 I'm sorry, I don't know that number.
it hits a return statement. For example, we can add a line to the get_number_word() function that will never
execute, because it comes after the function has returned a value:

More Later
There is much more to learn about functions, but we will get to those details later. For now, feel free to use
functions whenever you find yourself writing the same code several times in a program. Some of the things you
will learn when we focus on functions:

How to give the arguments in your function default values.


How to let your functions accept different numbers of arguments.

top

file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 9/12 file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 10/12


1/7/22, 3:49 PM 07 Introduction to Functions 1/7/22, 3:49 PM 07 Introduction to Functions

In [ ]: # Ex 4.3 : Addition Calculator

Exercises # put your code here

Greeter In [ ]: # Ex 4.4 : Return Calculator

Write a function that takes in a person's name, and prints out a greeting. # put your code here
The greeting must be at least three lines, and the person's name must be in each line.
Use your function to greet at least three different people. In [ ]: # Ex 4.5 : List Exercises - Functions
Bonus: Store your three people in a list, and call your function from a for loop.
# put your code here
Full Names

Write a function that takes in a first name and a last name, and prints out a nicely formatted full name, in a top
sentence. Your sentence could be as simple as, "Hello, full_name."
Call your function three times, with a different name each time.

Addition Calculator
Challenges
Write a function that takes in two numbers, and adds them together. Make your function print out a sentence Lyrics
showing the two numbers, and the result.
Call your function with three different sets of numbers. Many songs follow a familiar variation of the pattern of verse, refrain, verse, refrain. The verses are the parts
of the song that tell a story - they are not repeated in the song. The refrain is the part of the song that is
repeated throughout the song.
Return Calculator
Find the lyrics to a song you like (http://www.metrolyrics.com/dont-stop-believin-lyrics-journey.html) that
Modify Addition Calculator so that your function returns the sum of the two numbers. The printing should follows this pattern. Write a program that prints out the lyrics to this song, using as few lines of Python code
happen outside of the function. as possible. hint

List Exercises - Functions In [ ]: # Challenge: Lyrics


Go back and solve each of the following exercises from the section on Lists and Tuples
# Put your code here
(http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/lists_tuples.i
using functions to avoid repetetive code:
Ordered Working List top
(http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/lists_tup
Ordered Numbers
(http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/lists_tup
Hints
These are placed at the bottom, so you can have a chance to solve exercises without seeing any hints.

In [ ]: # Ex 4.1 : Greeter
Lyrics
# put your code here
Define a function that prints out the lyrics of the refrain. Use this function any time the refrain comes up in
the song.
In [ ]: # Ex 4.2 : Full Names

# put your code here

file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 11/12 file:///C:/Users/Administrator/Downloads/07 Introduction to Functions.html 12/12

You might also like