Salvatore Lopiparo

Software Engineer

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!

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!