Unit 3: Python Programming Statements
3.1 Comments, Indentations, Exception Handling
Comments:
● Single-line comments: Begin with # and extend to the end of the line.
Example: # This is a single-line comment
Multi-line comments: Use triple quotes (''' or """) for block comments.
Example:
Indentations:
● Python uses indentation to define the structure of the code (no braces {}).
All indented blocks must have the same level of spaces (typically 4 spaces).
Example:
Exception Handling:
● Used to manage errors gracefully.
Try-Except block:
Finally block: Executes regardless of exceptions.
3.2 Assignment, Expressions, and Print
Assignment:
● Assign values using =. Example: x = 10
Multiple Assignments:
Expressions:
● Combination of variables, operations, and values. Example: result = a + b * c
Print:
Display output using the print() function.
Example:
3.3 Branching and Looping
If Statements:
Syntax:
Example:
While Loop:
Repeats while a condition is True. Example:
For Loop:
Iterates over a sequence (list, string, range, etc.). Example:
3.4 List and Dictionary Traversal
List Traversal:
Using for loop:
Dictionary Traversal:
Iterate over keys, values, or both:
3.5 Function Basics
3.5.1 Definition, Call, Passing Arguments
Define a Function:
Call a Function:
● Passing Arguments:
○ Positional Arguments: Matched by order. Example: greet("Bob")
○ Keyword Arguments: Matched by name. Example:
greet(name="Charlie")
3.5.2 Lambda Functions
Anonymous functions defined with lambda keyword. Syntax: lambda arguments:
expression Example:
3.6 Modules
3.6.1 Python Program Structure
3.6.2 Import and Attributes
Import Modules:
Import Specific Attributes:
Alias Modules:
3.6.3 Module Creation and Usage
Create a Python file (e.g., my_module.py) with functions/classes.
Use it in another file: