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:
Exercises
0 / 23 solved · auto-graded, runs in your browser
Roots & powers
○** with a fractional exponent computes roots (e.g. x ** 0.5 is √x). Assign and print:a1= the square root of 3a2= one third of the cube root of 5a3= the 5th power of the 5th root of 1024a4= the 10th root of the 20th power of 2
a1 = <value>.Approximating pi
○pi4 = √(7 + √(6 + √5)). Compute it and print it as pi4 = <value>.Explore further (not graded): compare it to
223/71 and 22/17 + 37/47 + 88/83 — which is nearest to 3.141592653589793?Student age
○name and age. Print their age now, in one year, and in ten years.Circle: circumference & area
○pi = 3.14159.Cube diagonals
○round).Text in 10 lines
○txt and print it on 10 lines below each other using a single print. Use txt only once — combine repeated concatenation (*) with the newline character '\n'.Euro anniversary
○Largest number in n bytes
○Rice on a chessboard
○n and print how many grains are on the n-th square. Note the dot right after the number, with no space (5.).Sum without spaces (f-string)
○27+342=369. Use an f-string f'...{value}...'.Triangle of stars
○n and print a triangle of *: row 1 has one star, row 2 two, …, row n has n stars.Letter triangle
○PYTHON: P / YY / TTT / …Right-aligned word triangle
○computer the last row is the full word.Star pyramid
○Hollow pyramid
○-.Digit sum
○String of star runs
○Numbers in brackets
○<number> separated by spaces.Formatted powers table
○Leibniz pi
○n and print the partial sum.Song with swapped vowels
○'Sedí mucha na stene, sedí a spí.', read a set of vowels and for each one print the line with every vowel replaced by that vowel. Use an f-string template.