Python Basics: Syntax, Data Types, and Best Coding Practices
Understanding Python syntax and data types is an absolute foundation. Learn how to write clean, Pythonic code, how type hints work, and how to optimally use built-in collections.

- Python structures code using indentation, which eliminates the need for curly braces and enforces readability.
- Dynamic typing can be complemented with optional Type Hints, which significantly facilitates working in larger teams and systems.
- Built-in collections (list, tuple, dict, set) offer different mutability and uniqueness characteristics that should be matched to the problem.
- List comprehension allows for concise and highly efficient generation of new lists in a single line of code.
The first step in learning any programming language is mastering its fundamentals: syntax and data representation. Python is famous for its simplicity and clarity—it is often said to read like plain English. However, behind this approachable facade lies a consistent and powerful type system and a set of rules that allow you to write concise yet readable code.
In this article, we will go through the key elements of Python syntax. You will see how data types work, how to use operators effectively, and how to write elegant code in the spirit of the language. If you are just starting your journey with Python, this guide will give you a solid starting point.
The Importance of Indentation in Python Syntax
Python stands out from other languages with its unique approach to code structuring. It does not use curly braces `{}` to define blocks of statements. Instead, it relies on indentation. In Python, indentation is not just a matter of aesthetics—it is a syntax requirement. An incorrect number of spaces directly translates to compilation or runtime errors.
# Correct code
for i in range(3):
print("Cześć!")
# Error: missing indentation (IndentationError)
for i in range(3):
print("Cześć!")Thanks to this approach, Python forces developers to write structured code that looks consistent regardless of who created it.
Variables and Dynamic Typing
Python is a dynamically typed language. This means you do not need to declare a variable's type before using it. The interpreter automatically recognizes the type on the fly based on the assigned value.
x = 10 # integer (int)
y = 3.14 # floating-point number (float)
z = "Hello" # string (str)
flag = True # boolean value (bool)The flexibility of dynamic typing also allows you to easily change the type stored by a variable at any point during program execution:
x = 10
x = "dziesięć" # now x stores a string (str)Type Hints – Optional Static Typing
Although Python does not require declaring types, the modern standard of the language allows the use of so-called type hints. This is extremely helpful in larger projects because it facilitates code analysis for development tools (such as mypy, Pyright, or VS Code) and improves code readability for other developers.
def greet(name: str) -> str:
return f"Witaj, {name}!"
user_name: str = "Adam"
print(greet(user_name))In the example above, we used clear annotations:
- name: str indicates that the argument passed to the function should be a string,
- -> str informs that the result of the function will also be a string.
Remember that type hints do not affect real-time code performance, nor do they block the program from running in case of type mismatches. They are used solely for static code analysis.
Numeric Types: int and float
In Python, mathematical operations are mainly performed on two numeric types: integers (`int`) and floating-point numbers (`float`).
a = 5
b = 2.5
print(a + b) # Result: 7.5 (automatic conversion to float)Operators in Python
Arithmetic Operators
| Operator | Description | Example | Result |
|---|---|---|---|
| + | addition | 5 + 3 | 8 |
| - | subtraction | 5 - 3 | 2 |
| * | multiplication | 5 * 3 | 15 |
| / | division (always returns float) | 5 / 2 | 2.5 |
| // | floor division | 5 // 2 | 2 |
| % | modulo (remainder of division) | 5 % 2 | 1 |
| ** | exponentiation | 2 ** 3 | 8 |
Comparison Operators
| Operator | Description | Example | Result |
|---|---|---|---|
| == | equality | 5 == 5 | True |
| != | inequality | 5 != 3 | True |
| > | greater than | 5 > 3 | True |
| < | less than | 5 < 3 | False |
| >= | greater than or equal to | 5 >= 5 | True |
| <= | less than or equal to | 4 <= 3 | False |
Logical Operators
Unlike languages such as C++ or Java, Python emphasizes verbal readability. Instead of symbols like `&&`, `||`, or `!`, direct English equivalents are used.
| Operator | Description | Example | Result |
|---|---|---|---|
| and | logical AND (conjunction) | True and False | False |
| or | logical OR (disjunction) | True or False | True |
| not | logical NOT (negation) | not True | False |
Assignment Operators
| Operator | Description | Example | Equivalent |
|---|---|---|---|
| = | assign value | x = 5 | x = 5 |
| += | add and assign | x += 5 | x = x + 5 |
| -= | subtract and assign | x -= 5 | x = x - 5 |
| *= | multiply and assign | x *= 5 | x = x * 5 |
| /= | divide and assign | x /= 5 | x = x / 5 |
| //= | floor divide and assign | x //= 2 | x = x // 2 |
Identity and Membership Operators
| Operator | Description | Example | Result |
|---|---|---|---|
| is | checks if objects point to the same memory location | x is y | True/False |
| is not | checks if objects are not identical | x is not y | True/False |
| in | checks presence of an element in a collection | "py" in "python" | True |
| not in | checks absence of an element in a collection | "java" not in "python" | True |
Working with Strings (str)
Strings in Python can be defined using single (`'`) or double (`"`) quotes. Triple quotes (`"""` or `'''`) are used to create multi-line strings.
text = "Python jest super!"
print(text.upper()) # PYTHON JEST SUPER!
print(text.lower()) # python jest super!
print(text[0]) # P (zero-based indexing)
print(text[-1]) # ! (negative indexing from the end)For dynamically combining text with variables, highly convenient f-strings (formatted string literals) are used:
name = "ByteWay"
print(f"Witaj, {name}!") # Hello, ByteWay!Built-in Data Collections
Python has four basic, extremely flexible data structures that differ in their properties:
| Structure | Example Syntax | Mutable | Ordered | Element Uniqueness |
|---|---|---|---|---|
| list | [1, 2, 3] | Yes | Yes | Any |
| tuple | (1, 2, 3) | No | Yes | Any |
| dict (dictionary) | {"a": 1} | Yes | Yes (since Python 3.7) | Keys must be unique |
| set | {1, 2, 3} | Yes | No | Unique values only |
Examples of Collection Usage in Code
List (list) – a dynamic array for storing elements:
numbers = [1, 2, 3, 4]
numbers.append(5)
print(numbers) # [1, 2, 3, 4, 5]Tuple (tuple) – an immutable list, often used to pass constant data structures:
coords = (10, 20)
print(coords[0]) # 10Dictionary (dict) – an associative structure storing key-value pairs:
user = {"name": "Adam", "role": "admin"}
print(user["name"]) # AdamSet (set) – a collection storing only unique values, automatically eliminating duplicates:
tags = {"python", "ai", "data", "python"}
print(tags) # {'python', 'ai', 'data'}Control Flow: Loops and Conditionals
The for Loop
Used to iterate over elements of any collection or sequence generated, for example, by the `range()` function:
for item in ["AI", "Cloud", "Python"]:
print(item)The while Loop
Executes a block of code as long as a specific logical condition is met:
count = 0
while count < 3:
print(count)
count += 1The if Conditional Statement
Allows for conditional branching of program execution paths:
x = 10
if x > 5:
print("Większe niż 5")
elif x == 5:
print("Równe 5")
else:
print("Mniejsze niż 5")List Comprehension – Concise List Creation
One of the most characteristic and beloved constructs in Python is list comprehension. It allows for quick generation and filtering of lists in a readable way, without the need to write full `for` loops.
# Traditional squaring of numbers in a single line
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]We can also use filtering conditions inside a list comprehension:
# Selecting only even numbers
even = [x for x in range(10) if x % 2 == 0]
print(even) # [0, 2, 4, 6, 8]This is an excellent tool that makes the code more declarative and compact.
Summary
Python was designed with an emphasis on code readability and developer productivity. The lack of strict type declaration requirements, support for optional type hints, and a set of built-in, powerful data structures make this language perfect for both simple automation scripts and building advanced artificial intelligence systems or web applications. Mastering these basics is the key to smoothly navigating the Python ecosystem.
Ready to get started?
Got something I could help with? Get in touch — happy to share what I know.
Get in touch