Skip to content
Educora
IntermediateGrade 822 min29 / 59

Programming languages and Python: variables, input and output

What a program and a programming language are and how translators (interpreters and compilers) work; Python variables, input with `int(input())`, output with `print()` and the `//` and `%` operators — with exam-style “what does the program print?” tasks.

Check yourself
In this lesson you will learn
  • 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, str and bool, and read data with input(), int(input()) and input().split().
  • Evaluate + - * / // % ** in the right order and use abs(), int() and str().
  • 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

Definition
Program

A sequence of commands (instructions) for the computer, written in a programming language. A program is an algorithm written down for a computer.

Definition
Programming and programming language

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.

Definition
Translator

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.

CompilerInterpreterSource codeSource codetranslates thewhole programin advanceexecutable file(.exe)one commandat a time:translate → run →next commandResultResult
A compiler translates once and produces a ready file; an interpreter translates and carries out the commands one by one every time the program runs.
FeatureCompilerInterpreter
How it translatesthe whole program at once, before runningone command at a time: translates it and runs it at once
What it producesan executable file (e.g. .exe) that later runs without the translatorno separate file; the interpreter is needed on every run
Speedthe finished program runs fastusually runs more slowly
Errorsreported for the whole text before runningstops when it reaches the faulty command; earlier commands have already run
ExamplesC, C++, Pascal, GoPython, 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

Definition
Constants and variables

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, _k are valid, while 2a, my-sum and a b are not;
  • upper and lower case differ: a and A are two different variables;
  • keywords (if, else, for, while, and, or, not, True) cannot be variable names.
TypeWhat it storesExamples
inta whole number45, -7, 0
floata real number (decimal fraction)3.5, 2.0, -0.25
stra string: text in quotes'Baku', "45", ''
boola logical valueTrue, 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.
Python
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.

Example 1. Tracing assignments

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 solution
After every command we write down both variables:
a = a + b → a = 7 + 3 = 10, b = 3
b = a - b → b = 10 − 3 = 7, a = 10
a = a - b → a = 10 − 7 = 3, b = 7
Output: 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().

Python
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='_')
Exam version: the program reads three lines from the keyboard. The table below shows the input and the output.
Input (keyboard)Output (screen)
Leyla
14
3 8
Leyla 14 11
Leyla_is_14
The written exam tasks give their examples in exactly this kind of “Input / Output” table.

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.

Python
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
The version that runs in the browser: the lines that would come from the keyboard are written straight into variables. line.split() splits the string into the list ['3', '8']. Change the values and run it again.
Example 2. Two values on one line

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

OperatorMeaningExampleResult
+ - *addition, subtraction, multiplication17 + 5, 17 - 5, 17 * 522, 12, 85
/division; the result is always a float17 / 5, 8 / 23.4, 4.0
//floor division — the whole quotient17 // 53
%remainder of the division17 % 52
**exponentiation (power)2 ** 532
a = b · (a // b) + a % b, 0 ≤ a % b < b
where:
  • 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.

Example 3. Quotient and remainder

Calculate: 1) 47 // 6 and 47 % 6; 2) 5 // 8 and 5 % 8; 3) -17 // 5 and -17 % 5.

Show solution
1) 6 · 7 = 42 ≤ 47 < 48 = 6 · 8, so 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.
( ) → ** → * / // % → + −2 ** 3 ** 2 = 2 ** 9 = 512

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.

Python
a = 7
b = 45
c = b // a % 4 * 3 + b % a ** 2
print(c)
▸ Expected output
51
The program of Example 4. In the exam the first line is a = int(input()) and 7 is typed on the keyboard.
Example 4. An exam-style multiple-choice task

If 7 is typed on the keyboard, what does the program above print?
A) 15 B) 51 C) 45 D) 6 E) 57

Show solution
Split the expression into two parts; + 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

n = 100·a + 10·b + c ⇒ a = n // 100, b = n // 10 % 10, c = n % 10
where:
  • 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”.

Python
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
The program of Example 5. In the exam version the first line is n = int(input()).
Example 5. Working with digits (coded answer)

If 739 is typed on the keyboard, what does the program above print?

Show solution
a = 739 // 100 = 7 (hundreds), b = 739 // 10 % 10 = 73 % 10 = 3 (tens), c = 739 % 10 = 9 (units).
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.

Quick drill: what does Python return?
  1. 1.17 // 5 →
  2. 2.17 % 5 →
  3. 3.2 ** 3 ** 2 →
  4. 4.-7 // 2 →
  5. 5.int('12') + 3 →
  6. 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.

  1. 1
    Open 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.

  2. 2
    Go 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.

  3. 3
    Follow the priority

    In a long expression do ** first, then * / // % from left to right, then + -. Write down the intermediate results.

  4. 4
    Watch the types

    / always gives a float (8 / 2 → 4.0); for strings + joins and * repeats.

  5. 5
    Check the output format

    print(a, b) separates values with one space, and each print is on a new line. The answer options often differ exactly in spaces and lines.

Exercise

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())).

Exercise · Python
t = 7384
# hours, minutes, seconds
▸ Expected output
2 3 4
Exercise

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

Exercise · Python
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: use int(input()) for a number and input().split() for several values on one line.
  • // gives the whole quotient and % the remainder: a = b · (a // b) + a % b; n % 10 is the last digit, n // 10 the number without it.
  • Priority: brackets → ** (right to left) → * / // % (left to right) → + -; / always gives a float.

Check yourself

12 questions. Every correct answer earns XP.

1 / 12
What is the translator called that converts the whole program into machine language before it runs and creates an executable file?