This Quick Introduction to Python 3 aims to teach you just enough Python, so that you can get started in computer programming!
First, you’ll want to install Python 3 or you can use the in-browser Trinket near the bottom of the page – just edit the code directly in there. 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!”:
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
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:[python] 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.
Calculations are simple with Python, and expression syntax is straightforward: the operators
/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:
|+||Add||Adds the values on either side of the operator.||x + y -> 5|
|–||Subtract||Subtracts right side operand from left side operand.||x – y -> -1|
|*||Multiply||Multiplies values on either side of the operator||x * y -> 6|
|/||Divide||Divides left side operand by right side operand||x / y -> 0.666…|
|%||Modulus||Divides left side operand by right side operand and returns remainder||x % y -> 0|
|**||Exponent||Raise left operand to power of right operand||x ** 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![python] C = 50
F = C * 9 / 5 + 32
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:
- Set the variable C to the integer value of 50 (If you prefer, you can write ‘.0’ after each number.)
- Multiply C by 9, divide the result by 5, and add 32 to that
- Print the answer
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.
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:[python] x = 3
if x > 0:
print("x is positive")
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
Python knows the usual control flow statements that other languages speak —
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()![python] 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
result = ‘Please enter C or F’
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
- 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’
- ‘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:
- –> compute the Fahrenheit value, put it in result variable
- else if ‘which’ contains ‘f’:
- –> compute the Centigrade value, put it in result variable
- –> store ‘Please enter C or F’ into result
- 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 the switch or case statements found in other languages. – Python.org
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.
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:[python] done = False
while not done:
C = int(input("Temperature in C:"))
F = C * 9 / 5 + 32
done = input("Another?") != ‘y’
- done is a boolean variable, initialised to ‘False’
- while means “repeat the following block as long as the test (‘not done’) is True:
- –> get the user’s value of C
- –> compute F
- –> reset the boolean done: if the user answers with ‘y’ then it’s True, otherwise False
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’sfor 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:[python] for i in range(10):
The built-in function range() iterates over a sequence of numbers, generating arithmetic progressions. In this example, it generates integers from 0 to 9.
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 (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).[python] 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)!
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:[python] temps = open(‘Temperatures.C’)
for temp in temps:
_ = int(temp)
print(_, "C is ", _ * 9 / 5 + 32, "F")[/python]
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 hieght, zero or negative indicates end of data:[python] 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
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?
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.[python] ”’ 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
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.
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:[python] try:
number = int (string)
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:
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:[python] def C2F(value):
”’ Centigrade to Fahrenheit ”’
return value * 9 / 5 + 32
”’ Fahrenheit to Centigrade ”’
return (value – 32) * 5 / 9
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.