Python5 min readNov 10, 2025

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.

Udostępnij:
Python Basics: Syntax, Data Types, and Best Coding Practices
TL;DR - Executive Summary
  • 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.

python
# 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.

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

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

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

python
a = 5
b = 2.5
print(a + b)  # Result: 7.5 (automatic conversion to float)

Operators in Python

Arithmetic Operators

OperatorDescriptionExampleResult
+addition5 + 38
-subtraction5 - 32
*multiplication5 * 315
/division (always returns float)5 / 22.5
//floor division5 // 22
%modulo (remainder of division)5 % 21
**exponentiation2 ** 38

Comparison Operators

OperatorDescriptionExampleResult
==equality5 == 5True
!=inequality5 != 3True
>greater than5 > 3True
<less than5 < 3False
>=greater than or equal to5 >= 5True
<=less than or equal to4 <= 3False

Logical Operators

Unlike languages such as C++ or Java, Python emphasizes verbal readability. Instead of symbols like `&&`, `||`, or `!`, direct English equivalents are used.

OperatorDescriptionExampleResult
andlogical AND (conjunction)True and FalseFalse
orlogical OR (disjunction)True or FalseTrue
notlogical NOT (negation)not TrueFalse

Assignment Operators

OperatorDescriptionExampleEquivalent
=assign valuex = 5x = 5
+=add and assignx += 5x = x + 5
-=subtract and assignx -= 5x = x - 5
*=multiply and assignx *= 5x = x * 5
/=divide and assignx /= 5x = x / 5
//=floor divide and assignx //= 2x = x // 2

Identity and Membership Operators

OperatorDescriptionExampleResult
ischecks if objects point to the same memory locationx is yTrue/False
is notchecks if objects are not identicalx is not yTrue/False
inchecks presence of an element in a collection"py" in "python"True
not inchecks 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.

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

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

StructureExample SyntaxMutableOrderedElement Uniqueness
list[1, 2, 3]YesYesAny
tuple(1, 2, 3)NoYesAny
dict (dictionary){"a": 1}YesYes (since Python 3.7)Keys must be unique
set{1, 2, 3}YesNoUnique values only

Examples of Collection Usage in Code

List (list) – a dynamic array for storing elements:

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

python
coords = (10, 20)
print(coords[0])  # 10

Dictionary (dict) – an associative structure storing key-value pairs:

python
user = {"name": "Adam", "role": "admin"}
print(user["name"])  # Adam

Set (set) – a collection storing only unique values, automatically eliminating duplicates:

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

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

python
count = 0
while count < 3:
    print(count)
    count += 1

The if Conditional Statement

Allows for conditional branching of program execution paths:

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

python
# 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:

python
# 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.

Let's work together

Ready to get started?

Got something I could help with? Get in touch — happy to share what I know.

Get in touch