0% found this document useful (0 votes)
22 views

Python Control Structures Unexecuted

The document discusses different types of control structures in Python including sequential execution, conditional execution with if/else statements, repetitive execution with for and while loops. It provides examples of using if/else, elif, nested if statements, for loops over lists and ranges, nested loops, and iterating over dictionaries. The key control structures covered are if statements, for loops, and while loops.

Uploaded by

bm.nikhilesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python Control Structures Unexecuted

The document discusses different types of control structures in Python including sequential execution, conditional execution with if/else statements, repetitive execution with for and while loops. It provides examples of using if/else, elif, nested if statements, for loops over lists and ranges, nested loops, and iterating over dictionaries. The key control structures covered are if statements, for loops, and while loops.

Uploaded by

bm.nikhilesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Introduction to Control Structures in Python

by: Leon Shpaner


Control structures are fundamental components of programming languages that enable developers to con-
trol the flow of their programs. They determine how instructions are executed based on specified conditions
or rules. In Python, control structures allow you to make decisions, repeat actions, and create organized,
responsive code.
Python provides three primary types of control structures:
Sequential Execution
This is the default mode of execution where statements are executed in the order they appear. It’s the basic
foundation of any program.
Conditional Execution (if statements):
Python allows you to make decisions in your code using conditional statements. With if statements, you
can execute different blocks of code based on whether specific conditions are met.
Repetitive Execution (loops):
Loops are used to repeat a block of code multiple times. Python offers two types of loops: for loops and
while loops. For loops iterate over a sequence (like a list), while loops repeat as long as a certain condition
is true.
Understanding and effectively utilizing these control structures is essential for creating flexible, dynamic,
and efficient programs. They empower you to handle diverse scenarios, respond to user input, and auto-
mate repetitive tasks, making your code more robust and user-friendly. As you dive into this topic, you’ll
gain the ability to create more sophisticated and interactive Python programs.

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.

Example: Checking Age for Voting Eligibility

[ ]: age = 18

if age >= 18:


print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

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

if age >= 18:


if income > 30000:
print("You are eligible for a loan.")
else:
print("Your income is insufficient for a loan.")
else:
print("You are not of legal age for a loan.")

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.

[ ]: # Example of a for loop:


print("Example of a for loop:")

# The 'range()' function generates a sequence of numbers from 0 up to (but not


,→including) the specified number.

# In this case, 'range(5)' generates numbers 0, 1, 2, 3, 4.


for i in range(5):
# The code within the loop is indented. It will be executed for each value of 'i' in
,→the sequence.

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:

[ ]: fruits = ["apple", "banana", "cherry"] # list of fruits


print("\nLooping over a list:")
for fruit in fruits:
print(fruit)
# This loop iterates over each element (fruit) in the 'fruits' list.

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.

Example of Nested Loops


Suppose we have two ranges: an outer loop from 0 to 2, and an inner loop from 0 to 1. The outer loop
iterates over the values 0, 1, and 2. For each of these outer loop values, the inner loop iterates over the
values 0 and 1.

[ ]: print("\nExample of nested loops:")


print()
# Here, we have 2 ranges:
# outer loop iterates 0 to 2,
for i in range(3):
# and inner loop iterates 0 to 1.

3
for j in range(2):
print(f"i: {i}, j: {j}")
# This loop structure will print all combinations of i and j.

Iterating through Dictionaries


Dictionaries consist of key-value pairs. We can loop through the keys, values, or both. Iterating through
dictionaries allows you to access and process these pairs using for loops.
Suppose we have a dictionary representing student grades:

[ ]: student_grades = {"Alice": 90, "Bob": 85, "Carol": 78}

[ ]: print("Looping through dictionary keys:")


for student in student_grades:
print(f"Student: {student}")
# This loop iterates through the dictionary keys (student names).

[ ]: # Looping through Keys and Values (Items):


print("\nLooping through dictionary items:")
for student, grade in student_grades.items():
print(f"Student: {student}, Grade: {grade}")

The ‘keys()’ method returns a view of dictionary keys.


The ‘values()’ method returns a view of dictionary values.
The ‘items()’ method returns a view of dictionary key-value pairs.
It’s important to note that the order of iteration may not be the same as the order of insertion since dictio-
naries in Python 3.7 and later maintain the insertion order.

Practical Example: Counting Letter Frequency


Here’s an example of how you can use dictionaries and for loops to count the frequency of letters in a
string:

[ ]: text = "hello world"


letter_frequency = {}

[ ]: for char in text:


if char.isalpha():
# Convert to lowercase to treat uppercase and lowercase letters equally
char = char.lower()
if char in letter_frequency:
letter_frequency[char] += 1
else:
letter_frequency[char] = 1
print("\nLetter Frequency:")
for letter, frequency in letter_frequency.items():
print(f"Letter: {letter}, Frequency: {frequency}")

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:")

fruits = ["apple", "banana", "cherry"]

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.

[ ]: for index, fruit in enumerate(fruits):


print(f"Index: {index}, Fruit: {fruit}")
# This loop iterates through the fruits list, providing both index and value.

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.

Example: Counting Down


Let’s start with a simple example of a while loop that counts down from a given number:

[ ]: print("\nExample of a while loop:")


countdown = 5
while countdown > 0:
print(countdown)
countdown -= 1

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.

[ ]: def add(a, b):


"""A function to add two numbers and return the result."""
result = a + b
return result

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.

[ ]: def power(base, exponent=2):


"""A function to calculate the power of a number with an optional exponent."""
result = base ** exponent
return result

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.

[ ]: global_var = "I am global"

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.

Comprehensive Review - Using Wine Recognition Dataset

[ ]: # Import necessary libraries


import numpy as np
import pandas as pd
from sklearn.datasets import load_wine

[ ]: # Load the diabetes dataset


wine = load_wine()
df = pd.DataFrame(wine.data, columns=wine.feature_names)

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.

[ ]: # Function to calculate average value of a list


def calculate_average(numbers):
"""
Calculate the average value of a list of numbers.

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

Calculate the average alcohol content of wine

[ ]: alcohol_column = df['alcohol'] # Corrected index for age column


average_alcohol = calculate_average(alcohol_column)
print(f"Average age of patients: {average_alcohol:.2f}")

Loop to find wines with flavanoids above a certain threshold

[ ]: 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}")

Decision-making using if statements

[ ]: if average_alcohol > 10:


print("The average alcohol of wines is higher than 10.")
else:
print("The average alcohol of wines is not higher than 10.")

Display a subset of wine data

[ ]: 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}")

You might also like