[Python] Control Structures
Categories: Python
Tags: Control Structures
📋 Here are the notes summarizing what I learned from the course!
Control Structures
By understanding control structures, it is possible to implement the appropriate computational logic and validate the effects of a set of code statements.
1. Sequence
This is the natural order of processing, where each statement is processed sequentially until the end of the instruction set. Statements are not skipped, jumped, or repeated.
This control structure always produces the same effect because the same set of statements are processed in the same order.
num_list = [1, 2, 3, 4]
num_list.append(5)
print(f'Output: {num_list}')
Explanation:
- The code executes in the order it is written.
- Each line is executed one after the other.
2. Conditionals (Branching or Selection Logic)
Allows for the creation and execution of alternative flows (i.e., group of statements) based on a value, evaluation, state, or expression.
If Statement
Executes a block of code if a specified condition is true.
x = 10
if x > 5:
print("x is greater than 5")
If-Else Statement
Executes one block of code if a specified condition is true, and another block if it is false.
x = 10
if x > 15:
print("x is greater than 15")
else:
print("x is not greater than 15")
If-Elif-Else Statement
Executes different blocks of code depending on multiple conditions.
x = 10
if x > 15:
print("x is greater than 15")
elif x == 10:
print("x is 10")
else:
print("x is less than 10")
Explanation:
- Conditionals allow for decision-making in code.
- Different paths of execution are chosen based on conditions.
3. Loops
Loops are used to repeat a block of code multiple times.
3.1 While Loops
Repeats a block of code as long as a specified condition is true.
count = 0
while count < 5:
print(f'Count: {count}')
count += 1
3.2 For Loops
Iterates over a sequence (such as a list, tuple, or string) and executes a block of code for each item in the sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f'I like {fruit}')
Explanation:
while
loops repeat code based on a condition.for
loops iterate over elements of a sequence.
4. Functions
Functions are blocks of reusable code that perform a specific task.
Defining a Function
Create a function using the def
keyword, followed by the function name and parameters.
def greet(name):
print(f'Hello, {name}!')
Calling a Function
Execute the function by calling it with the required arguments.
greet('Alice')
Returning a Value
Functions can return a value using the return
statement.
def add(a, b):
return a + b
result = add(5, 3)
print(f'The sum is: {result}')
Explanation:
- Functions help in organizing code into reusable blocks.
- They can take parameters and return values.
Leave a comment