Saturday, July 30, 2011

Super Simple Python #5 - True, False, and the if statements

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

Please, keep that in mind. (Not just for this 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 <= 2 - True (1 is less than OR equal to 2)
1 <= 1 - True (1 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)
(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 this:

>>> my_money = 100
>>> if my_money > 10:
    print('Yay! I have money to spend!')
    my_money = my_money - 10
    print('This is how much money I have left: ', my_money)

Yay! I have money to spend!
This is how much money I have left:  90


We can also add a different statement afterward, called else, that will handle when the other statement didn't happen:

>>> if my_money > 10:
    print('Yay! I have money to spend!')
    my_money = my_money - 10
    print('This is how much money I have left: ', my_money)
else:
    print('I don\'t have enough money!!')
    print('I\'m poor now:', my_money)

    
Yay! I have money to spend!
This is how much money I have left:  80

Let's put that in a function:

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

Don't forget the return statement!

Now lets go on a shopping spree!

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

>>> my_money = spend_money(my_money, 20)
Yay! I have money to spend!
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

Monday, July 25, 2011

Super Simple Python #4 - Defining functions and 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 bit of code that is grouped together to do some task. The print function in the last lesson, for example, outputs stuff to the console. Here's how we define one:

>>> def my_function():
    print('Hello World!')

Make sure you hit enter a couple times until the ">>>" shows up again. You've now defined a function! To use it, type:

>>> my_function()
Hello World!

We can also pass it variables by adding them in the parentheses, separated by commas.

>>> def insult_comeback(insult1, insult2):
    print(insult1)
    print(insult2)
    print("Oh yeah? Well... your mom!")

>>> insult_comeback("Bite me.", "You smell.")
Bite me.
You smell.
Oh yeah? Well... your mom!

Most good functions have a return statement at the end. It does exactly that: returns what's after it 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 can go into a variable!

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

Putting that all together, we can do nifty stuff like:

>>> def get_a_comeback(what_they_said):
    print("What they said to me: " + what_they_said)
    my_comeback = "Yes, and this one will be if you sit down."
    return my_comeback

>>> my_comeback = get_a_comeback("Is this seat empty?")
What they said to me: Is this seat empty?
>>> print(my_comeback)
Yes, and this one will be if you sit down.

Super Simple Python #3 - The print Function

You don't have to worry about filling your printer with reams of paper yet. That's the wrong kind or printing we're talking about. With the print function, you can do lots of cool things! Like sending strings to the standard console output, or sending strings to the standard error output, or even sending things to a file! How exciting!

>>> 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 the quotation marks around it like:

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

The print function is used to display the value of something to the console (the interactive shell, IDLE, is a console). 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)
<built-in function print>

Using print is the simplest way to get feedback from your program. Use it liberally (at least until episode #163* where we discuss the logging package).

*yeah, right. I don't even have #4 planned yet...

Super Simple Python #2 - Strings

While it is quite fun to play with kittens and strings, it's even more fun to play with Python and strings! A string in programming speak is an ordered series of characters. That sounds a whole lot like words to me! Let's play with some strings!

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 ' and ", as long as you use the same one for that string. Nobody likes mismatched bookends. (Not sure that's a good example, as nobody really likes bookends to begin with.)

We can also assign strings to a variable!

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

and 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 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 (\) so that Python doesn't get confused.

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

See? Just as fun as kittens! And to make sure you get that warm and fuzzy feeling: Mister Rogers' Neighborhood Introduction Theme Song

Super Simple Python #1 - Math and 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!

Open up IDLE (look at #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 ">>>" also. 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 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 too!

>>> 3 + 5 - 10
-2

Ooooo look! It's a negative two!

Now a variable!

>>> red = 3

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

>>> red
3

There's our 3!

We can also do:

>>> blue = 5 - 10
>>> blue
-5

There, we totally subtracted 10 from 5, then assigned that (-5) to blue!

Now I'm going to be crazy and try something:

>>> red + blue
-2

NO WAY!! I totally just blew my own mind right there. I added red and blue and got a number!!! It took the value of red (3) and the value of blue (-5) and added them! That's some sweet skills right there.

Super Simple Python #0 - Install and Rules

I've had three people ask me in the last two months about how to learn Python, so I've decided to start doing a tutorial! 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! Alright, you didn't come here to listen to me yap, 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. I'm new at this, and I'll probably miss something that I take for granted but probably looks like voodoo to others. It's not, I promise.
3. Have fun - Yeah, this sounds like an obligatory rule just to fill out the nice round "Three" number. Well it is. But that doesn't mean you shouldn't have fun! 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!
Alright you maggots! (TF2 reference...) Go to http://www.python.org/download.

If you're on Windows, download Python 3.2.1 Windows X86 MSI Installer (or the X86-64 bit installer if you have a 64 bit machine. Don't know if you have a 64 bit machine? Then assume you don't). 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 Python 3.2.1 Mac OS X 32-bit i386/PPC Installer (or the other one if you have a Puma instead of a Tabby or whatever). 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 Warfare.

Now find the shortcut called "_IDLE (Python GUI)_". It'll be either on your desktop or in your Start Menu or Applications folder under Python 3.2. This is what we'll be using for most of the other tutorials.

Congratulations! You can now program!