Python Academy · English Edition
PricingSign in
Lesson W01

Introduction to Python

Winter semester · Chapter 1

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.

Unlike many other languages that are compiled (e.g. Pascal, C/C++, C#), Python is an interpreter. This means:

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):

shell.pyPython 3

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:

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)

+addition1 + 23
-subtraction2 - 5-3
*multiplication3 * 37111
//integer division22 // 73
%remainder (modulo)22 % 71
**exponentiation2 ** 8256

String operations

+concatenation (joining two strings)'a' + 'b''ab'
*repeated concatenation3 * 'x''xxx'

Repeated concatenation is unusual but handy — 10 * ' :-) ' repeats the smiley ten times. Experiment:

types.pyPython 3

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
Variable names
  • may contain letters, digits and the underscore _
  • are case-sensitive (ageAge)
  • 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×!)
Type conversion

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:

euro.pyPython 3

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.

Accumulator pattern

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:

loop.pyPython 3

Exercises

0 / 23 solved · auto-graded, runs in your browser

#1aeasy

Roots & powers

Using ** with a fractional exponent computes roots (e.g. x ** 0.5 is √x). Assign and print:
  • a1 = the square root of 3
  • a2 = one third of the cube root of 5
  • a3 = the 5th power of the 5th root of 1024
  • a4 = the 10th root of the 20th power of 2
Print each as a1 = <value>.
solution.pyPython 3
1 hidden test · numeric · loading engine…
#1bmedium

Approximating pi

Mathematicians approximated pi with clever formulas. One of the closest is 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?
solution.pyPython 3
1 hidden test · numeric · loading engine…
#2easy

Student age

Read a student's name and age. Print their age now, in one year, and in ten years.
solution.pyPython 3
2 hidden tests · loading engine…
#3aeasy

Circle: circumference & area

Read the radius of a circle and print its circumference and area. Assume pi = 3.14159.
solution.pyPython 3
2 hidden tests · numeric · loading engine…
#3beasy

Cube diagonals

Read the side of a cube and print its face diagonal and space diagonal, each rounded to 2 decimals (use round).
solution.pyPython 3
2 hidden tests · numeric · loading engine…
#4easy

Text in 10 lines

Read some text into 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'.
solution.pyPython 3
2 hidden tests · loading engine…
#5medium

Euro anniversary

The euro was introduced in Slovakia on 1 Jan 2009. Assuming 16 years, 8 months and 22 days have passed (each year = 365 days, each month = 30 days), compute the number of days, hours and seconds.
solution.pyPython 3
1 hidden test · loading engine…
#6medium

Largest number in n bytes

One byte (8 bits) stores 0–255. Two bytes store up to 256·256−1, etc. Read a number of bytes and print the largest value that fits.
solution.pyPython 3
2 hidden tests · loading engine…
#7medium

Rice on a chessboard

On square 1 there is 1 grain of rice, on each next square twice the previous. Read n and print how many grains are on the n-th square. Note the dot right after the number, with no space (5.).
solution.pyPython 3
3 hidden tests · loading engine…
#8easy

Sum without spaces (f-string)

Read two integers and print them as an equation without spaces, e.g. 27+342=369. Use an f-string f'...{value}...'.
solution.pyPython 3
2 hidden tests · loading engine…
#9medium

Triangle of stars

Read n and print a triangle of *: row 1 has one star, row 2 two, …, row n has n stars.
solution.pyPython 3
3 hidden tests · loading engine…
#10amedium

Letter triangle

Read a word and print a triangle: row 1 = first letter once, row 2 = second letter twice, …, last row = last letter repeated as many times as the word is long. (No indexing — use a counter.) For PYTHON: P / YY / TTT / …
solution.pyPython 3
2 hidden tests · loading engine…
#10bhard

Right-aligned word triangle

Improved variant: row i shows the first i letters of the word, right-aligned so all rows share the same right edge. For computer the last row is the full word.
solution.pyPython 3
2 hidden tests · loading engine…
#11amedium

Star pyramid

Print a pyramid: row 1 has n−1 spaces then 1 star; each next row has one space fewer and two stars more.
solution.pyPython 3
2 hidden tests · loading engine…
#11bhard

Hollow pyramid

Improved variant: only the outline is stars, the inside is filled with minus signs -.
solution.pyPython 3
1 hidden test · loading engine…
#12medium

Digit sum

Read an integer, split it into its digits (convert to a string, then each character back to a number), print each digit with its position, and print the digit sum.
solution.pyPython 3
2 hidden tests · loading engine…
#13medium

String of star runs

Build one long string of star runs separated by spaces: 1 star, space, 2 stars, space, 3 stars… for n runs, then print it once.
solution.pyPython 3
2 hidden tests · loading engine…
#14medium

Numbers in brackets

Like the previous task, but instead of star runs write the numbers of an interval in the form <number> separated by spaces.
solution.pyPython 3
1 hidden test · loading engine…
#15hard

Formatted powers table

Print a formatted table of powers for an interval: column 1 the number, then its 2nd, 3rd and 4th powers, all right-aligned in fixed-width columns.
solution.pyPython 3
1 hidden test · loading engine…
#16hard

Leibniz pi

The Leibniz series approximates pi: 4 − 4/3 + 4/5 − 4/7 + 4/9 − … Read the number of terms n and print the partial sum.
solution.pyPython 3
2 hidden tests · numeric · loading engine…
#17hard

Song with swapped vowels

For the line '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.
solution.pyPython 3
1 hidden test · loading engine…
#18hard

Multiplication table

Print a multiplication table for an interval, with a header row and column of the numbers and separator lines, as shown.
solution.pyPython 3
1 hidden test · loading engine…
#19hard

Three tables side by side

This fills an n×n table with the numbers 1..n². Modify it so the same table is printed three times next to each other.
solution.pyPython 3
1 hidden test · loading engine…
← All lessonsSubprograms