Skip to main content

1. What is a Statement?

  • A statement is a unit of code that performs an action or a task.
  • Statements can include variable assignments, function calls, loops, conditionals, and more.
  • Every line of code in Python is typically a statement.
Examples:

2. Types of Statements

Python statements can be categorized into the following types:

1. Assignment Statements

  • Used to assign a value to a variable.
  • The = operator is used for assignment.
Examples:
  • Multiple Assignments:

2. Expression Statements

  • Any expression becomes a statement when it is used on its own.
  • Examples include arithmetic operations, function calls, etc.
Examples:

3. Conditional Statements (if, elif, else)

  • Used to make decisions based on conditions.
  • Keywords: if, elif, else.
Examples:

4. Loop Statements (for, while)

  • Used to repeat a block of code multiple times.
  • Keywords: for, while.
Examples:
  • For Loop:
  • While Loop:

5. Function Definition Statements (def)

  • Used to define reusable blocks of code.
  • Keyword: def.
Example:

6. Import Statements

  • Used to import modules or specific functions/classes from modules.
  • Keyword: import.
Examples:

7. Control Flow Statements (break, continue, pass)

  • Used to control the flow of loops or conditionals.
  • Keywords: break, continue, pass.
Examples:
  • Break:
  • Continue:
  • Pass:

8. Return Statements

  • Used in functions to return a value to the caller.
  • Keyword: return.
Example:

9. Exception Handling Statements (try, except, finally)

  • Used to handle errors and exceptions in code.
  • Keywords: try, except, finally.
Example:

3. Compound Statements

  • Statements that contain other statements, such as loops, conditionals, and function definitions.
  • They are often indented to define blocks of code.
Examples:

4. Simple vs Compound Statements

  • Simple Statements: Single-line statements that perform a single task.
  • Compound Statements: Multi-line statements that contain blocks of code.

5. Additional Examples

  • Assignment Statement:
  • Conditional Statement:
  • Loop Statement:
  • Function Definition Statement:

6. Best Practices

  • Use meaningful variable names to make statements clear and readable.
  • Keep lines short and avoid overly complex statements.
  • Use comments to explain the purpose of complex statements.