Salvatore Lopiparo

Software Engineer

Super Simple Python #3 – The print Statement

You don’t have to worry about filling your printer with reams of paper yet. That’s a different kind of printing than we’re talking about. With the print function, you can do lots of cool things! Like sending strings to the console output! Exciting AND useful!

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!

>>> bob_string = 'Hi, my name is Bob.'
>>> print(bob_string)
Hi, my name is Bob.

It’s that simple. You may notice that it doesn’t have quotation marks around it in the output. The quotation marks are a side effect of not using the print statement.

>>> bob_string
'Hi, my name is Bob.'

Use the print function to display the value of something to the console (the interactive PyCharm Python Console, for example). Strings by themselves won’t print to the console inside of a function definition.

You can also print numbers!

>>> print(42)
42

You can even print print!!

>>> print(print)

Using print is the simplest way to get feedback from your program. Use it liberally. It’s your quickest way to figure out how your program is working.

Super Simple Python #2 – Intro to Strings

While it is quite fun to use strings to play with kittens, it’s even more fun to use strings to play with Python! (Although far less cute.) A string in programming speak is an ordered series of characters, which is a fancy way of saying “words”. Let’s play with some strings!

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 write a string, take any set of characters and put either double or single quotation marks around it:

>>> 'hi'
'hi'
>>> "howdy"
'howdy'

To Python, there is no difference between using single quotes (') and double quotes (" or Shift+'), as long as you use the same one for that string. Nobody likes mismatched bookends. (Not sure that’s a good example, as nobody uses bookends to begin with.)

We can also assign strings to a variable, just like numbers!

>>> hi_string = 'hi'
>>> hi_string
'hi'

and even add them!

>>> hi_string + 'howdy'
'hihowdy'

Let’s add a space between those two:

>>> hi_string + ' ' + 'howdy'
'hi howdy'

We can even type whole sentences, punctuation and all:

>>> taunt = "Your mother was a hamster and your father smelt of elderberries!"
>>> taunt
'Your mother was a hamster and your father smelt of elderberries!'

If we need to use an apostrophe (also known as the single quotation mark, ') in the middle of our sentence, we can either use the double quotation marks:

>>> "It's a wonderful day in the neighborhood."
"It's a wonderful day in the neighborhood."

or we can escape the apostrophe with a backslash (\). This tells the Python interpreter to ignore the special character following it. In this example, we use It\'s:

>>> 'It\'s a wonderful day in the neighborhood.'
"It's a wonderful day in the neighborhood."

You can also include numbers inside your strings:

>>> box_message = "I have 3 boxes."
>>> box_message
'I have 3 boxes.'

You can’t, however, add a number to a string. First you must convert the number to a string using the str function.

>>> '1' + '1'  # Adding strings
'11'
>>> 1 + 1  # Adding numbers
2
>>> 'hello' + str(1)  # Adding numbers to strings
'hello1'

See? Just as fun as kittens!

Super Simple Python #1 – Doing Math and Assigning Variables

Wait, wait! Don’t groan yet! It’s really simple math! Like, pluses and minuses and stuff! No long division, and no integrating differential equations, I promise! That’s a later chapter!

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!

Open up the PyCharm Python Console (see SSP#0). You’ll notice that the lines you type on start with “>>>”. That’s normal. You’ll also notice that I’ll start things I want you to type with “>>>”. That’s also normal. You should not, however, type extra “>>>”. That’s not normal. The line after the “>>>” is the output line. That’s also also normal. You’ll also notice that I say also too much. That’s also not normal.

Now some math! Type:

>>> 1 + 1
2

Yay! Math! See? Easy stuff. Now try:

>>> 1 - 1
0

And it works like that with all the numbers, including negatives!

>>> 3 + 5 - 10
-2
>>> 111 * 7777
863247

Now a variable! A variable is a name for a piece of data, like a number.

>>> bananas = 3

We call that “assigning 3 to bananas.” You may have noticed that it didn’t have any output. That’s because the number 3 went “into” the variable bananas. Now if we type:

>>> bananas
3

There’s our 3!

We can also do:

>>> apples = 10 - 6
>>> apples
4

There, we subtracted 6 from 10, then assigned that (4) to apples! It will always completely figure out the right side of the = before assigning the value (in this case 10 - 6).

You can also do math on variables that contain numbers:

>>> apples + 10
14
>>> apples  # Notice here how apples did not change!
4
>>> apples = apples + 10  # Now it will change, because we assigned it again!
>>> apples
14

In addition to adding numbers to variables, you can add variables to other variables:

>>> apples + apples
28
>>> apples
14
>>> fruits = bananas + apples
>>>fruits
17

Whew! Math is done. That wasn’t so bad, was it?

Questions or comments? Let me know below!

Super Simple Python #0 – Installing and Rules

I have always been meaning to flush out this Python tutorial, so here it is. It’ll be really easy, designed for someone who doesn’t know any programming. Also, it shouldn’t take more than about 5 minutes for each lesson! I don’t like long intros, so let’s start!

First, some ground rules.

  1. Type things yourself – Don’t just copy what I type and paste it into your own window. You won’t learn anything that way. They’ll be short, I promise.

  2. Ask questions – Please. Let me know if you don’t understand something. I’ll probably miss something that I take for granted but probably looks like voodoo to others. It’s not magic, I promise.

  3. Have fun – Programming is fun when you get the hang of it. I won’t post anything that I won’t laugh at myself*, I promise.

*and trust me, I laugh at myself all the time.

Install Python!

First things first: Go to http://www.python.org/download.

If you’re on Windows, download Python 3.3 Windows X86 MSI Installer. (We’re installing the 32-bit because there are a few libraries that do not support 64-bit.) Double click on the install file and use the default for everything (keep hitting Next, OK and Finish until the box goes away).

If you’re on a Mac, download the Python 3.3 Installer based on if you have a Puma or a Tabby. Double click (or whatever Mac people do) on the install file and use the default for everything.

If you’re on Linux, and you don’t know how to download Python, you need to set down your older sibling’s computer and go shout profanities on Modern Duty 2 (or whatever you kids play now-a-days). But if you’re insistent, it’s probably something like apt-get install python.

Install PyCharm!

PyCharm is a piece of software called an Integrated Development Environment or IDE. That’s fancy speak for “a feature-rich program to write code.” This step isn’t necessary, but is strongly suggested. Please download their Community Edition (it’s free). It will take us a minute to set up, but it will be worth it!

  1. After you install PyCharm and you get to the first configure window, choose whatever color scheme you like. (I like Darcula!)
  2. On the Welcome screen, choose “Configure”, then “Settings”.

  3. Find “Python Interpreter>Python Interpreters” on the left, then click the “+” on the right. Choose your Python 3.3 install listed, then click “OK” to go back to the Welcome screen.

  4. Click “Create New Project” and name it something like “super_simple_tutorial”.

  5. Finally, go to “Tools>Run Python Console…” on the menu bar.

This Python Console window will be your primary tool through most of the lessons. It will evaluate what you type on the line after the “>>>” and print it back to you below it. For example, type print("hello world") after the “>>>” and you will get something like this:

>>> print("hello world")
hello world

Congratulations! You can now program!

Python – try-finally and return statements

So I ran into an interesting issue today with try-finally and a return statement in Python.

I was creating a simple if-else on a library that was prone to erroring, so I needed to put it in a try-finally to make sure clean up always happened:

def get_error_prone_choice(value):
    try:
        if is_a_good_choice(value):
            return error_prone_function(True)
        else:
            return another_error_prone_function(False)
    finally:
        clean_up()

Here’s where the multiple exits from a function that Python allows adds some confusion. When does clean_up() happen? I needed to make sure that clean_up happened before it returned the value or bad things would happen (specifically a non-garbage collected object would start to accumulate from the inspect module).

It turns out the finally clause is called at the last possible moment when leaving the try-finally section even when leaving the function, which means I’m fine to use it as it is. However, returning from a finally AND from the main try statement can get confusing quickly:

def get_error_prone_choice(value):
    try:
        return error_prone_function(True)
    finally:
        return clean_up()

This will result in error_prone_function to be evaluated, then the result of clean_up() to be returned! The finally is always called at the last possible moment, meaning the return value is first set to the result from error_prone_function and then overwritten to the result from clean_up().