Welcome to the second lesson in our Python Essential Training series. In this post, we’ll cover the basic building blocks of Python: syntax, variables, data types, type casting, and comments. These are the foundations you need before moving on to control flow, functions, and more advanced concepts.
1. Python Syntax
Python is designed to be easy to read and write. Unlike other languages, Python uses indentation (spaces or tabs) instead of curly braces to define code blocks.
# Correct indentation
if True:
print("This is indented correctly")
# Wrong indentation → will cause an error
if True:
print("This will cause an IndentationError")
Key points:
- Indentation is mandatory in Python (default = 4 spaces).
- Statements end automatically (no semicolons needed).
- Case-sensitive:
Variableandvariableare different.
2. Variables
Variables are used to store data values. In Python, you don’t need to declare the type explicitly; Python figures it out automatically.
# Assigning values
name = "Alice"
age = 25
height = 5.6
print(name) # Alice
print(age) # 25
print(height) # 5.6
Rules for variable names:
- Must start with a letter or underscore (_).
- Cannot start with a number.
- Can only contain letters, numbers, and underscores.
- Should be descriptive (use
user_ageinstead ofx).
2.1 Constants
A constant is a value you decide not to change in your program. Python doesn’t lock constants, so we use a naming rule: write them in ALL_CAPS.
# Constants by naming convention (ALL_CAPS)
PI = 3.14159
MAX_USERS = 100
SITE_NAME = "Geeksters.link"
# Using them
radius = 5
area = PI * (radius ** 2)
print("Area:", area)
print("Welcome to", SITE_NAME)
Best practice: Use ALL_CAPS for values you don’t plan to change, and avoid reassigning them.
If a value may change, use a regular variable (lowercase, e.g., tax_rate) instead of an ALL_CAPS name.
Optional (for later): Type-checked constants
If you use a type checker (like mypy) or modern editors, you can add a small hint so reassignment is flagged:
from typing import Final
API_URL: Final = "https://api.example.com"
# API_URL = "https://other.com" # Editors/type checkers will warn you
3. Data Types in Python
Python has several built-in data types. Let’s explore the most common ones.
a) Integers and Floats
x = 10 # Integer
y = 3.14 # Float
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
b) Booleans
is_active = True
is_logged_in = False
print(is_active) # True
print(type(is_logged_in)) # <class 'bool'>
c) Strings
greeting = "Hello, Python!"
print(greeting.upper()) # HELLO, PYTHON!
print(greeting.lower()) # hello, python!
print(len(greeting)) # 14
c.1 More on Strings: Formatting & Methods
Strings are very powerful in Python. Besides upper/lower methods, you can also use formatting and other built-in functions.
String Formatting
name = "Alice"
age = 25
# f-string (modern, recommended)
print(f"My name is {name} and I am {age} years old.")
# str.format() method
print("My name is {} and I am {} years old.".format(name, age))
Useful String Methods
text = "Python is fun"
print(text.split()) # ['Python', 'is', 'fun']
print("-".join(["A", "B", "C"])) # A-B-C
print(text.replace("fun", "powerful")) # Python is powerful
These methods make it easy to manipulate and work with text data.
d) Bytes
Bytes are used for handling binary data, such as images or network packets.
data = b"Python" # b prefix makes it bytes
print(data) # b'Python'
print(type(data)) # <class 'bytes'>
e) None (Null)
None represents “no value” or “nothing here yet”. Its type is NoneType.
result = None
print(result is None) # True
print(type(result)) # <class 'NoneType'>
# A common pattern:
name = None # will be filled later
if name is None:
print("No name provided yet")
4. Type Casting
You can convert between data types using built-in functions like int(), float(), str(), etc.
# Casting examples
x = int("10") # String to integer
y = float("3.14") # String to float
z = str(100) # Integer to string
print(x + 5) # 15
print(y * 2) # 6.28
print("Value: " + z) # Value: 100
4.1 Type Annotations (Optional, but Recommended)
Type annotations (also called type hints) let you describe what types your variables and function parameters/returns are supposed to be. They don’t change how Python runs your code at runtime, but they make your code clearer and help editors/tools catch mistakes early.
Why use them?
- Better editor help (auto-complete, inline warnings)
- Fewer bugs (type checkers like
mypyor VS Code’s Pylance can warn you) - Clearer code for your future self and teammates
Variable annotations
name: str = "Ali"
age: int = 31
price: float = 19.99
is_active: bool = True
# Containers (Python 3.9+)
scores: list[int] = [88, 92, 79]
user: dict[str, str] = {"name": "Ammar"}
# Tuple and optional value (Python 3.10+ union operator)
point: tuple[int, int] = (10, 20)
nickname: str | None = None # None means “no value yet”
Function annotations
def greet(name: str, times: int = 1) -> str:
return ("Hello, " + name + "! ") * times
def log(message: str) -> None:
print(message) # returns nothing → None
Note: Python ignores type hints at runtime. To get warnings, run a type checker (e.g., mypy) or enable type checking in VS Code ( Settings → Pylance → Type Checking Mode: basic or strict).
5. Comments
Comments are notes in your code that are ignored by the Python interpreter. They make your code easier to understand for yourself and others.
# This is a single-line comment
"""
This is a multi-line comment
Useful for adding detailed explanations
"""
print("Hello, Comments!") # Inline comment
Pro Tip: Always use comments to explain why you wrote something, not just what it does.
Key Takeaways
- Python uses indentation to structure code (no braces or semicolons needed).
- Variables store data without explicit type declarations.
- Core data types : int, float, bool, str, bytes (and optionally None) .
- Constants are by convention (
ALL_CAPS); avoid reassigning them in your code. - Strings: use f-strings for formatting; handy methods include
strip,replace,split, andjoin. - Use type casting to convert values:
int(),float(),str(), etc. - Type annotations (optional) make code clearer and help tools catch mistakes; they don’t affect runtime.
In the next lesson, we’ll dive into Python Operators and Expressions to learn how to perform calculations and logic with Python.
Leave a comment
Your email address will not be published. Required fields are marked *
