November 24, 2016

Intro to Python: Containers, Functions, and Loops (Part 2 /2)

This is the second post in a series. If you're just getting started, see Part 1.

In the previous post, you got python installed, and ran a simple program. In this section we will use some language features to store data, and re-use code. These are important concepts for all programming languages.

Before we get started, let me warn you to pay attention to your indentation / white space here. Python doesn't care if you use tabs or spaces for white space, but does require that indented blocks are consistent. 


The first container we will look at is a list. A list is rather unsurprisingly just a series of items in a single object. To create a list, you just assign values inside square brackets separated by commas. After it is created you can add values using your_list_name.append(value). 

For example:

list_of_numbers = [1,1,1,1]

This creates a list with values 1, 1, 1, 1, -4. Individual values can be retrieved using square brackets and an index starting at zero. So list_of_numbers[0] = 1, and list_of_numbers[4] = -4.

Lists and looping

The list created here can also be looped very easily. This is done by using the syntax:

for <name> in <container>:
    do something with name

Note the indentation. Everything "inside" is indented to an equal level. 

So if we want to loop through all the numbers added in list_of_numbers, that can be done as follows:

list_of_numbers = [1,1,1,1]
sum = 0

for item in list_of_numbers:
    sum = sum + item
    print("Sum: {}".format(sum))

Running this code in your file will output:

Dictionaries and looping

There is another powerful type of container called a dictionary. Dictionaries store key value pairs, and can be created using curly braces. Elements are added just by providing a key in square braces.

They can also be iterated through (in fact, most things in python can be), but typically this is done by key, as there is no order to them like with lists. 

Here is an example of dictionary usage:

my_dictionary = {"word1":"Hello"}
my_dictionary["word2"] = "World"
for key in my_dictionary:


While lists are great for storing lots of one thing, dictionaries are great for storing many different things with descriptive names. You can even include a dictionary inside a list, and a list inside a dictionary.

Lists, dictionaries, and for loops make up 90% of my program. They rest is really just code organization techniques. 


Functions allow you to write some generalized code using variables and give it a name. This code can then be reused with different variable values. 

Here is an example of a function in use:

def my_talkative_function(phrase):

if __name__ == "__main__":
    my_phrase = "Hello Squirrel!" 
    my_talkative_function("I'm World not Squirrel!")


The "if __name__ == "__main__":" line might be a bit confusing. This is just telling the python interpreter where the code you want to run starts. It also lets you import your functions and classes into other files without importing your program.

Functions can also have optional parameters by using "=" in the argument list. If no parameter is given for these, the default will be used.

def my_talkative_function(phrase = "I have nothing to say."):

if __name__ == "__main__":

Note that with no arguments provided to my_talkative_function in __main__, it used the default value. Providing a value overrode this behaviour.

Functions are a fantastic way to simplify your program using smart names to wrap up complicated tasks.


Classes are another way to simplify programs. Classes let you create data types with names that explain what you're doing. Readability is so important in programming! 

To write a class, you first initialize it with a class name, and then you declare an __init__ function inside the class with some variables. This __init__ function assign its arguments to your class members. These can be accessed by calling my_class.variable_name on a class object.

In class functions, there is always at least one argument "self". This refers to the class object calling the function, and allows it to access member variables. This argument does not have to be passed in when calling the functions, as it is done automatically.

Here is a simple example containing all these concepts:

class two_word_phrase:
    def __init__(self, word1, word2, punctuation = '!'):
        self.word1 = word1
        self.word2 = word2
        self.punct = punctuation

def talkative_class(phrase):
    print("{} {}{}".format(phrase.word1, phrase.word2, phrase.punct))

if __name__ == "__main__":
    my_phrase_class = two_word_phrase("Hello", "Blorld") 


You can also declare functions other than __init__ to act on the class member variables. This is where the real simplifications come in with classes.

Here is the same example, but with talkative_class as a member function called talkative_class_func taking no arguments.

class two_word_phrase:
    def __init__(self, word1, word2, punctuation = '!'):
        self.word1 = word1
        self.word2 = word2
        self.punct = punctuation

    def talkative_class_func(self):
        print("{} {}{}".format(self.word1, self.word2, self.punct))

if __name__ == "__main__":
    my_phrase_class = two_word_phrase("Tutorial", "Completed") 


With some slight modifications, this will now output:

And now you're done with my tutorial. Give yourself a firm congratulatory handshake, and then take a look at some of python projects on this site (or start writing your own!)

No comments:

Post a Comment