Salvatore Lopiparo

Software Engineer

Super Simple Python #13 – Dictionaries

Python dictionaries, often called hash tables in other languages, are extremely powerful and surprisingly easy to use. They work just like a normal word dictionary works: looking up a key (word) in the dictionary gives back the information (definition) for that key (word).

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

To define a dictionary, we use curly brackets {}. Inside the curly brackets, we define key: value pairs, like so:

>>> word_dictionary = {'Aardvark': 'An animal with a long nose or something.',
...     'Apple': 'A red fruit (or sometimes green (or sometimes yellow)).',
...     'Brontosaurus': 'A big vegan dinosaur with a long neck and tail.'}

The keys can be any hashable type (which mostly includes strings and integers), and the value can be anything: string, int, object, class, function, list, your Aunt Sue, even another dictionary!

Using the dictionary is easy as well. To get the value associated to a key, we use a similar format as getting a value from a list.

>>> word_dictionary['Apple']
"A red fruit (or sometimes green (or sometimes yellow))."

And to add a new key-value pair to the dictionary, we again use a similar pattern to the list:

>>> word_dictionary['Twerk'] = "Some dance kids do now-adays? I guess?"
>>> print(word_dictionary['Twerk'])
Some dance kids do now-adays? I guess?

Changing something works the same way as adding:

>>> word_dictionary['Twerk'] = "Some stupid dance kids do now-adays."

To remove a key-value pair from the dictionary, use the pop function:

>>> word_dictionary.pop('Twerk')
'Some stupid dance kids do now-adays.'
>>> word_dictionary.keys()
dict_keys(['Apple', 'Aardvark', 'Brontosaurus'])

There are two things to note here: 1) The keys method of a dictionary returns a set-like object (which, for our purposes, works very similarly to a list) that shows you all the keys of the dictionary and 2) Twerk does not belong in the dictionary.

You can also use the for loop with a dictionary. The simplest and most common way to iterate over a dictionary gives you the keys of the dictionary, which we try here! (sorted is a built-in function that sorts alphabetically whatever you pass into it.)

>>> for word in sorted(word_dictionary):
...      print("key: " + word)
...      print("value: " + word_dictionary[word])
...
key: Aardvark
value: An animal with a long nose or something.
key: Apple
value: A red fruit (or sometimes green (or sometimes yellow)).
key: Brontosaurus
value: A big vegan dinosaur with a long neck and tail.

Super Simple Python #12 – Function Arguments

No, this is not about a function sleeping on the couch because it told another function what it really thought about that dress. Function arguments are the variables that you pass to a function. There are two basic kinds: arguments and keyword arguments.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

The first kind, arguments, are what we have used thus far for passing variables to a function. These types of arguments are required to use the function.

def greeting(first_name, last_name):
    print("Hello " + first_name + " " + last_name + "!")
    print("How are you today?")

They are also ordered, meaning in our example that first_name must come first, followed by last_name.

>>> my_first_name = "Frank"
>>> my_surname = "Sinatra"
>>> greeting(my_first_name, my_surname)
Hello Frank Sinatra!
How are you today?

The other type of function arguments, keyword arguments, are not required. They let you have a default argument that can be changed if the calling function wants. These are denoted by giving the name of the keyword argument followed by the default value to use. name_of_dog is our keyword argument in this snippet, with an empty string being the default value.

def greeting(first_name, last_name, name_of_dog=""):
    print("Hello " + first_name + " " + last_name + "!")
    if name_of_dog:
        print("Hello to your dog, " + name_of_dog + ", too!")
    print("How are you today?")

This will allow us to call the function with or without name_of_dog, so we don’t have to write a separate function for each case (such as, greeting_with_dog and greeting_without_dog)!

>>> greeting("Frank", "Sinatra", name_of_dog="Fido")
Hello Frank Sinatra!
Hello to your dog, Fido, too!
How are you today?
>>> greeting("George", "Clooney")
Hello George Clooney!
How are you today?

Keyword arguments are not ordered. You can pass the keyword arguments in any order (as long as all the ordered arguments are first!). You can also skip some keyword arguments if you want to keep the default values.

def greeting(first_name, last_name, name_of_dog="", name_of_cat="", name_of_bird=""):
    print("Hello " + first_name + " " + last_name + "!")
    if name_of_dog:
        print("Hello to your dog, " + name_of_dog + ", too!")
    if name_of_cat:
        print("Your cat, " + name_of_cat + ", is looking sassy!")
    if name_of_bird:
        print("And let's not forget your bird, " + name_of_bird + "!")
    print("How are you today?")
>>> first_name = "Michael"
>>> last_name = "Jordan"
>>> 
>>> name_of_cat = "Sylvester"
>>> name_of_bird = "Tweety"
>>> 
>>> greeting(first_name, last_name)
Hello Michael Jordan!
How are you today?
>>> greeting(first_name, last_name, name_of_bird=name_of_bird, name_of_cat=name_of_cat)
Hello Michael Jordan!
Your cat, Sylvester, is looking sassy!
And let's not forget your bird, Tweety!
How are you today?

I have the sudden urge to watch Space Jam.

Super Simple Python #11 – Comments

You may have noticed that I sometimes write words in the code that don’t affect execution at all. These are known as comments and are very useful in describing what a bit of code does or why it is there. A comment in Python can be one of two things: any words on a line after a # (hash); or any multi-line string (a string with 3 quotes instead of one).

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

The main difference between a hash (#) comment and a string comment is that a string comment is mainly used at the top of a function and a hash comment is used everywhere else. For example, here’s a good example of a string comment and a hash comment:

def estimate_circumference(radius):
    """Estimates the circumference of a circle
    from its radius.
    
    Circumference = 2 * pi * radius
    """
    two_pi = 6.28  # pi is about 3.14, this is 2 * pi
    return two_pi * radius

The first comment explains exactly what the function does; while the second comment explains why two_pi is there. Without these comments, it may not be clear to the next programmer (or, more often, future you) what is going on in this function.

You must watch out for bad comments, however. There are two kinds: Those that don’t tell you anything and those that tell you the wrong thing. The former is more annoying than hurtful:

def adder(x, y):
    value = x + y
    return value  # This returns value.

This comment is completely unnecessary, and only clutters the code. Only use comments when you need to further clarify something or explain code that is difficult to understand.

Much worse is a comment that is wrong in part or entirely. This usually happens when commented code gets edited, but the editor doesn’t change the comments to match!

def add_tax(sub_total, tax_rate):
    tax_amount = sub_total * tax_rate
    # This removes the California tax rate.
    total = tax_amount + sub_total
    return total

“What? There is nothing here that removes the California tax rate. California isn’t even in this code! Should I add it? What’s going on!?” — Future Programmer

This is a simple function with a poor comment that makes it much more confusing. Because the author didn’t update the comment when removing code about the California tax rate, the comment is now not only useless, it’s distracting and confusing.

Remember to use string comments at the beginning of a function to explain what it does, and hash comments to clarify what some code means. The easier the code is to read, the easier the code is to fix!

Super Simple Python #10 – Modules and Importing

If you find a bug in a program that is several months old, and you can’t understand the code enough to find or fix the bug, you have a big problem. The second most important part of programming, after making the code work, is making the code easy to understand. There will be several topics about ease-of-understanding tips and tricks, and our first installment will be about modules.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

Oh, this topic is about modules? I guess I should start then.

A module is a Python term for a file that contains Python code, or a .py file. The file we made last lesson (lesson_9.py) is a module. We can use the functions (greet, adder and main) without redefining them by importing the module!

>>> import lesson_9

We can now access the functions in our lesson_9 module by using the format: module.function(). Here’s our module and function:

>>> lesson_9.greet('Rhonin')
Hello Rhonin! Nice to meet you!

This lets us keep our code organized by putting related code together in the same module without cluttering it up!

There are several built-in modules in Python. In fact, there are a whole library of them! I recommend looking there for all your module needs! Here’s a few examples:

>>> import random  # For getting random numbers
>>> import urllib  # For accessing website urls
>>> import tkinter  # A GUI module
>>> import sys  # System functions
>>> import os  # Operating-System interface functions
>>> import os.path  # Functions for navigating the file system

Let me know in the comments if you want to see one of these modules! Each one can do some pretty cool stuff!

Super Simple Python #9 – Running a Python Script

After this lesson, you will be able to make your very own Python scripts! You’ll be a fully fledged Programmer! (Well, kinda…)

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

First, we need to create the file that will contain our script. In PyCharm, select our “super_simple_tutorial” project that we created in Lesson #0. Next, go to File > New > Python File. We normally name modules (a.k.a. Python files) something related to what it will contain, so lets name it lesson_9.py. Mine now looks like this:

__author__ = 'TorelTwiddler'

Not much there at the moment. You can leave or remove the __author__ = 'TorelTwiddler' line if you want, it won’t affect the rest of our script.

Now let’s put something useful in our module, like a function or two!

def greeter(name):
    print("Hello " + name + "! Nice to meet you!")


def adder(x, y):
    print("Adding " + str(x) + " to " + str(y) + "...")
    return x + y

We now have the functions defined in our module, but we still need to do something with them. That’s when we define the main function. The main function is the entrance point to your script. It’s where you set up anything you need before execution of the interesting stuff happens.

def main():
    greet("Thrall")
    apples = 3
    bananas = 4
    fruit = adder(apples, bananas)
    print("My fruit: " + str(fruit))

At the bottom of your file, we need to tell the Python Interpreter that if this file is the “main” entry point, to execute the main function. I will go into more detail about this is a later lesson. For now, put this at the bottom of the file:

if __name__ == "__main__":
    main()

Hurray! You now have a full Python script! Now to run the file, we’ll need to run a command shell (aka terminal). Luckily PyCharm has one built-in!

In PyCharm, go to Tools > Open Terminal. A new window will pop up in place of our Python Console (if it was open). It should look something like this:

Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\TorelTwiddler\PycharmProjects\super_simple_tutorial>

Note: You can also get to the operating system Terminal or Command Shell from one of the following: Windows – Start > search for Command Prompt; Mac – Finder > search for Terminal; Linux GUI – search button > Terminal; Linux Terminal – wat?

Now that we have our terminal, let’s run our program. To run a Python script in a terminal, we have to tell Python which script to run. We can use python [script_path] to execute a script. Here is how we run our script:

C:\Users\TorelTwiddler\PycharmProjects\super_simple_tutorial>python lesson_9.py
Hello Thrall! Nice to meet you!
Adding 3 to 4...
My fruit: 7

C:\Users\TorelTwiddler\PycharmProjects\super_simple_tutorial>

Super Simple Python #8 – The while Loop

A while statement continues to do something until it meets some condition. The basic structure is:

While some condition is True, run some code.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

The structure in Python should look familiar:

>>> bananas = 0
>>> while bananas < 5:
...     print("Adding a banana!")
...     bananas += 1  # Shorthand for bananas = bananas + 1
...     
Adding a banana!
Adding a banana!
Adding a banana!
Adding a banana!
Adding a banana!
>>> bananas
5

Python will run the entire code block if the condition is True, it will not stop in the middle.

>>> apples = 0
>>> while apples < 3:
...     print("Before we add an apple:" + str(apples))
...     apples += 1
...     print("After we add an apple: " + str(apples))
Before we add an apple:0
After we add an apple: 1
Before we add an apple:1
After we add an apple: 2
Before we add an apple:2
After we add an apple: 3
>>> apples
3

If the condition is False from the start, the code block will be skipped entirely!

>>> grapes = 10
>>> while grapes < 5:
...     print("This code won't run!")
...     grapes += 500
...     
>>> grapes
10

Working with the while statement can be dangerous! You must closely inspect your code such that the condition will eventually be False. If the condition stays True, you will get an infinite loop and your code will never stop executing!

In case it does get into an infinite loop, here’s how to deal with it: Press Ctrl-C (That is, hold the Ctrl key and press the C key). This will cancel the Python Console from executing any more code by sending the KeyboardInterrupt exception to the interpreter. Let’s practice. Run the following code followed directly by pressing cancel (Ctrl-C).

>>> while True:
...     grapes += 1
...     print("Grapes!!! " + str(grapes))
...
Grapes!!! 1
Grapes!!! 2
Grapes!!! 3
# etc...
Grapes!!! 76422
Grapes!!! 76423
Grapes!!! 76424
Traceback (most recent call last):
  File "", line 4, in 
KeyboardInterrupt

Now press Ctrl-C! My grapes got to 76424 before cancelling. You can see that it executes very fast!

Super Simple Python #7 – The for Loop

Last time we learned about lists and how to manipulate the list itself. This time we’ll learn how to do things to items in the list with the for statement.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

First, let’s make a list we can do things to.

>>> grocery_list = ['milk', 'apples', 'orange juice', 'paper towels', 'bbq sauce', 'eggs']
>>> print(grocery_list)
['milk', 'apples', 'orange juice', 'paper towels', 'bbq sauce', 'eggs']

Trying to do your shopping with the items listed like that would be quite difficult. Let’s try printing them in a better format using the for statement!

>>> for grocery_item in grocery_list:
...     print('- ' + grocery_item)
...     
- milk
- apples
- orange juice
- paper towels
- bbq sauce
- eggs

Pretty simple, yeah? When reading the lines above, we say “For each grocery_item in grocery_list, do some stuff (in this case, print the item). The word after for is the variable used for each item in the list, one after another. Using the for statement saves you from writing a lot of extra code, and handles lists of different sizes:

>>> print('- ' + grocery_list[0])
- milk
>>> print('- ' + grocery_list[1])
- apples
>>> print('- ' + grocery_list[2])
- orange juice
>>> print('- ' + grocery_list[3])
- paper towels
>>> # and so on...

We can make something more interesting too. Let’s say we have a bank account and a list of transactions.

>>> account_balance = 1000
>>> transactions = [-3, -149, -3, -3, -12, -3, -699, -3]

Now we can report each transaction and subtract it from our account balance using a for statement:

>>> account_balance = 1000
>>> for transaction in transactions:
...     print("Transaction processed: " + str(transaction))
...     account_balance = account_balance + transaction
...     print("Remaining Balance: " + str(account_balance))
...     
Transaction processed: -3
Remaining Balance: 997
Transaction processed: -149
Remaining Balance: 848
Transaction processed: -3
Remaining Balance: 845
Transaction processed: -3
Remaining Balance: 842
Transaction processed: -12
Remaining Balance: 830
Transaction processed: -3
Remaining Balance: 827
Transaction processed: -699
Remaining Balance: 128
Transaction processed: -3
Remaining Balance: 125

Super Simple Python #6 – Lists

Lists in Python are the same thing as they are in every day language: A sequence of items that go together. Usually things in the list are of the same type, like a grocery list or a hit list.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

You can either define an empty list:

>>> grocery_list = []

Or define a list with things in it:

>>> hit_list = ['Frankie', 'Jimmy', 'Gambini', 'Capone', 'Luciana', '3-Fingers Tony', 'Corleone']

If you want to get a specific item in the list, use square brackets and the index of the item. Note that lists start with an index of 0, not 1.

>>> hit_list[0]
'Frankie'
>>> hit_list[1]
'Jimmy'
>>> hit_list[5]
'3-Fingers Tony'

Now let’s say we need to… ahemremove someone from the list.

>>> hit_list.remove('Gambini')
>>> hit_list
['Frankie', 'Jimmy', 'Capone', 'Luciana', '3-Fingers Tony', 'Corleone']

Or, if you prefer to work in order, you can pop them off the back…

>>> hit_list.pop()
'Corleone'
>>> hit_list
['Frankie', 'Jimmy', 'Capone', 'Luciana', '3-Fingers Tony']

or the front…

>>> hit_list.pop(0)
'Frankie'
>>> hit_list
['Jimmy', 'Capone', 'Luciana', '3-Fingers Tony']

If you want to change an item in the list, simply assign it to an index like you would any other variable.

>>> hit_list[3]
'3-Fingers Tony'
>>> hit_list[3] = "2-Fingers Tony"
>>> hit_list[3]
'2-Fingers Tony'

I’d rather not think about why his name changed.

Let’s say some guy on the internet is making death threats to several high-profile gangsters. Obviously we will need to add someone to the list. You can append them to the end of the list like so:

>>> hit_list.append('Salvatore')
>>> hit_list
['Jimmy', 'Capone', 'Luciana', '2-Fingers Tony', 'Salvatore']

Or, if you’d rather not wait to elimina… I mean put them at the end of the list, we can use insert, passing it the index we want to insert it before. Inserting before 0 will put it in the front.

>>> hit_list.remove('Salvatore')
>>> hit_list.insert(0, 'Salvatore')
>>> hit_list
['Salvatore', 'Jimmy', 'Capone', 'Luciana', '2-Fingers Tony']

I will have to cut this lesson here, as there appears to be a couple of violin salesmen at the door.

Super Simple Python #5 – True, False, and The if Statement

If you run out of money, then don’t spend money.

Please, keep that in mind. (Not just for this lesson…)

Note: In this lesson and in most future lessons, we will be writing functions that span several lines. It will be easier to write the lines into a file, then copy-paste them into the Python Console. From within PyCharm, go to File>New>Python File, then name it “lesson5”. Use that as a place to write functions for this lesson. Now to the programming!

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

First, True and False are used in Python to denote whether something is… well, true or false. Here’s your basic Truth Table:

1 < 2 - True (1 is less than 2)
1 > 2 - False (1 is greater than 2)

Since 1 is NOT greater than 2, you’ll get False. Here are the rest (for reference. We’ll use them more later):

1 == 1 - True (1 is equal to 1, note the double equal signs)
1 == 2 - False (1 is equal to 2)

1 != 1 - False (1 is NOT equal to 1)
1 != 2 - True (1 is NOT equal to 2)

1 <= 2 - True (1 is less than OR equal to 2)
1 <= 1 - True (1 is less than OR equal to 1)
2 <= 1 - False (2 is less than OR equal to 1)

1 >= 2 - False ( 1 is greater than OR equal to 2)
1 >= 1 - True (1 is greater than OR equal to 1)
2 >= 1 - True ((2 is greater than OR equal to 1)

(x.x) o-(''Q) - Boxing Kirby

if statements work like this:

If some value is True, then do some action.

So in Python, we would write something like the following. Note the 4 space indent similar to a function:

>>> if True:
...     print('It was True!')
... 
It was True!
>>> if False:
...     print("It was True!")
...     

Or something a bit more useful:

>>> my_money = 100
>>> if my_money > 10:
...     print('Yay! I have money to spend: ' + str(my_money))
...     my_money = my_money - 10
...     print('I just spent $10!')
...     print('This is how much money I have left: ' + str(my_money))
...     
Yay! I have money to spend: 100
I just spent $10!
This is how much money I have left: 90

We can also add a different statement afterwards, called else, that will handle when the if statement didn’t happen:

If some value is True, then do some action, otherwise (else) do some other action.

>>> if False:
...     print("It was True!")
... else:
...     print("It was False!")
...     
It was False!

Or back to our more useful code:

>>> if my_money > 10:
...     print('Yay! I have money to spend: ' + str(my_money))
...     my_money = my_money - 10
...     print('I just spent $10!')
...     print('This is how much money I have left: ' + str(my_money))
... else:
...     print("I don't have enough money!!")
...     print('I\'m poor now: ' + str(my_money))
...     
Yay! I have money to spend: 90
I just spent $10!
This is how much money I have left: 80

Let’s put that in a function:

def spend_money(money_in_bank, money_to_spend):
    if money_in_bank > money_to_spend:
        print('Yay! I have money to spend: ' + str(money_in_bank))
        money_in_bank = money_in_bank - money_to_spend
        print('I just spent $' + str(money_to_spend) + '!')
        print('This is how much money I have left: ' + str(money_in_bank))
    else:
        print("I don't have enough money!!")
        print('I\'m poor now: ' + str(money_in_bank))
    return money_in_bank

Here, we’re replacing the $10 with money_to_spend so we can change how much we spend. Don’t forget the return statement at the end!

Now let’s go on a shopping spree!

>>> my_money = spend_money(my_money, 40)
Yay! I have money to spend: 80
I just spent $40!
This is how much money I have left: 40

>>> my_money = spend_money(my_money, 20)
Yay! I have money to spend: 40
I just spent $20!
This is how much money I have left: 20

>>> my_money = spend_money(my_money, 300)
I don't have enough money!!
I'm poor now: 20

Super Simple Python #4 – Defining Simple Functions and Using The return Statement

One of the many cool things about Python is the really easy way to define functions. But before we can define any functions, we first need to define “function”! A function is a grouped bit of code that does some task. The print function in the last lesson is a function that outputs stuff to the console.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

Here’s how we define a function of our own:

>>> def greeting():
...     print('Hello World!')
...     

To define a function, we use the tag def followed by the name of our function. The code that the function performs comes after the line with the colon (:). All following lines must be indented by 4 spaces (if you’re using the PyCharm Console, you can press the Tab key instead).

Make sure you hit enter a couple of times until the “>>>” shows up again. The lines with “…” mean you are continuing a command on the next line, you should not type them. You’ve now defined a function! To use it, type:

>>> greeting()
Hello World!

We can also pass it an argument by adding it in the parentheses. This allows the function to get data from outside of itself:

>>> def greeting(name):
...     print("Hello " + name + "!")
...     
>>> greeting("Frank")
Hello Frank!

Most often you will want to have multi-line functions. At the beginning of each line after the function name, it must start with a 4 space indentation.

>>> def greeting(name):
...     print("Hello " + name + "!")  # Note the 4 spaces
...     print("How are you today?")  # 4 spaces here too!
...     
>>> greeting("Frank")
Hello Frank!
How are you today?

You will often need your function to have more than one variable available from outside. You can include more by separating them with commas. Remember that order matters!

>>> def greeting(first_name, last_name):
...     print("Hello " + first_name + " " + last_name + "!")
...     print("How are you today?")
...     
>>> greeting("Frank", "Morgan")
Hello Frank Morgan!
How are you today?

Most good functions have a return statement at the end. It does exactly that: returns what’s after the return to whatever called it. Like so:

>>> def adder(x, y):
...     new_number = x + y
...     return new_number
...     
>>> adder(2, 3)
5

The good thing about return statements is that they allow functions to put their result into a variable!

>>> eight = adder(3, 5)
>>> eight
8

A good function definition describes what the function does. Here’s our greeting function with a good description. We use 3 double-quotes in a row (which is just a string that can span more than one line) to describe the function.

def greeting(first_name, last_name):
    """Prints a greeting for the given first
    and last name."""
    print("Hello " + first_name + " " + last_name + "!")
    print("How are you today?")

Now the next person to look at this function won’t be confused about what it does!