Skip to Content
Course content

1.3.1 Basics of Python syntax

Python's syntax is designed to be clear, simple, and easy to understand. It is one of the main reasons Python is considered an excellent language for beginners. Let’s explore the key elements of Python syntax that you need to know.

1. Indentation

  • Indentation is crucial in Python. Unlike other programming languages that use curly braces {} to group statements, Python uses indentation (spaces or tabs) to define the structure of code blocks. This includes defining the body of loops, functions, and conditional statements.
  • Python’s strict use of indentation ensures that your code is consistently organized and readable.

Example:

# Correct indentation
if True:
    print("This is inside the if statement")
    
# Incorrect indentation (will result in an error)
if True:
print("This is not indented properly")

By default, Python recommends using 4 spaces for each level of indentation.

2. Comments

  • Comments are used to add explanations or notes in the code. Python provides two types of comments:
    • Single-line comments: These are preceded by the # symbol and extend to the end of the line.
    • Multi-line comments: These are written using triple quotes ''' or """.

Example:

# This is a single-line comment

'''
This is a multi-line comment.
It can span several lines.
'''

"""
Another example of multi-line comment.
"""
  • Docstrings are special comments used to document functions, classes, and modules. They are written inside triple quotes """ or ''' and provide descriptions for code components.

3. Variables and Data Types

  • Python is a dynamically typed language, which means you don't need to explicitly declare the data type of a variable. The type is inferred based on the value assigned to it.

Example:

x = 10  # Integer
y = "Hello, Python"  # String
z = 3.14  # Floating-point number
is_valid = True  # Boolean

Python supports various data types, such as:

  • Integers (int): Whole numbers (e.g., 5, 100).
  • Floating-point numbers (float): Decimal numbers (e.g., 3.14, 0.99).
  • Strings (str): Text (e.g., "Hello").
  • Booleans (bool): True or False values.

4. Keywords and Identifiers

  • Keywords are reserved words in Python that have special meaning. Examples include if, else, for, while, def, import, etc.
  • Identifiers are names you give to variables, functions, or classes. They must start with a letter (a-z, A-Z) or an underscore (_), followed by letters, digits, or underscores.

Example:

def greet():  # 'greet' is an identifier (function name)
    pass
  • Keywords cannot be used as identifiers.

5. Basic Operators

Python supports a variety of operators that perform operations on variables and values. Some common categories include:

  • Arithmetic operators:
    • + (addition)
    • - (subtraction)
    • * (multiplication)
    • / (division)
    • // (integer division)
    • % (modulus)
    • ** (exponentiation)
  • Comparison operators:
    • == (equal to)
    • != (not equal to)
    • > (greater than)
    • < (less than)
    • >= (greater than or equal to)
    • <= (less than or equal to)
  • Logical operators:
    • and (logical AND)
    • or (logical OR)
    • not (logical NOT)

6. Control Flow Statements

Python provides control flow statements that allow you to make decisions and repeat actions:

  • Conditional Statements:
    • The if, elif, and else keywords help control the flow of execution based on conditions.

    Example:

    x = 10
    if x > 5:
        print("x is greater than 5")
    else:
        print("x is 5 or less")
    
  • Loops:
    • Python supports for and while loops to repeat tasks.
    • for loop: Iterates over a sequence (list, string, etc.)

    Example:

    for i in range(5):
        print(i)
    
    • while loop: Repeats as long as a condition is true.

    Example:

    count = 0
    while count < 5:
        print(count)
        count += 1
    

7. Functions

  • Functions are blocks of code that perform specific tasks. They are defined using the def keyword and can take parameters and return values.

Example:

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

greet("Alice")
  • Functions can return values using the return keyword.

Example:

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

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

8. Error Handling (Exceptions)

  • Python provides exception handling using try, except, and finally blocks. This allows you to handle errors gracefully without crashing the program.

Example:

try:
    x = 10 / 0  # Division by zero
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This will always execute")

9. Python Code Structure

Python code is typically structured into modules (files), classes (blueprints for creating objects), and functions (reusable code). Python supports object-oriented programming (OOP) as well as procedural programming, allowing flexibility in how you organize your code.

Summary

Python's syntax is designed to be easy to read and write. The basic structure includes:

  • Indentation to define code blocks.
  • Variables and data types that are dynamically assigned.
  • Operators for performing arithmetic, comparison, and logical operations.
  • Control flow statements (if, else, for, while) for decision-making and iteration.
  • Functions for reusing code.

Mastering these basics will provide a strong foundation for writing Python programs and understanding more advanced concepts.

Commenting is not enabled on this course.