- Tell apart a program, a programming language, machine language and low- and high-level languages, and compare an interpreter with a compiler.
- Create variables, recognise the types
int,float,strandbool, and read data withinput(),int(input())andinput().split(). - Evaluate
+ - * / // % **in the right order and useabs(),int()andstr(). - Work out what a short program prints by tracing it step by step (the closed and coded tasks of the exam).
A computer understands only commands made of 0s and 1s, yet you type print(7 * 6) and it instantly answers 42. Who translates between these two languages? In this lesson you will find out, and you will learn Python’s first essential tools: variables, reading from the keyboard, printing to the screen and arithmetic. In the informatics part of Azerbaijan’s university entrance exam (DİM, group I), 9 of the 30 tasks are Python programs — and all of them are built from the bricks of this lesson.
Programs, programming languages and translators
A sequence of commands (instructions) for the computer, written in a programming language. A program is an algorithm written down for a computer.
Programming is the process of creating a program: stating the problem, designing the algorithm, writing it in a programming language and testing it. A programming language is a formal language with strict rules (syntax) for writing programs: Python, C++, Java, Pascal, BASIC.
Languages are divided into levels by how close they are to the machine. Machine language is the only language the processor executes directly: commands are binary codes and depend on the type of processor. Low-level languages (for example, assembly language) write machine commands with short letter codes such as MOV and ADD; they are also tied to a particular processor. High-level languages (Python, C++, Java, Pascal) are close to human language and mathematical notation, do not depend on the processor, and one of their commands turns into many machine commands.
A program that converts the text of a program written in a high-level language (the source code) into machine language. There are two kinds: the compiler and the interpreter.
| Feature | Compiler | Interpreter |
|---|---|---|
| How it translates | the whole program at once, before running | one command at a time: translates it and runs it at once |
| What it produces | an executable file (e.g. .exe) that later runs without the translator | no separate file; the interpreter is needed on every run |
| Speed | the finished program runs fast | usually runs more slowly |
| Errors | reported for the whole text before running | stops when it reaches the faulty command; earlier commands have already run |
| Examples | C, C++, Pascal, Go | Python, JavaScript, PHP |
Python is an interpreted language. If the program fails at its 5th command while running (for example, division by zero), the output of the first four commands is already on the screen. Strictly speaking, Python first turns the whole text into intermediate bytecode — that is why a program with a typing (syntax) error does not start at all — but at school and in the exam Python is classed as an interpreted language.
Constants, variables and assignment
A constant is a value that does not change while the program runs: 45, 3.14, 'Baku'. A variable is a named place in memory whose value can change as the program runs. In Python a variable is created the first time a value is assigned to it.
The assignment operator = works like this: first the expression on the right is calculated, then the result is stored in the variable on the left, and the old value is lost. That is why x = x + 1 is not an equation but the command “increase x by 1”. Official exam explanations describe it as “the value … is assigned to the variable”. Python also allows several assignments in one line: a, b = 3, 8.
- a name starts with a letter or
_, followed by letters, digits and_:a1,sum_2,_kare valid, while2a,my-sumanda bare not; - upper and lower case differ:
aandAare two different variables; - keywords (
if,else,for,while,and,or,not,True) cannot be variable names.
| Type | What it stores | Examples |
|---|---|---|
int | a whole number | 45, -7, 0 |
float | a real number (decimal fraction) | 3.5, 2.0, -0.25 |
str | a string: text in quotes | 'Baku', "45", '' |
bool | a logical value | True, False |
45 and '45' are different: the first is a number, the second is text. Python always writes real numbers with a point: 3.5.a = 7
b = 2.5
s = '7'
t = a > 5
print(type(a), type(b), type(s), type(t))
print(a * 2, b * 2, s * 2, t)▸ Expected output
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> 14 5.0 77 True
type() shows the type of a value. Note: s * 2 repeats the string (77), while b * 2 stays a float (5.0).In Python the type of a variable is set by the value assigned to it and can change while the program runs: after x = 5, x is a whole number; after x = 'five' it is a string. So in every task ask yourself: does the variable hold a number or text at this moment? The same + sign adds numbers but glues strings together.
Let a = 7 and b = 3. Then the commands a = a + b, b = a - b, a = a - b are executed in this order. What does print(a, b) print?
Show solutionHide solution
a = a + b → a = 7 + 3 = 10, b = 3b = a - b → b = 10 − 3 = 7, a = 10a = a - b → a = 10 − 7 = 3, b = 7Output: 3 7. The variables have swapped their values without a third variable. In Python the same job takes one line:
a, b = b, a.Input and output: input() and print()
The print() function shows the values in its brackets on the screen. Several values separated by commas are printed on one line with one space between them, and every new print() starts a new line. The sep parameter changes the separator and end changes the line ending: print(1, 2, 3, sep='-') → 1-2-3, while print('a', end='') keeps the next output on the same line.
input() reads the line the user types on the keyboard and **always returns it as a string (str)**: even if you type 5, you get '5'. To calculate with it, convert the string: int(input()) for a whole number, float(input()) for a real number. That is exactly how the exam programs begin: n = int(input()). Several values typed on one line with spaces are read with input().split() — it cuts the line at the spaces and returns a list of strings; we convert each part with int().
name = input()
age = int(input())
a, b = input().split()
a = int(a)
b = int(b)
print(name, age, a + b)
print(name, 'is', age, sep='_')| Input (keyboard) | Output (screen) |
|---|---|
Leyla143 8 | Leyla 14 11Leyla_is_14 |
Read the task statement carefully: if the numbers are typed each on its own line, repeat int(input()) as many times as needed (a = int(input()), b = int(input())); if they are typed on one line, separated by spaces, use input().split(). Both forms appear in the written exam tasks: for example, the elements of a list may come as one line separated by single spaces, while their count n comes on a line of its own.
name = 'Leyla'
age = int('14')
line = '3 8'
a, b = line.split()
a = int(a)
b = int(b)
print(name, age, a + b)
print(name, 'is', age, sep='_')▸ Expected output
Leyla 14 11 Leyla_is_14
line.split() splits the string into the list ['3', '8']. Change the values and run it again.While the program runs, 12 5 is typed on one line:a, b = input().split()print(a + b, int(a) + int(b), a * 2)
What is printed?
Show solutionHide solution
split() cuts the line into the list ['12', '5']: a = '12', b = '5' — both are strings.a + b joins the strings: 125.int(a) + int(b) = 12 + 5 = 17.a * 2 repeats the string twice: 1212.Answer: 125 17 1212.
Arithmetic: //, % and the order of operations
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | addition, subtraction, multiplication | 17 + 5, 17 - 5, 17 * 5 | 22, 12, 85 |
/ | division; the result is always a float | 17 / 5, 8 / 2 | 3.4, 4.0 |
// | floor division — the whole quotient | 17 // 5 | 3 |
% | remainder of the division | 17 % 5 | 2 |
** | exponentiation (power) | 2 ** 5 | 32 |
- athe dividend (a whole number)
- bthe divisor, b > 0
- a // bthe whole quotient
- a % bthe remainder
Division with remainder: // and % always work as a pair. Check: quotient times divisor plus remainder must give back the dividend.
Calculate: 1) 47 // 6 and 47 % 6; 2) 5 // 8 and 5 % 8; 3) -17 // 5 and -17 % 5.
Show solutionHide solution
47 // 6 = 7 and 47 % 6 = 47 − 42 = 5. Check: 6 · 7 + 5 = 47.2) The dividend is smaller than the divisor:
5 // 8 = 0, 5 % 8 = 5 (the number itself is left over).3) In Python
// always rounds down, towards the smaller number: −17 / 5 = −3.4 → -17 // 5 = −4. Remainder: −17 − 5 · (−4) = 3, so again 0 ≤ 3 < 5.Operator priority (decreasing from left to right). Operators of one level, * / // %, are done from left to right, but ** goes from right to left: 2 ** 3 ** 2 = 2 ** 9 = 512. ** is stronger than a leading minus: -2 ** 2 = −4.
a = 7
b = 45
c = b // a % 4 * 3 + b % a ** 2
print(c)▸ Expected output
51
a = int(input()) and 7 is typed on the keyboard.If 7 is typed on the keyboard, what does the program above print?
A) 15 B) 51 C) 45 D) 6 E) 57
Show solutionHide solution
+ is done last.Left part, from left to right:
b // a = 45 // 7 = 6 → 6 % 4 = 2 → 2 * 3 = 6.In the right part
** is stronger: a ** 2 = 49, then 45 % 49 = 45 (45 < 49, the number itself is left).c = 6 + 45 = 51, answer B.
Trap: whoever reads
b % a ** 2 as (b % a)² gets 3² = 9 and wrongly picks 15 (A).Digits of a number and type conversions
- na three-digit natural number
- athe hundreds digit
- bthe tens digit
- cthe units (last) digit
n % 10 always gives the last digit and n // 10 the number without its last digit. The digits of numbers of any length are handled with loops in the lesson “Working with numbers: digits, divisors and primes”.
n = 739
a = n // 100
b = n // 10 % 10
c = n % 10
print(c * 100 + b * 10 + a, a + b + c, abs(a - c))▸ Expected output
937 19 2
n = int(input()).If 739 is typed on the keyboard, what does the program above print?
Show solutionHide solution
First value: 9 · 100 + 3 · 10 + 7 = 937 — the number written backwards.
Second: 7 + 3 + 9 = 19 — the digit sum.
Third:
abs(7 - 9) = |−2| = 2.print separates the three values with spaces: 937 19 2.Type conversions. str() turns a number into a string, and int() turns a string or a real number into a whole number: str(45) + '1' → 451, int('45') + 1 → 46, int(7.9) → 7 (the fraction is simply cut off, not rounded). len(str(n)) gives the number of digits: len(str(2026)) → 4. abs(x) returns the absolute value: abs(-12) → 12.
- 1.17 // 5 →
- 2.17 % 5 →
- 3.2 ** 3 ** 2 →
- 4.-7 // 2 →
- 5.int('12') + 3 →
- 6.len(str(40961)) →
Exam tasks: what does the program print?
In the exam a program is usually 5–15 lines long and the question is always the same: “determine the result of the program”. A closed task has 5 answer options; in a coded task you write the answer yourself. In both cases the winning method is the same — “run” the program line by line, like a computer.
- 1Open a table of variables
Draw a column for each variable and write the starting values. If there is
input(), write the given input with the right type:int(input())→ a number,input()→ a string. - 2Go line by line
After each assignment update only that variable’s column and cross out the old value. The right-hand side is always computed with the old values.
- 3Follow the priority
In a long expression do
**first, then* / // %from left to right, then+ -. Write down the intermediate results. - 4Watch the types
/always gives afloat(8 / 2→4.0); for strings+joins and*repeats. - 5Check the output format
print(a, b)separates values with one space, and eachprintis on a new line. The answer options often differ exactly in spaces and lines.
A film lasts t seconds. Print how many whole hours, minutes and seconds that is, on one line separated by spaces. Test the program with t = 7384 (the exam version would use t = int(input())).
t = 7384
# hours, minutes, seconds▸ Expected output
2 3 4
One line holds two natural numbers separated by a space: line = '38 7'. Split them with split(), convert with int() and print on one line the quotient, the remainder and the check value (divisor · quotient + remainder).
line = '38 7'
# split, convert, print quotient, remainder, check▸ Expected output
5 3 38
Key points
- A translator turns a high-level program into machine language: a compiler translates the whole program in advance into an executable file, an interpreter translates and runs the commands one by one. Python is interpreted.
=is assignment: the right side is computed first, then the result is stored in the variable on the left.input()always returns a string: useint(input())for a number andinput().split()for several values on one line.//gives the whole quotient and%the remainder: a = b · (a // b) + a % b;n % 10is the last digit,n // 10the number without it.- Priority: brackets →
**(right to left) →* / // %(left to right) →+ -;/always gives afloat.
Check yourself
12 questions. Every correct answer earns XP.