graph TD;
A{Condition 1?} -->|Yes| B[Execute Block 1]
A -->|No| C{Condition 2?}
C -->|Yes| D[Execute Block 2]
C -->|No| E[Execute Block 3]
Code blocks are a group of statements that are executed together.
In Python, indentation is used to define blocks of code.
Python uses whitespaces (spaces or tabs) at the beginning of a line to determine the indentation level of the line.
The amount of indentation is flexible, but it must be consistent throughout that block.
Generally, four spaces are used for each level of indentation.
Example:
graph TD;
A{Condition 1?} -->|Yes| B[Execute Block 1]
A -->|No| C{Condition 2?}
C -->|Yes| D[Execute Block 2]
C -->|No| E[Execute Block 3]
The if statement is used for decision-making in Python programming. It tests a condition and executes a block of code only if that condition evaluates to True. If the condition is False, the block of code is skipped.
The if statement can be combined with elif and else clauses to control the flow of execution in the program, allowing for the implementation of more complex logical structures.
Objective: Categorize life stages by age.
age = 20"Adult"Loops in Python are used to execute a block of code repeatedly. Python provides two types of loops: for and while.
graph TB;
A[Start Loop<br/>for item in iterable:] --> B[Execute Block]
B --> A
A -->|No More Items| C[End Loop]
for LoopsA for loop is used to iterate over a sequence (e.g., a list, tuple, string, or range) and execute a block of code for each item in the sequence.
while LoopsA while loop, on the other hand, continues to execute a block of code as long as a given condition evaluates to True.
break: Immediately exits a loop.continue: Skips the remainder of the loop’s body and immediately proceeds with the next iteration.pass: Acts as a placeholder, allowing for the definition of empty control structures.List Comprehensions in Python are a concise and efficient way to create lists. They allow for the construction of a new list by applying an expression to each item in an iterable, optionally filtering items to include only those that meet a condition.
The basic syntax of a list comprehension is:
where:
Error handling is a critical aspect of writing robust Python programs. Python provides the try and except blocks to catch and handle exceptions, preventing the program from terminating unexpectedly.
A common error in programming is division by zero, which occurs when a number is divided by zero. Python raises a ZeroDivisionError exception in such cases.
The basic syntax for handling exceptions in Python is:
Write a program that generates the first 20 numbers in the Fibonacci sequence.
Hints:
Example output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181