Hello World 2, in Python 3

Hello World is the famous minimal introductory program for many programming languages. But as soon as it’s served its purpose, it’s discarded in the dust of history for more exciting things, such as data types or expressions… This is politically incorrect discrimination and must be stopped! This loyal and true didactic program should have the right to features and bugs just like any other! So ladies and gentlemen, please welcome the New and Improved Hello World, version 2.0!

Just to remind you, the traditional first program in Python (and other programming languages) is “Hello world!”:

print('Hello, World')

Type this after the ‘>>>’ prompt in your interpreter, or into your IDE. Run it and be greeted in the time-honoured tradition of most introductory programming texts! But, you’re itching to get on with some serious programming, so let’s make this more interesting!

What’s My Name?

Don’t greet ‘World’, greet me, by name! So, we need a way for the program to get my name. We could supply our name after typing the program name, like:

$ ./hello.py Monty

#!/usr/bin/python3
import sys
 
if len(sys.argv) > 1:
    name = sys.argv[1]
    print("Hello", name)

We need to import the sys module, to get access to the command-line arguments via sys.argv Note that we need to check if some were given; if not, the length of the sys.argv list would be 1 (the program name or path itself is in sys.argv[0]), and trying to access the second element would upset Python. In which case we could just ask:

#!/usr/bin/python3
import sys
 
if len(sys.argv) > 1:
    name = sys.argv[1]
else:
    name = input("Please tell me your name: ")
    if name == '': name = 'Monty
 
print ("Hello", name, " You're wonderful!")

I have arranged for it to provide the default name of ‘Monty’ in the case that I still don’t give my name.

Is it Still Morning?

Now, let’s make it greet us appropriately to the time of day:

import datetime
hour = datetime.datetime.now().hour
name=input("Please tell me your name: ")
if hour < 12:
    print ("Good morning", name)
elif hour < 18:
    print ("Good afternoon", name)
else:
    print ("Good evening", name) 
 
print ("You're wonderful!")

Not quite a Chatbot…

Nice, but now recall that the usual human convention on greeting someone, is to follow it up with a little small talk. Like this:

#!/usr/bin/python3
import sys
import random
import datetime
 
remarks=['Isn\'t it a nice day!',
         'How are you today?',
         'I hear there was another shooting']
reply=['Really?', 'Oh wow!', 'Yeah...','Cool!']
 
if len(sys.argv) > 1:
    name = sys.argv[1]
else:
    name = input("Please tell me your name: ")
    if name == '': name = 'Monty'
 
hour = datetime.datetime.now().hour
 
if hour < 12:
    print ("Good morning", name)
elif hour < 18:
    print ("Good afternoon", name)
else:
    print ("Good evening", name)
 
input (random.choice(remarks))
print (random.choice(reply), "Oh well, see you later!\n")

What the Internet was Built for

Would you like a cat picture with that? Of course you would! Just append the following lines to the program, and feel free to move the import statements to the top:

import urllib
from PIL import Image
 
catapi="http://thecatapi.com/api/images/get?format=xml&results_per_page=1"
response = urllib.request.urlopen(catapi, timeout = 5)
imgurl = response.read().split()[6][5:-6].decode("utf-8")
Image.open(urllib.request.urlopen(imgurl, timeout = 5)).show()

Note that this is not an example of a well-written program – I’ll improve it in my next post.

Command Line too Hard for You?

In case you’d prefer a GUI for your greeting program, here is a minimal example. I leave the inclusion of the new features (& bugs?) as an ‘exercise for the reader’.

Tkinter is Python’s de-facto standard GUI (Graphical User Interface) package. It is a thin object-oriented layer on top of Tcl/Tk.

from tkinter import *
 
root = Tk()
 
w = Label(root, text="Hello, Monty!")
w.pack()
 
root.mainloop()

What other features do you think the new Hello World program should have? Did you spot the bug? Leave your suggestions below!

A Quick Introduction to Python 3 Programming

This Quick Introduction to Python 3 aims to teach you just enough Python, so that you can get started in computer programming, and try out some of the example codes on this site!

First, you’ll want to install Python 3. If you have Python installed, you can use any text editor to start with (but do not use a word processor). You might find it useful to start up the Python interpreter and type in the examples as we go.

The Python Interpreter

Experienced programmers in any other language can pick up Python very quickly, and beginners find the clean syntax and indentation structure easy to learn. – Python.org

Do you have the Python interpreter already installed on your computer? To find out, open a command line and type “python” (without the quotes). Hopefully you’ll get something like this:

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Python 2 is almost always readily available on Linux; probably Macs too; Windows I don’t know. If your computer doesn’t have it then go to https://www.python.org/ and get the latest version (3.4.3 at this time). Follow the instructions to install it. You’ll also want to do this if your installed version is less than 3.

The traditional first program in Python (and other programming languages) is “Hello world!”:


 print "Hello world!"

Type this after the ‘>>>’ prompt in your interpreter. If it’s version 2 it’ll obligingly print ‘Hello World!’, but version 3 will complain:

File "<stdin>", line 1
 print 'Hello World!'
                    ^
SyntaxError: invalid syntax

Version 3 changed the print statement to being a function call (more on that later) which requires parentheses around the thing to be printed (as well as the quotes). In your Python 3 interpreter (invoked as python3 if necessary) type print (“Hello World!”), and hopefully it will! You can also get the same result by just typing in “Hello World!” (with the quotes), without the print function call. Try typing in some arithmetic, like ‘2*3′. No need to say print! However outside the interpreter you’ll need the print function.

Statements & Expressions

The line of text in our first program is called a statement. It’s like a sentence in English (sort of). The statement usually appears on a line of its own, and comprises ‘smaller’ bits like identifiers (names for things such as data), keywords (reserved words that tell Python what to do), operators (like arithmetic symbols) etc. You can think of it as an instruction for the computer to do something, like print some text. We’ll meet various kinds of statement, like assignment and conditional statements. An expression is a part of a statement where a little bit of computation is required, e.g. x = 2 * 3

Assignment Statements

A program is a set of instructions (‘algorithm‘) and some data that tell a computer how to perform a task, for example, to convert a temperature in Centigrade, to Fahrenheit. This data could take many forms, but for now we’ll assume it’s a set of numbers. And we’ll need some working storage (‘memory‘) where we can save intermediate results. When we put these results in the memory, we’ll give them names and let the computer take care of figuring out where they are in the memory. You can store data in memory using assignment statements.

maxit = 100
temperature = 50.1
distance = 100
greeting = "Hello"

The first text, before the ‘=’, is the name or identifier you have chosen for your item of data; it’s often called a variable because (normally) your program may change it later. An identifier is a name used to identify a variable, function, class, module or other object. It starts with an uppercase or lowercase letter, or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). The ‘=’ assigns a value (e.g. 100) to the variable. Data values have particular types, e.g integers, floats, strings, boolean, complex etc.

Arithmetic

Calculations are simple with Python, and expression syntax is straightforward: the operators +, -, * and / work as expected; parentheses () can be used for grouping. – Python.org.

Python can do arithmetic such as add, subtract, multiply, and divide, using these operators: + – * / We can write arithmetic expressions as you’d expect to see them in mathematics, with some small exceptions, e.g. y = m * x + c You can’t write variables next to each other to signify multiplication; all operations must be explicit. Operands must be one of:

  • Integer: whole numbers, zero, positive, or negative, e.g. 1, 2, -3, 0
  • Floating Point: numbers with decimal point, e.g. 3.14, -0.8

If x is 2, and y is 3, then:

OperatorDescriptionExample
+AddAdds the values on either side of the operator.x + y -> 5
SubtractSubtracts right side operand from left side operand.x – y -> -1
* MultiplyMultiplies values on either side of the operatorx * y -> 6
/ DivideDivides left side operand by right side operandx / y -> 0.666…
% ModulusDivides left side operand by right side operand and returns remainderx % y -> 0
** ExponentRaise left operand to power of right operandx ** y -> 8
// Floor Division Division where the result is rounded away from zero (towards negative infinity)7//2 = 3 and 7.0//2.0 = 3.5

A Programming Example

Let’s have an example. Let’s convert a temperature given in Centigrade degrees,°C, to Fahrenheit,°F. From Physics, we know that there’s a simple formula: F = C * 9 / 5 +32. That is, multiply the value in Centigrade by 9, divide that by 5, and then add 32. So what is 0°C in F? It’s 32. The freezing point of water is 0° in C, but 32° in F. How about 100°C? The order of operations in C * 9 / 5 isn’t important, so let’s divide 100 by 5 first. That’s 20. Now multiply by 9; that’s 180. Now add 32. That’s 212°, the boiling point of water in Fahrenheit.

Note that in the following, I’m a bit carefree about integers and floats; I use integers for simplicity, but in serious applications you might do better to use floats if they better represent the real-world values!

C = 50
F = C * 9 / 5 + 32
print(F)

Our program (let’s call it C2F.py) is a sequence of instructions, executed one after the other, starting with the first one, C = 50:

  1. Set the variable C to the integer value of 50 (If you prefer, you can write ‘.0’ after each number.)
  2. Multiply C by 9, divide the result by 5, and add 32 to that
  3. Print the answer

String Theory

In our “Hello, World!” example, we wrote it one time with “double quotes”, and one time with ‘single quotes’: ‘Hello, World!’. Text, when enclosed in quotes (either kind) is called a string. Strings are very useful not only for greetings, but also for programs to tell you the results of computations, or to tell you what input is needed next, or for storing information like people’s names, or for labelling graphs, etc. Note that if you need a string to contain quotes, you must either use the other style of quote (single or double) to enclose it, or ‘escape’ the internal quote with a backslash: “This is Freddie’s cat” or ‘This is Freddie\’s cat’.

You can do a limited amount of ‘arithmetic’ on strings – you can add or multiply them! So if a contains ‘a’, and b contains ‘b’, then a + b is ‘ab’ (this is called concatenation), and a * 3 is ‘aaa’. You can’t subtract or divide them however.

Input & Output

Outputting a result can be done with print() as we’ve just seen. We could make it a little more helpful if we write it like this: print(“The temperature is “, F, “F”).

This is all well and good, whenever we want to convert 50°C to F. But it’d be much more useful if we could somehow tell it any value of C! We can do this just by replacing the first line, C = 50, with: C = input(“Enter the Centigrade temperature:”) It prints out “Enter the Centigrade temperature:” (without the quotes) and waits for the user to type in something.

But if we try to do arithmetic on C, Python will complain about ‘unsupported operand type(s)’. This is because input() delivers the user’s input as a string of characters – it doesn’t know that we want it as a number. So we feed that string into int() (for integer) or float() (for decimal-pointed numbers). When it has that number it does the arithmetic, and prints out the result.

Branching Conditions

In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test … is a simple comparison. The standard comparison operators are written the same as in C:<(less than),>(greater than),==(equal to),<=(less than or equal to),>=(greater than or equal to) and!=(not equal to). – Python.org

Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. If the condition is true, one path of code is taken, but if not, another path is taken. For example:

x = 3
if x > 0:
    print("x is positive")
else:
    print("x is zero or negative")

Let’s meet another data type:

  • Boolean: True or False. For example, 4 > 3 is True, 2 > 3 is False, 2 == 2 is True, 3 == 2 is False.

Boolean has only 2 values: True or False. Usually the result of a comparison, e.g. x > 3 is True if x is 4, but False if x is 2. It can also result from testing for equality, e.g. x == 3 is True if x is 3, False otherwise. Note the double equals! You will ( I repeat, will) at some point in your Python programming career, write x = 3 when you want to know if x is 3!

Here are the comparison operators that you can use in boolean expressions:

  • == equality
  • != not equal
  • > greater than
  • >= greater than or equal
  • < less than
  • <= less than or equal

If Statements

Python knows the usual control flow statements that other languages speak — if, for, while and range — with some of its own twists, of course. – Python.org

What if we want to convert temperatures in the other direction – F to C? Well the formula is C = (F – 32) * 5 / 9. Why don’t you re-write the previous program and call it F2C.py Whenever we want to convert Fahrenheit to Centigrade, we’ll use this one. So whenever you have a temperature conversion to do, you’ll reason something like this:

If I want to convert C to F then
    run C2F.py
otherwise (I want to convert F to C)
    run F2C.py

Now we have 2 programs that look very similar and have the same physical constants in them (9, 5, and 32). We could simplify things a bit, if we could combine them into one! But how will the computer know which conversion we want? Sounds like we need another input()!

which = input("Is your temperature C or F?").lower()
value = int(input("What is its value? "))
if which == 'c':
    result = value * 9 / 5 + 32
elif which == 'f':
    result = (value - 32) * 5 / 9
else:
    result = 'Please enter C or F'
print(result)

Indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount. – Python.org

  1. Let’s assume that the user types a ‘C’ or an ‘F’; .lower() converts to lowercase (so it doesn’t matter if the user types ‘C’ or ‘c’); this goes into the variable ‘which’
  2. ‘if‘ test the value of the following Boolean expression, which == ‘c’. Note the ‘:’ at the end of the line. If the expression is True then the following block is run:
  3. –> compute the Fahrenheit value, put it in result variable
  4. else if ‘which’ contains ‘f’:
  5. –> compute the Centigrade value, put it in result variable
  6. otherwise:
  7. –> store ‘Please enter C or F’ into result
  8. print the result

There can be zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif … sequence is a substitute for theswitchorcasestatements found in other languages. – Python.org

Looping

A loop is a sequence of statements which is specified once but which may be carried out several times in succession. The code “inside” the loop (the body of the loop) is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely.

While Loops

Suppose that we have several temperatures that we want to convert. Well, we could run the appropriate program (C2F.py or F2C.py) several times. But it would be nicer if the program could ‘start over’ by itself, till I indicate I’m done:

done = False
while not done:
    C = int(input("Temperature in C:"))
    F = C * 9 / 5 + 32
    print(F)
    done = input("Another?") != 'y'
  1. done is a boolean variable, initialised to ‘False’
  2. while means “repeat the following block as long as the test (‘not done’) is True:
  3. –> get the user’s value of C
  4. –> compute F
  5. –> reset the boolean done: if the user answers with ‘y’ then it’s True, otherwise False

For Loops

The “for” statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. – Python.org

while isn’t the only looping construct in Python; perhaps better-known is the for-loop, which repeats the enclosed block a fixed number of times:

for i in range(10):
    print(i)

The built-in function range() iterates over a sequence of numbers, generating arithmetic progressions. In this example, it generates integers from 0 to 9.

Compound Data

Sometimes you need several items of data together, representing multiple measurements or different facets of the world; such as arrays, records, files, data bases etc.

Lists

Lists (known as arrays in other languages) are one of the compound data types that Python understands. Lists can be indexed, sliced and manipulated with other built-in functions. – Python.org

Alternatively, instead of asking the user to supply all the values, we could put them straight into the program. Maybe you’re just writing a quick little program to do some number crunching, so you don’t need the fancy prompts! Well, we can put the data in a list (‘array’ in other languages, and math).

temps = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for temp in temps:
    print(temp, "C is ", temp * 9 / 5 + 32, "F")

Lists might contain items of different types, but usually the items all have the same type. Also, lists can contain lists (aka, 2D arrays)!

Files

Lists are very handy, but you might prefer sometimes to process data that’s in a file rather than right there in your program. We can do this very easily, with very little change to our program:

temps = open('Temperatures.C')
for temp in temps:
    _ = int(temp)
    print(_, "C is ", _ * 9 / 5 + 32, "F")

Instead of the list, we now have open(‘Temperatures.C’) (or whatever name your file has if not Temperatures.C). What is read from the file, each time the for loop iterates, is a string, hence the _ = int(temp). The _ is just some anonymous variable that we needn’t bother giving a name to – but you can, if you prefer (e.g. because it helps document the code).

Looping Around Conditionals

A very common pattern in programming is to loop over some data while testing it for some condition so as to process it accordingly. The simplest example is probably where some abnormal value of the data is used to signal the end of the data, e.g. if we’re calculating average height, zero or negative indicates end of data:

sum = 0.0
num = 0
done = False
while not done:
    height = float(input("Enter a height or 0 to finish: "))
    if height <= 0:
        done = True
    else:
        sum += height
        num += 1
 
print ("Average height is ", sum / num)

There is an error in this program. What is it, and how would you fix it?

Comments

Another important thing to know about is ‘comments’. You can put text in your program that isn’t Python code, such as explanations about how the code works. Anything between triple quotes (single or double, so long as they’re the same) will be ignored. Anything after ‘#’ on the same line will be ignored.

'''   Test the first N numbers for primality.
    Count up to N, dividing by primes known so far.
    Add this number to the list of primes if none divide into it.
'''
N = 1000                    # N is how many numbers to test
primes = []                 # List of primes so far
for n in range(2,N+1):      # For each number from 2 to N:
    for p in primes:            # For each prime so far:
        if n % p == 0: break        # If it divides into it, it's not prime
    else:                       # No primes divided into it so
        primes.append(n)            # Add it to the list
print(primes)

When range() has 2 arguments, the first one is the starting number, and the second one is the next number after the end of the range! So we have to add 1 if we want the range to include the Nth number. The ‘%’ operator is modulus, i.e. the remainder left by dividing the first operand by the second. It’s very useful to tell if one number is evenly divisible by another, because if it is, the remainder is 0.

Error Handling

What happens when things go wrong? They will! The user might enter a value that isn’t right, such as a value out of range, or ‘K’ when we wanted ‘C’ or ‘F’. In simple cases like that you can just have an ‘else’ clause to catch the values that are ‘none of the above’, and print out an error message. For more difficult cases, e.g. a number has invalid digits, you can use Python’s exception handling. It looks like this:

try:
    number = int (string)
except:
    print(string, "isn't a valid number")

So Python will try to convert string to an integer, but if it can’t, it will perform the except block, otherwise execution continues after the except block.

Here’s a better version of our temperature converter:

''' Temperature Convertor.
    to illustrate minimal Python
'''
done = False          
while not done:                 # Repeat until the done flag gets set
    
    which = 'x'                     # Give which a value that isn't c or f
    while which not in 'cf':        # repeat until user gives good value:
        which = input("Is your temperature C or F? ").lower()   # lowercase it
    
    try:                            # we want a floating point number
        value = float(input("What is its value? "))
    except:                         # but didn't get one :()
        print("Not a number")
        continue                    # continue loop from beginning
    
    if which == 'c':                # Centigrade -> Fahrenheit
        result = str(value * 9 / 5 + 32) + 'F'
        
    elif which == 'f':              # Fahrenheit -> Centigrade
        result = str((value - 32) * 5 / 9) + 'C'
        
    else:
        pass                # Cannot possibly get here !
        
    print(result)
    
    done = input("Another? ").lower() != 'y'    # != is 'not equal'

print("Done!")

Functions

The core of extensible programming is defining functions. Python allows mandatory and optional arguments, keyword arguments, and even arbitrary argument lists. – Python.org

A function is a piece of code ‘wrapped up’ in a way that enables us to use it like we used the range() function – it gets a name and some arguments that supply its input values. So if we wanted, for example, to make our temperature conversions re-usable, we could declare these functions:

def C2F(value):
    ''' Centigrade to Fahrenheit '''
    return value * 9 / 5 + 32
 
def F2C(value):
    ''' Fahrenheit to Centigrade '''
    return (value - 32) * 5 / 9
 
print(C2F(0))
print(C2F(100))
print(F2C(32))
print(F2C(212))

“def” declares that a function definition is coming. First, the name, then in parentheses, the value or values. The line ends with a colon indicating that an indented block of code will follow. There is then an optional comment, called a docstring, which may be used by tools to automatically document your code. When the function is called, the conversion is calculated, and the result appears in the place where the function was called.

Functions are an extremely important addition to your programming repertoire! They enable:

  • Unit testing, like the above prints of known correct values;
  • Modularisation, dividing your code into easier to understand pieces;
  • Object-oriented programming which further improves code modularity;
  • Reusability, either in the same program, or in others by use of modules (files which can be imported);
  • Recursion, where a problem can be solved by repeatedly breaking it down into smaller instances until a trivial base case is reached.

What Next? Getting Started With Python