Now that your Python project is set up and your IDE is ready, it’s time to dive into the fundamentals of Python syntax. If you’re coming from PHP, you’ll notice some key differences in how Python handles code structure, variables, and control flow. This section will guide you through the core syntax elements that form the foundation of Python programming.
1. Indentation and Code Structure⌗
Python uses indentation (spaces or tabs) to define blocks of code, unlike PHP, which uses braces {} for this purpose. Proper indentation is mandatory in Python and determines the scope of loops, conditionals, and functions.
Example:
if 5 > 2:
print("5 is greater than 2")
print("This line is also inside the if block")
print("This line is outside the if block")
Key Rules:
- Use 4 spaces per indentation level (the most common convention).
- Avoid mixing tabs and spaces.
- Python enforces consistent indentation, so tools like PEP 8 (Python’s style guide) help maintain readability.
2. Variables and Dynamic Typing⌗
Python is a dynamically typed language, meaning you don’t need to declare a variable’s type explicitly. Variables are created by assigning a value to them using the = operator.
Example:
x = 10 # Integer
y = "Hello" # String
z = True # Boolean
Key Features:
- Variables can change type dynamically.
- No need for semicolons
;at the end of statements (though allowed). - Variable names are case-sensitive and should follow snake_case (e.g.,
my_variable).
3. Data Types⌗
Python supports a wide range of built-in data types. Here are the most commonly used ones:
| Data Type | Description | Example | |
|---|---|---|---|
| int | Integer (whole numbers) | x = 42 |
|
| float | Floating-point numbers (decimals) | y = 3.14 |
|
| str | String (text) | name = "Alice" |
|
| list | Ordered, mutable collection | fruits = ["apple", "banana", "cherry"] |
|
| tuple | Ordered, immutable collection | coordinates = (10, 20) |
|
| dict | Unordered, key-value pairs | person = {"name": "Bob", "age": 30} |
|
| bool | Boolean (True or False) | is_valid = True |
|
| set | Unordered, unique elements | unique_numbers = {1, 2, 3} |
Note: Python automatically infers the type of a variable based on its value.
4. Control Structures⌗
Python uses keywords like if, elif, else, for, and while to control program flow. These are similar to PHP but use indentation instead of braces.
Example: Conditional Statements
age = 18
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Example: Loops
# For loop
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
# While loop
count = 0
while count < 5:
print("Count:", count)
count += 1
Key Differences from PHP:
- No need for braces
{}to enclose code blocks. elifis used instead ofelse if.
5. Functions⌗
Functions in Python are defined using the def keyword. They can take parameters and return values, much like PHP functions.
Example:
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message) # Output: Hello, Alice!
Key Features:
- Functions are first-class citizens (can be assigned to variables, passed as arguments, etc.).
- Use
*argsand**kwargsfor variable numbers of arguments.
6. Comments and Documentation⌗
Python uses # for single-line comments and triple quotes (""") for multi-line comments or docstrings.
Example:
# This is a single-line comment
x = 10 # Assigning value to x
"""
This is a multi-line comment.
It can span multiple lines.
"""
def add(a, b):
"""
Adds two numbers and returns the result.
"""
return a + b
7. Print Statements⌗
Python uses the print() function to output text to the console. It automatically adds a newline character at the end.
Example:
print("Hello, World!") # Output: Hello, World!
print("Python", "is", "fun!") # Output: Python is fun!
Note: In Python 3, print() is a function, unlike PHP’s echo or print_r.
Summary⌗
This section covered the core syntax elements of Python, including:
- Indentation as the primary way to define code blocks.
- Variables and data types with dynamic typing.
- Control structures like
if,for, andwhile. - Functions defined with
def. - Comments and print statements.
These concepts form the foundation for writing Python programs. In the next section, we’ll explore data structures in more detail, such as lists, dictionaries, and tuples.