Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation.
Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming. It is often described as a "batteries included" language due to its comprehensive standard library.
What you should already know
This guide assumes you have the following basic background:
- A basic knowledge of English.
- General PC skills
Using the Python Interpreter
The Python interpreter is usually installed as /usr/local/bin/python3.10 on those machines where it is available; putting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing the command:
python3.10
to the shell. Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative location.)
On Windows machines where you have installed Python from the Microsoft Store, the python3.10
command will be available. If you have the py.exe launcher installed, you can use the py
command. See Excursus: Setting environment variables for other ways to launch Python.
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +
, -
, *
and /
work just like in most other languages (for example, Pascal or C); parentheses (())
can be used for grouping. For example:
2 + 2
50 - 5*6
(50 - 5*6) / 4
8 / 5 # division always returns a floating point number
Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...'
) or double quotes ("..."
) with the same result 2. \
can be used to escape quotes:
'spam eggs' # single quotes
'doesn\'t' # use \' to escape the single quote...
"doesn't" # ...or use double quotes instead
'"Yes," they said.'
"\"Yes,\" they said."
'"Isn\'t," they said.'
Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.
squares = [1, 4, 9, 16, 25]
squares
Like strings (and all other built-in sequence types), lists can be indexed and sliced:
squares[0] # indexing returns the item
squares[-1]
squares[-3:] # slicing returns a new list
All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:
squares[:]
Lists also support operations like concatenation:
squares + [36, 49, 64, 81, 100]
Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:
cubes = [1, 8, 27, 65, 125] # something's wrong here
4 ** 3 # the cube of 4 is 64, not 65!
cubes[3] = 64 # replace the wrong value
cubes
First Steps Towards Programming
Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:
# Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while a < 10:
print(a)
a, b = b, a+b
Perhaps the most well-known statement type is the if statement. For example:
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
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.
If you’re comparing the same value to several constants, or checking for specific types or attributes, you may also find the match
statement useful. For more details see match Statements.
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. For example (no pun intended):
# Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
If you do need to iterate over a sequence of numbers, the built-in function range()
comes in handy. It generates arithmetic progressions:
for i in range(5):
print(i)
The given end point is never part of the generated sequence; range(10)
generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):
list(range(5, 10))
list(range(0, 10, 3))
list(range(-10, -100, -30))
break
and continue
Statements, and else
Clauses on Loops
The break
statement, like in C, breaks out of the innermost enclosing for
or while
loop.
Loop statements may have an else
clause; it is executed when the loop terminates through exhaustion of the iterable (with for
) or when the condition becomes false (with while
), but not when the loop is terminated by a break
statement. This is exemplified by the following loop, which searches for prime numbers:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
The pass
statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)