🐍 Python Syntax Essentials: Clean Guide with Examples and Insights
✅ Statements and Indentation
Python uses indentation to define blocks of code. Unlike many other languages that use curly braces {}
or keywords, Python enforces indentation.
# Example:
def greet(name):
print("Hello", name)
- Recommended: Use 4 spaces per indentation level.
- Consistency is key: Mixing tabs and spaces can lead to errors.
You can also place multiple statements on one line using ;
, though it’s discouraged:
x = 1; y = 2; print(x + y)
✅ Comments in Python
- Single-line comments start with
#
- For multi-line documentation, use triple quotes (
'''
or"""
)
# This is a comment
x = 10 # Inline comment
"""
This is a multiline comment.
Used for module or function descriptions.
"""
Shortcut for commenting in editors:
- VSCode:
Ctrl + /
- IDLE:
Alt + 3
✅ Variables and Memory Allocation
- Variables in Python are dynamically typed.
- You don’t need to declare the type explicitly.
- Internally, every variable is a reference to an object in memory (like a pointer).
x = 42 # int
name = "Raj" # str
pi = 3.14 # float
Python uses reference counting and garbage collection to manage memory. Example:
x = [1, 2, 3]
y = x # Both x and y point to the same list in memory
✅ Python Numbers and Boolean Values
Numeric Types in Python:
int
: Whole numbersfloat
: Numbers with decimalscomplex
: Numbers with real and imaginary parts
x = 10 # int
pi = 3.14 # float
z = 2 + 3j # complex
Use type()
to check:
print(type(x)) # <class 'int'>
print(type(pi)) # <class 'float'>
print(type(z)) # <class 'complex'>
You can perform arithmetic operations with all numeric types.
print(x + pi) # 13.14
print(z * (1 + 2j)) # Complex multiplication
Boolean Values:
- Only two:
True
andFalse
- Internally,
True
is 1 andFalse
is 0 - Often used in conditions, comparisons, and logical operations
is_ready = True
is_valid = False
print(True + 5) # 6
print(False * 10) # 0
Used in control flow:
if is_ready:
print("Ready to go!")
else:
print("Hold on.")
Conversion:
print(bool(0)) # False
print(bool(123)) # True
print(bool("")) # False
print(bool("abc")) # True
✅ Multiple Assignments
x, y, z = 1, 2.5, "hello"
print(x, y, z)
x = y = z = 100 # All three variables point to the same value
✅ Swapping Made Easy
x, y = 10, 20
x, y = y, x
✅ Variable Naming Rules & Best Practices
- Rules
- Must start with a letter (a-z, A-Z) or underscore (_)
- Followed by letters, digits, or underscores
- Case-sensitive
- Best Practices
- Use snake_case:
user_name
- Use meaningful names:
count
,total_price
- Avoid keywords:
if
,for
,def
- Constants:
MAX_LIMIT = 100
- Use snake_case:
# Good
customer_name = "Alice"
PI = 3.14159
# Bad
1stVar = 5 # SyntaxError
If = 7 # 'if' is a keyword
🔢 Python Operators (with Examples)
1. Arithmetic Operators
a, b = 10, 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000
2. Comparison Operators
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a < b) # False
3. Logical Operators
x, y = True, False
print(x and y) # False
print(x or y) # True
print(not x) # False
4. Assignment Operators
x = 5
x += 2 # x = 7
x *= 3 # x = 21
x **= 2 # x = 441
5. Identity Operators
list1 = [1, 2, 3]
list2 = list1
list3 = list1[:]
print(list1 is list2) # True (same object)
print(list1 is not list3) # True (different objects)
6. Membership Operators
colors = ["red", "blue"]
print("red" in colors) # True
print("green" not in colors) # True
7. Bitwise Operators
x, y = 6, 3
print(x & y) # 2
print(x | y) # 7
print(x ^ y) # 5
print(~x) # -7
print(x << 1) # 12
print(x >> 1) # 3
📐 Operator Precedence (PEMDAS)
- P: Parentheses
()
- E: Exponentiation
**
- M/D: Multiplication/Division
- A/S: Addition/Subtraction
result = 2 + 3 * 4 # 14
result = (2 + 3) * 4 # 20
Left to right for operators of same precedence.
💻 Bonus: Complete Operator Use Case
a = 10
b = 5
result = (a + b) * 2
if result >= 30:
print("Result is large")
if result > 0 and result % 2 == 0:
print("Result is a positive even number")
# Bitwise check
if result & 1 == 0:
print("Even number via bitwise check")
# Membership test
nums = [10, 15, 20]
if 10 in nums:
print("10 found")
# Identity test
x = nums
y = nums[:]
print(x is y) # False (different memory)
🧠 How Python Handles Variables in Memory
- Every variable is a reference to an object in memory.
- Python uses reference counting and garbage collection to manage memory.
- Use
id(var)
to check memory address.
x = [1, 2, 3]
y = x
z = x[:]
print(id(x), id(y), id(z))
Leave a Reply