The Beauty of Python
Foreword
This article explains the Python basics and shows a few cool functional programming concepts.
The Python Version
Currently there are two major versions of Python: 2 and 3. In this tutorial we will use Python 2 because it makes our lives easier when using map, filter, reduce and zip later. Another reason is that it sometimes looks slightly more elegant:
Print in Python 2:
print x, y, z
Print in Python 3:
print(x, y, z)
The IDE
At first we need a way to run Python code. If you don't know how to do it, then please read our Default Python IDE tutorial first.
Note: we will use Python 2 but it should work with Python 3 too.
Print in Python
After creating a new Python project, we jump right into it by printing something:
# this is a comment
print 'I love noobtuts.com'
Yay simple as that. No need for a ";" at the end.
Variables in Python
Defining and adding Variables
Let's take a look at variables:
a = 'sun'
b = 'day'
c = a + b
print c
We don't even have to declare the type, variables can be everything (int, string, float, ...).
Here another way to declare variables in Python:
x, y = 1, 2
q = x + y
print q
Switching Variables
Now here comes a cool thing about Python. We can switch two variables without using a third one:
x, y = y, x
Seriously, how cool is that?
If in Python
Let's create a if clause:
if 2 > 1:
print '2 is bigger than 1'
A very cool thing about Python can be seen in the code above. Instead of using parenthesis like { and } like in most other programming languages, Python uses indentation to save us from typing all those weird brackets all the time. Here is an example that shows how it works:
if 2 > 1:
print 'this print belongs to the if'
print 'this print belongs to the if as well'
print 'this print has nothing to do with the if'
The last print has nothing to do with the if clause, because of its indentation.
Here is how else if and else work:
if n == 3 or n == 4:
print 'n is 3 or 4'
elif n == 5:
print 'n is 5'
else:
print 'n is not 3, not 4 and not 5'
For Loops in Python
If we want to use a for loop in Python, we can do it like this:
for c in 'Test':
print c
for i in range(3):
print i
for i in range(1,5): # 1 2 3 4
print i
for i in range(0, 6, 2): # 0 2 4
print i
Simple as that.
Now since Python is not awesome enough yet, it also comes with a else for a for loop that happens if break was not called in the for loop:
# example where else is called:
for i in range(1, 5):
print i
else:
print 'loop never broken'
# example where else is not called:
for i in range(1, 5):
if i == 2:
break
else:
print 'this is never printed'
As you can see, Python really makes our lives easier.
Functions in Python
Let's create a function that compares two variables:
def eq(a, b):
return a == b
Now let's have some more fun by creating a function that returns two variables:
def swap(x, y):
return y, x
Is that awesome or what?
Classes in Python
Here is how to create and use a class:
# class definition
class Monster:
health = 100
def dead(self):
return self.health == 0
# using the class
m = Monster()
print m.dead()
Again, incredibly simple and as minimalistic as possible.
Lists in Python
Create a List
Often we want to create a list of values which is (as usual) incredibly easy in Python:
x = [1, 2, 3, 4]
Copy a List
If we just want to create a second variable that references the exact same list all the time, we would do this:
x = [1, 2, 3, 4]
y = x
Now if we would remove the 4 from the x list, here is what our variables would look like:
- x contains [1, 2, 3]
- y contains [1, 2, 3] (because it's just a reference)
If we want to create a real copy of the list, here is how we do it:
x = [1, 2, 3, 4]
y = x[:]
If we remove the 4 from the x list, the variables look like this:
- x contains [1, 2, 3]
- y contains [1, 2, 3, 4] (because it's a real copy)
So the question is, whats that [ : ] thing?
The Colon Operator
The [:] thing is one of the greatest things ever invented when it comes to lists. It's called the Colon operator and it specifies a range like [from : to].
Here is what we can do with it:
x = [1, 2, 3, 4, 5]
print x[:2] # gives us [1, 2]
print x[3:] # gives us [4, 5]
print x[1:4] # gives us [2, 3, 4]
print x[:] # gives us [1, 2, 3, 4, 5]
Just imagine how complicated it would be to do that in a language like C++ or Java.
More Lists
Here are a few more things that we commonly need when it comes to lists:
x = [1, 2, 3, 4, 5]
print len(x) # gives the length of the list, which is 5
x = x + [6] # adds 6 to the list so it's [1, 2, 3, 4, 5, 6]
if 3 in x:
print '3 is in the list'
List Comprehensions
List Compre.. what?
Let's create a list of all numbers between 0 and 4. Here is the old way to do it:
# gives [0, 1, 2, 3]
result = []
for x in range(4):
result.append(x)
Now the big benefit of List Comprehensions is that we can do the same thing (and more) in just one line of code:
# gives [0, 1, 2, 3]
[x for x in range(4)]
Here are some more examples that show how List Comprehensions work:
Take the numbers and multiply each by 10:
# gives [0, 10, 20, 30]
[x * 10 for x in range(4)]
Take the numbers and pair each one with a cow:
# gives [(0, 'cow'), (1, 'cow'), (2, 'cow')]
[(x, 'cow') for x in range(3)]
Take the numbers from two for loops (for x... for y...):
# gives [(0, 0), (0, 1), (1, 0), (1, 1)]
[(x, y) for x in range(2) for y in range (2)]
Let's add the condition that x has to be odd:
# gives [[1, 3]]
[x for x in range(4) if x % 2 != 0]
This might doesn't look like much, but shorter code is often better code. It improves readability and it makes our keyboard (and fingers) happier.
Functional Magic
All that stuff above is cool, but we want to go further. There is a concept that is called functional programming. Python supports this concept!
But functional programming is very close to math and it can become very complicated to understand, so we will only talk about a few things that are actually useful and understandable by humans.
We will take a look at the typical functional programming functions: map, zip, reduce and filter and show how they work with the help of some very easy to understand examples.
Note: those functions usually just do some crazy stuff to a list. For example applying a function to each entry of a list. No scary math involved at all!
filter
The first typical function is filter. As the name says, it filters a list.
Let's take a look at how to use it:
# our test function that returns a bool value
def is_bigger_than_two(n):
return n > 2
# using filter on a list
print filter(is_bigger_than_two, [1, 2, 3, 4])
# => gives [3, 4]
It just goes through the list [1, 2, 3, 4] and applys a function (in our case is_bigger_than_two) to each element. If it returns true it takes the element to the result list, otherwise it just ignores it. Hence why the result is the list [3, 4] which are all elements that are bigger than two.
Not too scary yet, so let's keep going.
map
The map function maps another function to each element of a list. In other words: it applys a function to each element in the list, nothing more.
Example:
# our test function
def inc(n):
return n + 1
# using map
print map(inc, [1, 2, 3, 4]) # gives [2, 3, 4, 5]
The above code just maps the inc function to each element of the list [1, 2, 3, 4]. So it increases 1 by 1, increases 2 by 1, increases 3 by 1 and then increases 4 by 1 and returns the result list which is [2, 3, 4, 5].
Again, still not too complicated but incredibly powerful.
zip
The zip function connects values like a zipper. It takes two lists and creates a list with the connected values as tuples ( a tuple is something like (1, 2) ).
Let's just create a example which will show very clearly what happens:
# using zip
print zip(['a', 'b', 'c'], [1, 2, 3])
It prints [('a', 1), ('b', 2), ('c', 3)]. That's it, no crazy math or anything. Just a combination of two lists.
reduce
The last one is the reduce function. It takes a list and a function, but it only returns a single value this time, instead of returning a list like all the previous functions.
Example: if we have the list [1, 2, 3] and call reduce with a multiply function, it would return 1 * 2 * 3. If we would call it with a minus function then it would return 1 - 2 - 3. The fun starts if we call it with more complicated functions, but more about that later.
Here is how we use it:
def multiply(a, b):
return a * b
print reduce(multiply, [1, 2, 3])
# => gives 1 * 2 * 3 = 6
For the lazy, Python already comes with basic functions like multiply. Here is how to use them:
import operator
print reduce(operator.mul, [1, 2, 3])
# => gives 1 * 2 * 3
Hint: it helps to get a pen and a piece of paper to draw the lists and see what exactly happens.