3: Conditionals/if and Code Blocks

Book ref: 70ff

Python 2.7: Same, see earlier post

Note: this tutorial will be easier if you use Python-IDLE, not Python (Command Line).

So far, the programs you’ve written have gone straight from top to bottom, without skipping any lines. There are times though, when you do want a line to run only some of the time. For example, if you wrote a game, you’d only want one of these two lines of code to run:

print("Congratulations, you win!!!") 
print("Sorry, you lose.")

In fact, you’d want your code to look something like:

if player wins:
     print("Congratulations, you win!!")
     print("Sorry, you lose.")

Python isn’t quite that much like English, but it’s pretty close. In Python you can do this by using the if and else (not otherwise) keywords, like this:

player_wins = True

if player_wins:
    print("Congratulations, you win!!")
    print("Sorry, you lose.")

You see I’ve changed the two English words player wins to a single Python name player_wins. When you run this code, you get this output:

Congratulations, you win!!

If you change the line

player_wins = True


player_wins = False

(try it) then this is printed:

Sorry, you lose.

You need to remember that player_wins is just the name you’re using to store a value, the program can’t tell whether the player has won or lost. You need to set the value beforehand. You also need to notice that player_wins takes only two values – True and False (True and False are special values in Python, but you can take them as having their English meanings).

The if keyword needs to be followed by something that is either True or False. It could be a variable that holds one of those values or it could be an expression (see below) that evaluates to them. After “that something” you put a colon. The colon tells Python that a new code block is about to start. On the next line the code in the code block is indented. This indenting is important. Python will complain if the code is not indented (try it). If you want more things to happen, then you can put in more lines of code, as long as they’re all indented at the same level – that is, they have the same number of spaces in front of them (try 4 spaces in front). When you do more Python you’ll discover that you can put code blocks within code blocks – but that’s for later.

After the code block comes another keyword, else, followed by a colon and another code block. The else keyword serves the function of word otherwise in my mock code above. It is run if the if isn’t. After the else is another code block. This is indented like the first one and, like the first one, can contain more lines of code, as long as they are all indented with the same number of spaces in front of them.

Visually indented code blocks are one of Python’s great programming features. Most languages have code blocks, but few of them require them to be shown visually with indents. This makes Python programs easier to read and follow.

If you don’t have alternative code that is to be run if the conditional is not True, then you can leave out the else: and its code block. So, if you want to say Happy Birthday if it’s someone’s birthday, but nothing if it’s not, you could do something like this:

players_birthday = False

if players_birthday:
    print("Happy Birthday!")

When you run this code, it doesn’t print anything, because you’ve set players_birthday = False and have not included an else block. Set players_birthday = True and see what happens.


Rather than setting a value of True or False expressly, you can include a comparison. Python has a lot of comparisons but the main ones are == (equal- note the two equal signs together, not one), > (greater than) and < (less than). Here are some of them in action:

>>> 1 == 1
>>> 1 == 2
>>> 1 > 2
>>> 1 < 2

See how they give either a True or False result? Try some yourself. Make sure you know the difference between 1 = 2 and 1 == 2.

Going back to our earlier example, rather than having a name player_wins, you’re probably more likely to have something like players_score. You can then compare the score against a winning score and print your message. For example, if they players_score is 100 and a score of greater than 90 is a win you could code this:

players_score = 100

if players_score > 90:
    print("Congratulations, you win!!")
    print("Sorry, you lose.")

Run it, then change players_score = 90 and run it again.

3: Getting Input

3: Getting Input

Book ref: Pg 60ff
Python 2.7: this function is called raw_input() in Python 2.7.

Pretty much any program you’re ever going to write will involve 3 parts – getting data, processing data and outputting a result. In your Hello world! program you learned one way of outputting data with the print() function. In 3: Python for Homework you learned how to process some data. But you still don’t have a way to get data into the program. That’s what this post is all about – input().

You use the input() function get string literals that the user types in at the keyboard. Try it now:

>>> input()
this was a blank line before I typed this
'this was a blank line before I typed this'

You need to type input() and hit enter to really understand what is happening here. When I typed enter, Python gave me a blank line. Then I typed “this was a blank line before I typed this” and hit enter again (you should type anything you like). Then it echoed (repeated) what I typed back to the screen.

If you put your own string literal inside the brackets the input() function will echo that literal before it gets input from the user. Here is an example:

>>> input("What is your name?")
What is your name?Brendan

Instead of a blank line, input gave me a line starting with What is your name?. You can use this to tell the user what it is you want them to input. Notice also that there is no space between the question mark and the start of my answer. This is because Python has no idea about English grammar. You have to do that for Python. Remember to add a space to the end of your literals so that they look right:

>>> input("What is your name? ")
What is your name? Brendan 

That space makes all the difference, don’t you think?

You can save the literals that someone types in by naming them – exactly how you saved literals in the earlier post. If you name the literal it is not echoed, but you can see it by printing the name you gave it. Here is an example:

>>> users_name = input("What is your name? ")
What is your name? Brendan 
>>> print(users_name)

Python thinks that everything that the user types is a string literal – so you can’t enter a number and expect to be able to add and multiply (etc) it:

>>> users_number = input("Please type in a number: ")
Please type in a number: 11
>>> users_number * 2
>>> users_number + 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Can't convert 'int' object to str implicitly

When you typed in 11, Python attempted to multiply it by 2 and got “1111” – that is, 11 repeated rather than 22. When you tried to add 2 to it, it failed completely. If you are expecting your user to enter a number you need to use another function, called int() to convert it to a ‘Python number’:

>>> int(users_number) * 2
>>> int(users_number) + 2

But notice, unless you rename it, the int() function does not change what’s stored (try users_number * 2 again). You can rename it by putting the name on both sides of the equal sign like this:

>>> users_number = int(users_number)
>>> users_number * 2

Now, Python is happy to treat this as an honest-to-goodness number.

If your user inputs a decimal number, int() won’t work. In that case you need to use a similar function, called float() instead:

>>> users_number = input("Please type in a decimal number: ")
Please type in a decimal number: 2.5
>>> int(users_number)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: '2.5'
>>> float(users_number)

You can get the rough equivalent age of a dog in human years by multiplying it by 7 (purists will quibble that this is too inexact). For example, ie a 1 year old dog is roughly 7 human years old. Now write a short program to calculate the age of your dog in human years (notice here, I’m printing more than one thing by adding a comma between the things I’m printing):

>>> dog_age = input("How old is your dog? ")
How old is your dog? 2.5
>>> print("Your dog is about ", float(dog_age)*7, " years old.")
Your dog is about  17.5  years old.

Try it now!

3: Python for Homework

Book ref: Pg 64-66

If you are ever stuck for a calculator, Python can be a stand in for you. It is able to do any calculations that a calculator can do. Some things might be easier on a calculator, but, since Python is a general purpose programming language, there’s a heap of things that Python can calculate that your calculator can’t.
Addition and subtraction are pretty straight forward, just use the + and – keys on your keyboard like this:

>>> 1+1
>>> 2-1

Try some yourself.

In the last post you were using string literals. Here you’re using numbers, but you can use them in the same way that you can with string literals. For example, you can give them names (here, I’m using a and b as very simply names):

>>> a = 1
>>> b = 2

As in the last post, once you’ve named them you can use the names to refer to the numbers indirectly:

>>> a + b
>>> b - a 

Addition and subtraction are easy because you have a plus and minus sign on your keyboard. Not so multiplication or division! Since there’s no times sign on the keyboard, and you aren’t able to write a number on top of another for divide, Python instead uses symbols that are already on your keyboard, You use * for multiply and / for divide (on my keyboard * is Shift-8 and / is next to my right hand Shift key). Note that / starts in the bottom left and goes to the top right. You don’t want \ – that’s a different character. Here are some examples:

>>> 2*3
>>> 6/2

Try some yourself!

In the example above, see that the answer 6/2 gives a decimal answer (ie it ends in .0), even though 2*3 doesn’t. It used to in Python 2. In Python 2 you’d get this:

>>> 6/2

However, Python 2 also did this:

>>> 7/2

When you used / for division and both numbers were whole numbers, Python 2 would round the answer down to the next whole number. If you want to do this in Python 3 (stranger things have happened!) you use a double slash //. Like this:

>>> 7/2
>>> 7//2

The other thing you might be interested in trying is raising a number to a power. To do this in Python you use a double star: **. To calculate 3 squared and cubed respectively you would type:

>>> 3**2
>>> 3**3

To find the square, or cube root, you raise to the power of 0.5 and 1/3 respectively:

>>> 9**(0.5)
>>> 27**(1/3)

Python has the advantage that it can calculate stuff really quickly and display many more digits than your calculator can. If you want to know what 2 to the thousand is, Python can work it out in the blink of an eye:

>>> 2**1000

Try some yourself. If your computer stops responding Ctrl-C should stop it. If not, close the window and restart Python.

3: A Literal Assignment

Book ref: page 39ff

In the previous post you learned about Python’s print feature*. In that post you used print  to display the text:

hello world!

You did that by putting single quotes/apostrophes/inverted commas (‘) around the text to be displayed:

'hello world!'

This thing (inside the single quotes) is called a literal. In fact, it’s a string literal.  You can create any string you like at the command line by typing it in with single quotes around it:

>>> ‘hello world!’
‘hello world!’

Try creating some of your own now.  If you try to type a string at the command line without the single quotes Python gets upset:

>>> hello world!
 File "<stdin>", line 1
 hello world!
SyntaxError: invalid syntax

This failed because there were no quotes around the string.

When you create a literal, Python stores it in memory. However, you can’t get to that literal, because you don’t know where Python has stored it. You can know where Python stores the literal by giving it a name. You do that by:

  1. Thinking of a name
  2. Using the = give the name to the literal.

Here’s an example:

>>> a_name = 'hello world!'

In this case, the name is a_name. You can choose any name you like, subject to some constraints (see page 42 of my book). The main things to mention are that names can’t have spaces in them, and can’t start with a number:

>>> a name = 'hello world!'
 File "<stdin>", line 1
 a name = 'hello world!'
SyntaxError: invalid syntax
>>> 1stname = 'hello world!'
  File "<stdin>", line 1
    1stname = 'hello world!'
SyntaxError: invalid syntax

In the first case, there’s a space after the a. In the second the name starts with a number. Remember to put a single quote at the start and at the end of the string.  Think up a name and assign it to ‘hello world!’ (or think up some other string!).

After you give a name to a literal then, whenever you use that name, it’s the same as retyping the literal:

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

Can you see that print(a_name) gives the same output as print(‘hello world!’)? That’s because thinks if Python is happy to let you Then putting that inside some brackets ():

('hello world!)

Then putting that on the right hand side of print:

print(‘hello world!’)

The text with the

* Actually, “function” is the technical term. You’ll learn about functions in a later post.

3: Hello World!

For those of you interested in learning Python 3, I’m going to start revisiting old blog posts, updating them for Python 3. They might, but probably won’t, be repeating the same order as the original. Python 3 posts will start with a 3 (in case you hadn’t worked out the 3: at the start of this posts’ title).  To do these posts I’m assuming that you’ve:

  1. Installed a version of Python starting with 3 (if you have a version starting with 2, start here).  If you haven’t installed it, follow the instructions on the Getting Started page.
  2. Managed to open Python (command line). You can also use the IDLE editor (and you’ll get onto that later anyways).

For some reason, lost to the mists of time, the first program you write in any language is supposed to be a program, called “Hello World”, that gets the computer to say “hello world”.    So here it is. Open up your Python prompt. You should see something like this:


That thing’s the Python prompt.  Type everything after the >>> in the first line here:

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

When you press the Enter* button at the end of the first line, “hello world!” appears on the next line.  Make sure that you type:

print('hello world!')

in exactly. That is,  (don’t type >>>) but make sure you include the (, ‘, ‘ and ).  If you leave any of them out, it won’t work (try it).

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


*  If you are on a Mac, think “Return Button” whenever I say  Enter button.