Python Syntax

Python’s renowned readability and user-friendly syntax are cornerstones of its popularity. This guide delves into the fundamental rules of Python syntax, empowering you to craft well-structured and effective Python code.

Key Elements of Python Syntax:

  • Whitespace and Indentation:
    • Python employs whitespace, particularly indentation, to define code blocks instead of curly braces.
    • Consistent indentation is crucial for correct code execution.
    • Example:
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")
  • Comments:
    • Comments clarify code purposes and enhance readability.
    • Single-line comments start with #.
    • Multi-line comments are enclosed within triple quotes (“”” or ”’).
    • Example:
# Calculate the area of a rectangle
length = 10
width = 5
area = length * width  # Calculate the area
print("The area is:", area)
  • Variables:
    • Variables store data values.
    • Naming conventions: start with a letter or underscore, use letters, numbers, or underscores.
    • Dynamically typed: no need to specify data type beforehand.
    • Example:
name = "Alice"
age = 30
is_active = True
  • Data Types:
    • Common data types:
      • Numbers (int, float, complex)
      • Strings (text enclosed in single or double quotes)
      • Lists (ordered collections of items, mutable)
      • Tuples (ordered collections of items, immutable)
      • Dictionaries (unordered collections of key-value pairs)
    • Example:
numbers = [1, 2, 3, 4]
person = {"name": "Bob", "age": 25}
  • Operators:
    • Arithmetic operators: +, -, *, /, // (integer division), % (modulo), ** (exponent)
    • Comparison operators: ==, !=, <, >, <=, >=
    • Logical operators: and, or, not
    • Example:
result = (5 + 3) * 2  # Arithmetic operations
if x > y and y > z:  # Logical operations
    print("x is the largest")
  • Control Flow Statements:
    • if-else statements: conditional execution
    • for loops: iterating over sequences
    • while loops: repeating code based on a condition
    • Example:
for i in range(5):
    print(i)  # Prints numbers from 0 to 4

count = 0
while count < 3:
    print("Counting:", count)
    count += 1
  • Functions:
    • Reusable blocks of code that perform specific tasks.
    • Defined using the def keyword.
    • Example:
def greet(name):
    print("Hello,", name + "!")

greet("World")  # Output: Hello, World!

Remember:

Consistent formatting and indentation are essential for writing clear and maintainable Python code. Practice regularly to solidify your understanding of Python syntax and its nuances.