Python Control Structures Unexecuted
Python Control Structures Unexecuted
If Statements
If statements are essential control structures in programming that allow you to make decisions and exe-
cute code based on certain conditions. They enable your program to choose between alternative paths of
execution.
Basic Syntax of an If Statement:
The basic structure of an if statement is as follows: if condition:
code to be executed if the condition is true
The ‘condition’ is an expression that evaluates to either True or False.
[ ]: age = 18
In this example, the if statement checks whether the ‘age’ is greater than or equal to 18. If the condition is
true, it prints the eligibility message; otherwise, it prints the ineligible message.
Using Elif for Multiple Conditions
The ‘elif’ (short for “else if”) keyword allows you to specify additional conditions to check if the previous
condition is false.
1
[ ]: number = 0
if number > 0:
print("Number is positive.")
elif number == 0:
print("Number is zero.")
else:
print("Number is negative.")
In this example, the if statement checks multiple conditions in sequence and executes the appropriate code
block.
Nested If Statements
If statements can be nested within each other to handle more complex decision-making scenarios.
[ ]: age = 25
income = 50000
In this example, nested if statements are used to determine loan eligibility based on age and income.
Ternary Operator (Conditional Expression)
Python also supports a concise way to write simple if-else statements using the ternary operator.
[ ]: x = 10
y = 20
max_value = x if x > y else y
print("Maximum value:", max_value)
The ternary operator assigns the value of ‘x’ to ‘max_value’ if ‘x’ is greater than ‘y’, otherwise it assigns the
value of ‘y’ to ‘max_value’.
In Summary, if statements provide a way to make decisions in your code by evaluating conditions. They
allow you to execute different code blocks based on whether a condition is true or false.
With the addition of ‘elif’ and ‘else’, you can handle multiple scenarios and paths of execution.
Mastering if statements is essential for creating dynamic, responsive, and logic-driven programs.
For Loops
For loops are used to iterate over a sequence of items, such as a list, range, or string. They execute a block
of code for each item in the sequence. For loops are fundamental control structures in Python used for
repetitive tasks. They are designed to iterate over a sequence of items, performing a set of actions for each
item.
The basic syntax of a for loop is as follows:
2
for item in sequence:
Code to be executed for each item
Common sequences include lists, ranges, strings, and dictionaries.
Let’s explore some key aspects of for loops and start with a basic example, below.
print(i)
# This line prints the current value of 'i' during each iteration.
You can also loop over other sequences like lists, tuples, strings, etc. For example:
For loops are versatile and can be extended with advanced concepts like nested loops, list comprehensions,
and the enumerate() function. They are essential tools for automating repetitive tasks and processing data
in various forms.
Remember that the indentation is crucial in Python. The code block inside the for loop must be indented
properly to indicate its scope.
Nested Loops
Nested loops are used when you want to iterate over multiple sequences within each other.
In some scenarios, you may need to work with multiple sequences simultaneously. Nested loops provide a
way to iterate over combinations of items from different sequences. The structure of a nested loop involves
placing one loop inside another loop. Each iteration of the outer loop triggers a complete iteration of the
inner loop.
3
for j in range(2):
print(f"i: {i}, j: {j}")
# This loop structure will print all combinations of i and j.
In summary, dictionaries provide a flexible way to store and retrieve data. Using for loops to iterate through
dictionaries allows you to work with keys, values, and key-value pairs effectively.
4
[ ]: # Using enumerate() to get index and value
print("\nUsing enumerate() with a list:")
The enumerate() function adds a counter to an iterable and returns it in a form of enumerate object. You
can use it to get both the index and the value of items in a sequence.
While Loops
While loops are another fundamental control structure in Python that allow you to repeat a block of code
as long as a certain condition is true. Unlike for loops, which iterate over a sequence, while loops continue
executing as long as the specified condition remains true.
A while loop starts by evaluating the condition. If the condition is initially false, the code inside the loop
may not execute at all.
While loops are useful when the number of iterations is not known beforehand or when you want to repeat
a process until a specific condition is met.
The loop continues to execute while the ‘countdown’ variable is greater than 0. The variable is decremented
by 1 in each iteration.
Caution: Infinite Loops –> It’s important to be cautious with while loops, as an incorrect or unchanging
condition can lead to infinite loops, causing your program to run indefinitely. Make sure the condition
eventually becomes false.
While loops can be controlled using break and continue statements to exit the loop prematurely or skip
iterations. In summary, while loops provide a way to repeatedly execute code while a condition remains
true. They are versatile tools for scenarios where the number of iterations is uncertain or when waiting for
specific conditions.
Functions
Functions are fundamental building blocks in programming that allow you to organize, modularize, and
reuse code. They encapsulate a set of instructions and can be invoked with arguments to perform specific
tasks. Functions enhance code readability, maintainability, and allow for efficient development.
Defining a Function
In Python, functions are defined using the ‘def’ keyword, followed by the function name and a pair of
parentheses. Parameters (input values) can be specified inside the parentheses, and the colon indicates the
5
start of the function block.
[ ]: def greet(name):
"""A function to greet a person by name."""
print(f"Hello, {name}!")
Calling a Function
To use a function, you ‘call’ it by using its name followed by parentheses. You can provide arguments
(input values) inside the parentheses to customize the function’s behavior.
[ ]: greet("Alice")
# Output: Hello, Alice!
greet("Bob")
# Output: Hello, Bob!
Return Values
Functions can return values using the ‘return’ statement. This allows them to provide output to the caller.
sum_result = add(5, 3)
print("Sum:", sum_result)
Default Parameters
Functions can have default parameter values. If an argument is not provided for a parameter with a default
value, the default value will be used.
square = power(4)
print("Square:", square)
cube = power(3, 3)
print("Cube:", cube)
Scope of Variables
Variables declared inside a function have ‘local’ scope, meaning they are only accessible within the function.
Variables declared outside functions have ‘global’ scope, and they can be accessed within functions.
def demonstrate_scope():
6
local_var = "I am local"
print(global_var) # Accessing a global variable within the function
print(local_var) # Accessing a local variable within the function
demonstrate_scope()
In Summary, functions are essential for writing organized, reusable, and modular code in Python. They
encapsulate code blocks, accept inputs, return outputs, and help manage the scope of variables. With func-
tions, you can break complex tasks into smaller parts, making code more understandable and maintainable.
Using functions is a key skill for efficient and effective programming in Python.
The calculate_average function below is designed to compute the average value of a given list of numeric
values. Averaging is a common mathematical operation that provides insight into the central tendency of
a dataset. By summing up all the values in the list and dividing by the count of values, the function yields
the average.
The function takes a single parameter, ‘numbers’, which is expected to be a list containing numeric ele-
ments. It then calculates the total sum of these numeric elements and determines the count of items in the
list. Using these values, the function computes the average value.
It’s important to note that if the provided list is empty, meaning it contains no numeric elements, the
function returns 0 as the average since there are no values to average.
The calculate_average function serves as a handy tool for various applications, such as analyzing data,
generating summary statistics, and making comparisons based on central tendencies. Its simple yet funda-
mental functionality makes it a valuable addition to data manipulation tasks.
Parameters:
numbers (list): A list of numeric values.
Returns:
float: The calculated average value. If the list is empty, returns 0.
"""
total = sum(numbers)
count = len(numbers)
if count > 0:
return total / count
7
else:
return 0
[ ]: flavanoids = df['flavanoids']
flav_threshold = 1.5
wines_above_threshold = []
for i in range(len(flavanoids)):
if flavanoids[i] > flav_threshold: # Corrected comparison
wines_above_threshold.append(i)
print(f"Number of wines with flavanoids above {flav_threshold}:
,→{len(wines_above_threshold)}")
While loop to find the wine with the highest alcohol content
[ ]: highest_alcohol_index = 0
highest_alcohol = df['alcohol'][highest_alcohol_index]
i = 1
while i < len(df):
if df['alcohol'][i] > highest_alcohol:
highest_alcohol = df['alcohol'][i]
highest_alcohol_index = i
i += 1
print(f"Highest alcohol content: {highest_alcohol:.2f}% for wine at index
,→{highest_alcohol_index}")
[ ]: subset_size = 5
print("\nSubset of wine data:")
for i in range(subset_size):
print(f"Wine {i + 1}: Alcohol {df['alcohol'][i]:.2f}%,"
f" Flavanoids {df['flavanoids'][i]:.2f},"
f" Proline {df['proline'][i]:.2f}")