Skip to Content
Course content

1.3 Python Syntax and Structure

Understanding Python syntax and structure is crucial for writing clean, efficient, and error-free code. Python’s syntax is known for being easy to learn and very readable. In this section, we’ll explore the key elements of Python syntax and how the code structure works.

Python Indentation

  • Whitespace and Indentation:
    • Python uses indentation (spaces or tabs) to define the structure of code blocks, such as loops, functions, and classes. Unlike many other programming languages that use curly braces {} to define code blocks, Python relies on indentation.
    • Consistent indentation is critical in Python; incorrect indentation will result in errors.

Example:

# Correct indentation
if True:
    print("This is indented correctly.")

# Incorrect indentation (will raise an error)
if True:
print("This is not indented correctly.")

In the above example, the code inside the if statement is indented by 4 spaces (or one tab), which is the standard in Python.

Python Statements

  • Statements in Python are instructions that the Python interpreter executes. Each line of code typically represents one statement.

Example:

x = 10  # Assignment statement
print(x)  # Function call statement
  • Python statements can span multiple lines, and the interpreter will understand them if they are logically continued.

Example:

total = 10 + \
        20 + \
        30
print(total)

Python Comments

  • Comments are text in your code that are not executed but provide explanations for humans reading the code.
  • Comments start with the hash mark (#) and extend to the end of the line.

Example:

# This is a single-line comment
x = 10  # This is an inline comment

# Multi-line comments can be written like this:
'''
This is a
multi-line comment.
'''
  • Docstrings are a special type of comment used to document functions, classes, and modules. They are placed in triple quotes (""" or ''') and are used to describe the purpose or functionality of the code.

Example:

def greet():
    """
    This function prints a greeting message.
    """
    print("Hello, World!")

Variables and Data Types

  • Variables are used to store values in Python. They don't need explicit declaration of types (Python is dynamically typed), so you can assign values directly.

Example:

x = 5  # An integer
name = "Alice"  # A string
is_active = True  # A boolean
  • Python has several built-in data types, including:
    • Integers (int) – Whole numbers (e.g., 1, 100, -5).
    • Floating-point numbers (float) – Decimal numbers (e.g., 3.14, -0.001).
    • Strings (str) – Sequences of characters (e.g., "Hello").
    • Booleans (bool) – True or False values.
    • Lists, Tuples, Dictionaries, and Sets are other important data types used for storing collections of data.

Python Operators

  • Operators are symbols that perform operations on variables and values. Python supports several types of operators:
    • Arithmetic operators: +, -, *, /, %, //, **
    • Comparison operators: ==, !=, >, <, >=, <=
    • Logical operators: and, or, not
    • Assignment operators: =, +=, -=, *=, /=

Example:

a = 10
b = 20
c = a + b  # Addition operator
print(c)

Python Control Structures

  • Python has several control structures that help in making decisions and repeating actions in the program:
    • Conditional Statements (if, elif, else):
      x = 10
      if x > 5:
          print("x is greater than 5")
      else:
          print("x is less than or equal to 5")
      
    • Loops (for, while):
      • for loop: Iterates over a sequence (e.g., list, string).
        for i in range(5):
            print(i)
        
      • while loop: Repeats a block of code while a condition is true.
        count = 0
        while count < 5:
            print(count)
            count += 1
        

Functions

  • Functions are reusable blocks of code that perform a specific task. You define functions using the def keyword, followed by the function name and parameters.

Example:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")  # Calling the function

Functions can return values using the return keyword.

def add(a, b):
    return a + b

result = add(5, 3)
print(result)

Python Blocks and Scope

  • Blocks in Python are created using indentation (as explained earlier). They are groups of code that are executed together under certain conditions (e.g., inside a function or loop).
  • Scope refers to the region of the program where a variable or function is accessible. Variables declared inside a function are in local scope, and those declared outside are in global scope.

Summary

Python syntax is simple and emphasizes readability, with consistent indentation for defining blocks of code. Python's use of indentation instead of braces {} makes it visually appealing and less cluttered. You should understand:

  • Indentation and statements.
  • Variables, data types, and operators.
  • Control structures for flow control.
  • Functions for reusable code blocks.

This structure allows developers to write Python code quickly and with minimal confusion, making it a favorite for both beginners and advanced programmers.

Commenting is not enabled on this course.