Introduction to Python
Introduction to Python
Variables, the three basic data types, reading input, and the for loop โ everything you need to write your first real programs. Run every example right here; finish with four auto-graded exercises.
The Python language
Python is a modern programming language whose popularity keeps growing.
- its author is Guido van Rossum (he created it in 1989)
- it is used at Google, YouTube, Dropbox, Mozilla, Quora, Facebook, Raspberry Pi, โฆ
- many top universities teach it as a first language: MIT, Carnegie Mellon, Berkeley, Cornell, Caltech, Illinois, โฆ
- it runs on Windows, Linux and Mac. It is freeware and open source.
Unlike many other languages that are compiled (e.g. Pascal, C/C++, C#), Python is an interpreter. This means:
- the interpreter does not produce an executable file (e.g. an .exe on Windows)
- to run a program, Python must be installed on the computer
- the interpreter also allows interactive work with the environment
Key properties of Python: very simple, highly readable syntax (which makes it great for teaching); it is dynamically typed, so there are no type declarations; it supports advanced features of modern languages (data structures, object-oriented design); it is a general-purpose language for data analysis, media processing, networking and more; and it has a huge, welcoming community.
Starting Python
From python.org download the latest version and run the installer. During installation we recommend: install for all users, add Python to PATH, and include pip, tkinter and IDLE. The bundled IDLE environment is ideal for a complete beginner and is what we use in this course.
When you launch IDLE you see the version info and, at the start of the line, the three characters >>> โ the prompt. After this prompt we type commands for Python:
>>> 12345 12345 >>> 123 + 456 579 >>> 1 * 2 * 3 * 4 * 5 * 6 720
This interactive window is called a shell, and it runs a REP loop: Read the line, Evaluate it, Print the result โ and repeat. Try it yourself below (this editor runs real Python, just like the shell โ use print() to see results):
The three basic data types
Python provides several types of data. To start, we meet three: integers, floats and strings. Every type has a name:
- int โ integers, e.g. 0, 15, -123456789. Their size is limited only by available memory (millions of digits are fine).
- float โ decimal numbers, e.g. 3.14159, 33e50. They contain a decimal point or an exponent, and have limited precision (~16โ17 significant digits).
- str โ strings, written between apostrophes 'text' or quotes "text".
You can ask Python for the type of any value with the type() function, and each type defines its own operations:
Integer operations (both operands must be integers)
| + | addition | 1 + 2 โ 3 |
| - | subtraction | 2 - 5 โ -3 |
| * | multiplication | 3 * 37 โ 111 |
| // | integer division | 22 // 7 โ 3 |
| % | remainder (modulo) | 22 % 7 โ 1 |
| ** | exponentiation | 2 ** 8 โ 256 |
String operations
| + | concatenation (joining two strings) | 'a' + 'b' โ 'ab' |
| * | repeated concatenation | 3 * 'x' โ 'xxx' |
Repeated concatenation is unusual but handy โ 10 * ' :-) ' repeats the smiley ten times. Experiment:
Variables and assignment
So far we only worked with values. To remember a value for later we use a variable. Unlike Pascal or C, where a variable is a named, reserved memory slot, in Python a variable is a name attached to an existing value in memory. A variable is created not by declaration but by running an assignment statement:
premenna = hodnota # name = value
The value on the right is computed first, then the name on the left is bound to it. A name can refer to at most one value, but several names may refer to the same value. The classic example is increasing a variable by referring to itself:
>>> ab = 13 >>> ab = ab + 7 # right side 13+7=20 is computed first, then stored back into ab
- may contain letters, digits and the underscore _
- are case-sensitive (age โ Age)
- must differ from Python's reserved words (for, if, def, return, โฆ)
Programming mode: print(), input() and conversions
In a saved program (a script, usually a .py file), typing a bare expression does nothing โ its value is ignored. To show a value you must use print(), which prints its arguments separated by spaces:
a = 17 b = 'abcd' print(a) print(b) print('the result is', 3 + a * 2)
The input() function prints an optional prompt and then waits for the user to type a line ending with Enter; it returns that line as a string. Watch what happens if we forget that it is a string โ a "euro โ koruna" converter that multiplies by 25:
amount = input('enter euros: ') koruna = amount * 25 print(amount, 'euro is', koruna, 'koruna') # input '100' โ '100' * 25 โ '100100100100โฆ' (the string repeated 25ร!)
The type names int, float, str double as conversion functions:
- int('37') โ 37 ยท int(3.14) โ 3
- float('3.14') โ 3.14 ยท float(333) โ 333.0
- str(356) โ '356'
So the fix is amount = float(input('enter euros: ')). Most of our programs will begin by reading input and converting it to the right type.
Try the fixed converter โ change the input box below to feed it different values:
The for loop
The for loop repeats a block of indented statements. The simplest form runs a fixed number of times using range(n), which generates the integers from 0 to n-1:
for i in range(4): print(i, 'row') # prints: 0 row / 1 row / 2 row / 3 row
The loop variable (i) automatically takes the values 0, 1, 2, โฆ, n-1. The block is everything indented by 4 spaces; the first non-indented line runs after the loop ends. With two arguments, range(5, 15) starts at 5 and stops before 15.
A pattern you'll use constantly: initialise a variable before the loop, update it inside, read the result after. Summing 0+1+โฆ+(n-1):
total = 0 for i in range(n): total = total + i print(total)
The loop can also walk over listed values (for x in 5, 7, 11:) or over the characters of a string (a string is a sequence of characters). This computes 6! by multiplying โ run it and change the numbers: