If only

Sometimes life presents you with challenges.   Some are large and some are small.  How you decide to deal with them has consequences.  Those consequences flow from your decision.  If I eat all my lollies now, I won’t have any after dinner.   If I annoy my friend Ben he won’t invite me over anymore.  If I don’t keep my hands to myself I don’t get the DS.  If I don’t let the dog out when I get up, I don’t get to play computer games. When these conditions are coupled with consequences, they can guide our lives.  Programs are the same.  Not exactly the same, but similar.

Within a program you can direct its flow by using “if”.  The if statement has a particular structure which needs to be followed (called its “syntax”).  The structure of if is as follows:

if :

Don’t worry about the stuff in angle brackets <> at the moment.  The important thing is that the first line starts with “if” and ends with a colon “:”.  No colon and Python will get upset. Further, the code that follows the colon is indented.  That’s important!

>>> time = '5PM'
>>> if time == '5PM':
...    print 'Time to play the computer!!'
...
Time to play the computer!!

So, working through this code… First the string ‘5PM’ is put in the bucket that we’ve called ‘time’.  Then, we’ve compared to see if the time is ‘5PM’.  If it is, then a message is printed (‘Time to play the computer!!!’).

Notice also that we said “time ==”, not “time =”.  That’s because ‘=’ and ‘==’ mean different things to Python.  When you write ‘=’ you are saying to Python, “take the thing on the right and put it in the thing on the left”.  However, when you write ‘==’ you are saying to Python, “these two things are equal – true or false?”

>>> time = '6PM'
>>> if time == '5PM':
...    print 'Time to play the computer!!'
...
>>>

If the condition (in this case: does time equal ‘5pm’) is not true, then the code is not processed.  Here we assigned a different time (actually string)  to time.  When we ran through the condition, Python said “well, that’s false now” so the code didn’t execute.

You can use other sorts of comparisons (like > and <)  in the condition.  They won’t work well in the examples above because time is a string (type), not actually a representation of time.   So if things like this work:

>>> time = '6PM'
>>> if time > '5PM':
...    print 'Time to play the computer!!'
...
Time to play the computer!!

it’s only because of blind luck.  This really won’t work:

>>> time = '6AM'
>>> if time > '5PM':
...    print 'Time to play the computer!!'
...
Time to play the computer!!

In this case, it’s a failure because the message printed when it shouldn’t have (6AM is not later than 5PM, but it printed anyway).  It’s doing this because Python is comparing them as if they were strings (which they are) not as if they were times.  Python is able to compare them as times, but that’s not something we’ll cover here.

We can compare things in lots of ways:

a< b – a is less than b: true or false?

>>> a,b = 1,2
>>> if a < b:
...   print "a is less than b"
...
a is less than b

Did you notice the sneaky way we did two assignments there?  Instead of a=1 and b=2 we said a,b = 1,2.  You can do this too.  Also pay attention to the fact that both a and b are integers, not strings – they have no quotation marks.

a> b – a is greater (or more) than b: true or false?

>>> if a > b:
...   print "a is greater than b"
...

Nothing printed because a is 1, which is less than b, which is 2.

not – this means “not” so if you have another comparison you can negate it:

not a > b  – it is not the case that a is greater than b: true or false? (think it through, it does make sense)

>>> if not a > b:
...   print "it is not true that a is greater than b"
...
it is not true that a is greater than b

a != b the ! (sometimes called a “shriek!” or a “bang!”) here means “not” (strangely this is just “!=”, not “!==” which given what we said about Python and “==” above would make more sense, but also take more typing.  Perhaps Python is just a bit schizophrenic?).   The translation of this is: a is not equal to b: true or false?

>>> if a != b:
...    print "They are not equal"
...
They are not equal

a <= b – a is less than or equal to b: true or false? The other way around (=<) won’t work:

>>> if a <= b: ...   print "a is less than or equal to b" ... a is less than or equal to b >>> if a =< b:
 File "", line 1
 if a =< b:
 ^
SyntaxError: invalid syntax

a >= b – a is greater than or equal to b: true or false?

You can also connect a number of conditions together using “and” and “or”:

>>> if a==1 and b== 2:
...    print 'a equals 1 AND b equals 2'
...
a equals 1 AND b equals 2

>>> if a == 1 or b ==5:
...    print "a equals 1 or b equals 5 (or both)"
...
a equals 1 or b equals 5 (or both)

Try some different combinations.

You can even let Python do some calculations before it compares things:

>>> if 5-1 == 3+1:
...   print "four equals four"
...
four equals four

In fact, Python’s methods of evaluating the conditions you pass it are more many and varied than this.  We may meet them later.  But for the time being note this:

>>> if 1:
...   print "1 is true!"
...
1 is true!
>>> if 0:
...   print "But 0 isn't"
...

Ponder it.

Interacting with raw_input

Python also has a feature which lets you interact with the outside world to get input.  The raw_input() function waits for the user to type some input and press return.  It then gets whatever was typed.

>>> raw_input()
some input
'some input'

It’s not obvious what is going on here.  When you hit return at the end of the first line, a blank line appears.  You type what you want into the line and when you hit enter Python gets the line and (in this case, because we’re in an interactive window) prints what it got.  Do it yourself to see, because the text doesn’t show how it happens.

We might have instead assigned the input to a placeholder:

>>> a = raw_input()
some more input, where is it all going?
>>> # note it hasn't printed anything?
...
>>> a
'some more input, where is it all going?'

In a program this allows us to get information into the program, which might come in handy for maths (aka ‘math’) homework:

>>> a=raw_input()
45
>>> b=raw_input()
23
>>> a+b
'4523'

Ooops!  The input that Python is getting is returned to us as strings.  And strings have a funny form of plus called concatenation.  We can use what we learned earlier to push this input into numbers:

>>> int(a)+int(b)
68

That’s what we were looking for (notice that there are no quotes around 68, because it’s a number now).

We are working in the interactive shell at the moment so the context of what is going on is clear.  However, when running a python program “in the wild” there won’t be that context.  You can add some information for the user if you put a message inside the raw_input brackets.  The message must be a string – so it must have quotes or it must be a variable which holds something which has quotes:

>>> a=raw_input('Enter your number here: ')
Enter your number here: 34

Can you see the string has been reproduced in front of the place you type?  This is called a ‘prompt’ because it prompts you to enter something.

Range and For

>>> range(5)
[0, 1, 2, 3, 4]
>>> for i in range(5):
...   print i
...
0
1
2
3
4
>>>

Strings are not numbers

>>> a='5'
>>> a+1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> a=5
>>> a+1
6
>>>

Notice that when the number is in quotes ‘5’ it’s not a number anymore (it’s called  a string).   When it doesn’t have quotes it’s treated as a number which can be added.

In fact, the issue isn’t that you can add numbers, but not strings, it’s that ‘5’  and 5 are different ‘types’.  ‘5’ is a string but 5 (no quotes) is an integer.  The two ‘types’ don’t mix. But you can still ‘add’ two strings together:

>>> a='5'
>>> a+'1'
'51'
>>>

Note here though that ‘1’ is not a number, it’s a string (because it has quotation marks around it).  Note also that it’s a sort of addition, but not as we’re used to it.   It’s called ‘concatenation’ which sort of means sticking together end to end.

Try it with some other strings:

>>> a = 'hello'
>>> b = 'there'
>>> a+b
'hellothere'
>>> # hmmmm. maybe I need to add a space?
...
>>> a+' '+b
'hello there'

If you have a string, but want to have a number, Python has a way of trying to push it into a number, called int(). You put the string in the brackets and int will give you a number back if it can.  Sometimes it can’t.

>>> int('5')
5
>>> int('hi there')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hi there'
>>>

So, if you ever know you’ve got a number trapped inside a string, you can sometimes still get it out if you remember the int() function.

>>> a = '5'
>>> a+1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> int(a)+1
6
>>> a
'5'
>>>

See, in this example, that a is still a string, but we’ve managed to push its number out of it.

This is very important as you will often receive numbers hidden in strings and will need to convert them before you can do anything with  them.

Hello world!

(Works for both Python 2.7 and Python 3)
Your first program, for reasons lost to the mists of time, must always be a “hello world!”  If you don’t do it, something bad will happen to you (or one of your friends, relatives, distant relatives, acquaintances or some other citizen of your country).  Believe me, it is scary.

So, to avoid such a horrible fate, repeat after me:

>>> print('hello world!')
hello world!
>>>

Phew! We’re done.    You should notice that the print statement here did something – it printed the letters between the ” (inverted commas) and it printed them on the next line.  Try it for yourself, but remember to press the enter key at the end otherwise nothing will happen.

Congratulations, you’re now a programmer (in training).