Python: Functions and Loops
August 04, 2018
In the tutorials so far in this course, you’ve used functions many times. In this tutorial, you’ll see how to create new ones! After that, you’ll learn about loops in Python, one of the most important concepts in programming.
Your own functions!
Remember functions like len()
that you can execute in Python? Well, good news – you will learn how to write your own functions now!
A function is a sequence of instructions that Python should execute. Each function in Python starts with the keyword def
, is given a name, and can have some parameters. Let’s give it a go. Replace the code in python_intro.py with the following:
def hi():
print 'Hi there!'
print 'How are you?'
hi()
Okay, our first function is ready!
You may wonder why we’ve written the name of the function at the bottom of the file. The first time (line 1), we’re defining what the function does. The second time (line 5), we’re calling the function, i.e. asking Python to actually execute the function.
Note that because Python reads the file and executes it from top to bottom. When Python is executing the function, if it hasn’t yet found the definition, it will throw an error. Hence, we define the function before calling it.
Let’s run this now and see what happens:
$ python python_intro.py
Hi there!
How are you?
Note: if it didn’t work, don’t panic! The output will help you to figure why:
- If you get a
NameError
, that probably means you typed something wrong, so you should check that you used the same name when creating the function withdef hi():
and when calling it withhi()
. - If you get an
IndentationError
, check that both of theprint
lines have the same whitespace at the start of a line: python wants all the code inside the function to be neatly aligned. - If there’s no output at all, check that the last
hi()
isn’t indented - if it is, that line will become part of the function too, and it will never get run.
Let’s build our first function with parameters. We will use the previous example – a function that says ‘hi’ to the person running it – with a name:
def hi(name):
As you can see, we now gave our function a parameter that we called name
:
def hi(name):
if name == 'Commonlounge':
print 'Hi Commonlounge!'
elif name == 'Dave':
print 'Hi Dave!'
else:
print 'Hi anonymous!'
hi()
Remember: The print
function is indented four spaces within the if
statement. This is because the function runs when the condition is met. Let’s see how it works now:
$ python python_intro.py
Traceback (most recent call last):
File "python_intro.py", line 10, in
hi()
TypeError: hi() missing 1 required positional argument: 'name'
Oops, an error. Luckily, Python gives us a pretty useful error message. It tells us that the function hi()
(the one we defined) has one required argument (called name
) and that we forgot to pass it when calling the function. Let’s fix it at the bottom of the file:
hi("Commonlounge")
And run it again:
$ python python_intro.py
Hi Commonlounge!
And if we change the name?
hi("Dave")
And run it:
$ python python_intro.py
Hi Dave!
Now, what do you think will happen if you write another name in there? (Not Commonlounge
or Dave
.) Give it a try and see if you’re right. It should print out this:
Hi anonymous!
This is awesome, right? This way you don’t have to repeat yourself every time you want to change the name of the person the function is supposed to greet. And that’s exactly why we need functions – you never want to repeat your code!
Let’s do something smarter – there are more names than two, and writing a condition for each would be hard, right?
def hi(name):
print 'Hi ' + name + '!'
hi("Rachel")
Let’s call the code now:
$ python python_intro.py
Hi Rachel!
Multiple parameters and return values
So far, we have seen functions which take one parameter, and print something based on that. In fact, a function can take multiple inputs, and also return a value. Here’s a simple example,
def subtract(x, y):
return x - y
z = subtract(5, 2)
print z # Outputs: 3
The above subtract
function takes two inputs, which it calls x
and y
. It then returns the result of subtracting y
from x
. Hence, when we call subtract(5, 2)
, the returned value is 3
. We can assign this value to a variable, or use it any other way we want.
Note that we can take as many more inputs as we want, and we can also return a string, list, dictionary, etc. Here’s an example of a function which returns a dictionary.
def math(x, y):
return { 'sum': x+y, 'difference': x-y, 'product': x*y, 'quotient': x/y }
print math(5, 2)
# Outputs: {'sum': 7, 'difference': 3, 'product': 10, 'quotient': 2.5}
Congratulations! You just learned how to write functions! :)
Loops
Programmers don’t like to repeat themselves. Programming is all about automating things, so we don’t want to greet every person by their name manually, right? That’s where loops come in handy.
Still remember lists? Let’s do a list of people:
people = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'You']
We want to greet all of them by their name. We have the hi
function to do that, so let’s use it in a loop:
for name in people:
The for
statement behaves similarly to the if
statement; code below both of these need to be indented four spaces.
Here is the full code that will be in the file:
def hi(name):
print 'Hi ' + name + '!'
people = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'You']
for name in people:
hi(name)
print 'Next person'
And when we run it:
$ python python_intro.py
Hi Rachel!
Next person
Hi Monica!
Next person
Hi Phoebe!
Next person
Hi Ola!
Next person
Hi You!
Next person
As you can see, everything you put inside a for
statement with an indent will be repeated for every element of the list people
.
You can also use for
on numbers using the range
function:
for i in range(1, 6):
print i
Which would print:
1
2
3
4
5
range
is a function that creates a list of numbers following one after the other (these numbers are provided by you as parameters).
Note that the second of these two numbers is not included in the list that is output by Python (meaning range(1, 6)
counts from 1 to 5, but does not include the number 6). That is because “range” is half-open, and by that we mean it includes the first value, but not the last.
Conclusion
That’s it. You totally rock! This was a tricky chapter, so you should feel proud of yourself. We’re definitely proud of you for making it this far!
Based on content from https://tutorial.djangogirls.org/en/python_introduction/