Python is a dynamically typed language: a variable appears at its first assignment, and the type does not need to be declared in advance. The main built-in types are integers int, floats float, strings str, booleans bool, and the collections list and dict.
- Store a value under a clear name and reuse it later.
- Know what value and type we are working with at a given moment.
x = 7
price = 3.14
name = "Python"
print(x)Output:
7The “=” operator puts a value into the variable on its left. Each name appears exactly at its first assignment.
x = 7
print(type(x))Output:
<class 'int'>The type is determined by the value, not by the variable name. type() returns the type of the current value.
Key rules:
- ✓A variable name does not need to be declared — it appears at its first assignment.
- ✓The type is bound to the value, not to the variable name.
Common mistakes:
- !x = 7 is an int, while x = 7.0 is a float: the decimal part changes the type.
- !A repeated assignment overwrites the previous value of the variable.
Python understands all basic operations. The key is to distinguish regular division “/” (always yields a float), floor division “//” and the modulo “%”.
- Check whether a number is even via “n % 2”.
- Confidently get an integer when the fractional part is not needed.
print(7 / 2)
print(7 // 2)
print(17 % 5)Output:
3.5
3
2“/” is always a float, even 8 / 2 returns 4.0. “//” drops the fractional part down. “%” returns the remainder.
print(2 ** 3)Output:
8“**” is exponentiation: 2 ** 3 = 2·2·2 = 8.
Key rules:
- ✓“/” is always a float; “//” is the integer part (rounding down); “%” is the remainder.
- ✓"n % 2 == 0" means that n is an even number.
Common mistakes:
- !7 / 2 (float) and 7 // 2 (int) are different results, easy to confuse.
- !“%” is the remainder, not a percent: 10 % 5 returns 0, not 0.5.
The if statement runs a block of code only when the condition is true. elif and else add extra branches. The body of a branch is always separated by an indent (usually 4 spaces).
- Make decisions: run code only when a condition holds.
- Handle several cases with an if / elif / else chain.
age = 20
if age >= 18:
print("Adult")
else:
print("Child")Output:
AdultAfter “:” the body is indented. If the condition is false, the else branch runs.
for n in range(4):
if n % 2 == 0:
print(n)Output:
0
2Of the numbers 0–3 only the even ones reach the print — 0 and 2; 1 and 3 are skipped.
Key rules:
- ✓A colon is always followed by an indent, otherwise you get an IndentationError.
- ✓“==” is comparison, while “=” is assignment.
Common mistakes:
- !Writing “=” instead of “==” in a condition is a common beginner mistake.
- !Mixing tabs and spaces in indentation is forbidden.
The for loop iterates over the elements of a sequence and runs its body for each of them. range(n) produces numbers from 0 to n−1 inclusive — counting in Python starts at zero.
- Repeat an action for each element of a list or a number from a range.
- Process a sequence of values without tracking a counter by hand.
for i in range(3):
print(i)Output:
0
1
2range(3) is 0, 1, 2, not 1, 2, 3: the end of a range in Python is not included.
fruits = ["apple", "banana"]
for fruit in fruits:
print(fruit)Output:
apple
bananaKey rules:
- ✓range(n) gives numbers 0..n-1: the start is included, the end is not.
- ✓The loop repeats its body once for each element of the sequence.
Common mistakes:
- !range(3) prints 0, 1, 2, not 1, 2, 3.
- !If you forget the indent of the loop body, the code runs once outside the loop.
A list is a mutable ordered collection. Element numbering starts at 0, and the append() method adds a new element to the end of the list.
- Store several values of the same meaning in one variable.
- Gradually accumulate elements while the program runs.
nums = [1, 2]
nums.append(3)
print(nums)Output:
[1, 2, 3]append() changes the list itself, adding the value to the end. The list prints in square brackets.
letters = ["a", "b", "c"]
print(letters[0])Output:
aThe first element is at index 0, so letters[0] is "a", not "b".
Key rules:
- ✓The first element of a list has index 0.
- ✓append() puts the value exactly at the end of the list.
Common mistakes:
- !Accessing a nonexistent index causes an IndexError.
- !A list and a string are easy to confuse: they are different types, each with its own methods.
An f-string substitutes values from curly braces right into the text. The input() function always returns a string. A dictionary dict stores key → value pairs and is convenient for data with named fields.
- Assemble readable text, substituting variable values.
- Get data from the user and work with data by keys.
name = "Python"
print(f"I am learning {name}")Output:
I am learning PythonInside the curly braces of an f-string the value of the expression is substituted — here the variable name.
age = input("How old? ")
print(type(age))Output:
<class 'str'>Even if the user types 25, the age variable stays a string. For numbers you need int(age).
person = {"name": "Anna", "age": 20}
print(person["name"])Output:
AnnaA dictionary is accessed by key: d["name"]. Unlike a list, there is no order or indexes here.
Key rules:
- ✓f-strings substitute values through curly braces.
- ✓input() always returns a string (str).
- ✓A dictionary is accessed by key, not by index.
Common mistakes:
- !Forgot int() around input() — you get an error doing arithmetic on a string.
- !An f-string without the “f” prefix leaves the text {name} as is, without substitution.
The boolean type bool takes two values: True and False. It is returned by comparisons “==”, “!=”, “<”, “>”, while the operators and, or and not let you chain conditions.
- Check conditions in if and while.
- Combine several conditions: and (both), or (at least one), not (negation).
age = 20
print(age >= 18)
print(age == 21)Output:
True
FalseComparisons always return True or False. “==” checks equality, while “=” assigns a value.
age = 20
has_card = True
print(age >= 18 and has_card)
print(not has_card)Output:
True
Falseand is true only when both conditions are True; not turns True into False and vice versa.
Key rules:
- ✓Comparisons (==, !=, <, >) return bool: True or False.
- ✓and — both conditions, or — at least one, not — negation.
Common mistakes:
- !Writing “=” instead of “==” in a condition is a common beginner mistake.
- !The operators && and || do not work in Python — only the words and and or.
The while loop repeats its body while the condition is true, and is useful when the number of steps is not known in advance. The keywords break and continue control the course of any loop: break exits it, continue moves to the next iteration.
- Repeat an action until a condition holds (for example, until the user enters a valid value).
- Stop a loop on an event inside the body via break.
n = 0
while n < 3:
print(n)
n = n + 1Output:
0
1
2The variable n must change inside the loop — otherwise the condition never becomes false and the loop becomes infinite.
for i in range(5):
if i == 2:
continue
if i == 4:
break
print(i)Output:
0
1
3continue skips the number 2, break stops the loop at 4 — so 4 does not reach the print.
Key rules:
- ✓while runs while the condition is true; the counter must change inside the body.
- ✓break exits the loop early, continue moves to the next iteration.
Common mistakes:
- !Forgot to change the counter → an infinite loop.
- !break and continue act only on the nearest loop.
The functions int(), float() and str() bring a value to the needed type. This is mandatory when working with input(): user input is always a string, and you cannot add it as a number.
- Turn user input from a string into a number before arithmetic.
- Convert values to the needed type when an operation requires a specific kind.
age = input("How old? ")
age = int(age)
print(age + 1)Output:
26After int("25") the variable becomes the number 25, and only then can you add to it. Without int() you get a TypeError.
print(int(3.9))
print(float(7))Output:
3
7.0int() drops the fractional part (it does not round!), while float() adds a decimal point.
Key rules:
- ✓int("25") → 25, float("2.5") → 2.5, str(7) → "7".
- ✓input() always returns a string — convert it before arithmetic.
Common mistakes:
- !int("abc") ends with a ValueError: text cannot be turned into a number.
- !int(3.9) gives 3, not 4 — the fractional part is just dropped.
Strings have many ready-made methods: .upper() and .lower() change the case, .strip() removes spaces on the edges, .split() divides a string into a list. The slice s[start:end] cuts out a part of a string, and negative indexes count from the end.
- Clean and normalize user input (for example, remove extra spaces).
- Extract a needed fragment from a string or split it into parts.
name = " python "
print(name.strip().upper())
print(len(name.strip()))Output:
PYTHON
6strip() removes edge spaces, upper() converts to uppercase. Methods can be called in a chain.
s = "Python"
print(s[0:3])
print(s[-1])Output:
Pyt
ns[0:3] takes characters with indexes 0, 1, 2 (the end is not included), and s[-1] is the last character.
Key rules:
- ✓.upper()/.lower() change the case, .strip() removes spaces, .split() divides a string into a list.
- ✓The slice s[2:5] — characters from 2 to 4 inclusive; s[-1] — the last character.
Common mistakes:
- !Strings are immutable: s.upper() does not change s, it returns a new string — the result must be saved.
- !In a slice the end is not included: s[0:3] does not contain the character at index 3.
A function is created with the keyword def and runs only when called. Parameters pass input data, and return sends the result out.
- Extract repeated actions into a reusable block of code.
- Compute a result from parameters and return it via return.
def greet(name):
return f"Hello, {name}!"
print(greet("Anna"))Output:
Hello, Anna!The parameter name gets its value at the call. return returns the string that print outputs.
def add(a, b):
return a + b
result = add(3, 5)
print(result)Output:
8add(3, 5) substitutes a=3 and b=5 and returns 8. If you forget return, the function returns None.
Key rules:
- ✓A function runs only when called, not when defined.
- ✓return passes the result out; without it the function returns None.
Common mistakes:
- !Forgot return — the function returns None, and print(result) prints None.
- !Variables inside a function are not visible outside (local scope).
When code breaks, Python throws an exception and stops the program: ValueError, TypeError, IndexError and others. The try/except construct catches the exception and runs fallback code.
- Stop the program from crashing because of invalid input.
- Catch expected errors and print clear messages.
try:
n = int("abc")
except ValueError:
print("That is not a number!")Output:
That is not a number!int("abc") throws a ValueError; the except block catches it and runs its branch instead of crashing.
nums = [1, 2, 3]
print(nums[5])Output:
IndexError: list index out of rangeAccessing a nonexistent list index causes an IndexError. TypeError — an operation on incompatible types.
Key rules:
- ✓try/except catches an exception and stops the program from crashing.
- ✓NameError — the name is undefined, ValueError — a wrong value, TypeError — incompatible types, IndexError — no index.
Common mistakes:
- !A bare except catches all errors at once — better to specify a concrete type so bugs are not hidden.
- !except does not fix the cause: the code in try must stay correct.