Control Structures
Control structures are the fundamental tools that dictate the flow and logic of your code. They enable you to make decisions, repeat actions, and structure your program effectively. In this unit, we'll explore the various control structures available in Python, including conditional statements (if, else, elif) and loops (for, while). Understanding and mastering these concepts will be crucial for writing efficient and dynamic Python programs.
Logical Operators
Logical operators are used to combine conditions in Python. They help you create more complex expressions based on the truth values of individual conditions.
Python Logical Operators
and
: ReturnsTrue
only if both conditions areTrue
.or
: ReturnsTrue
if at least one condition isTrue
.not
: Reverses the logical value of a condition.
## LOGICAL OPERATORS EXAMPLE ##
a = True
b = False
print(a and b)
print(a or b)
print(not a)
False
True
False
Comparison Operators
Comparison operators are used to compare values in Python. They help you determine the relationship between two expressions.
The result of a comparison is always a Boolean value: either True
or False
.
Common Comparison Operators
- Equal to:
==
- Not equal to:
!=
- Greater than:
>
- Greater than or equal to:
>=
- Less than:
<
- Less than or equal to:
<=
## COMPARISON OPERATORS EXAMPLE ##
age = 18
print(age == 21)
print(age != 21)
print(age > 18)
print(age >= 18)
print(age < 21)
print(age <= 21)
False
True
False
True
True
True
Conditional Statements
Conditional statements are used to control the flow of execution in a Python program. They allow you to make decisions based on certain conditions and execute different code blocks accordingly. By using both Logical and Comparison operators effectively, we can write very complex conditional statements that control the flow of a program however we wish.
if Statement
The if
statement is the most basic conditional statement. It executes a block of code only if a specified
condition is True
.
## IF STATEMENT EXAMPLE ##
age = 18
if age >= 18:
print("You are eligible to vote.")
if-else Statement
The if-else
statement provides an alternative block of code to execute if the specified condition is False
.
## IF-ELSE STATEMENT EXAMPLE ##
weather = "sunny"
if weather == "rainy":
print("Don't forget your umbrella.")
else:
print("Enjoy the sunny day!")
if-elif-else Statement
The if-elif-else
statement allows you to check multiple conditions and execute different code blocks based on
the first condition that is True
.
Note: The else
is not required to use an elif
.
## IF-ELIF-ELSE STATEMENT EXAMPLE ##
grade = 85
if grade >= 90:
print("Excellent!")
elif grade >= 80:
print("Good job!")
else:
print("Needs improvement.")
Nested Conditional Statement
You can also nest conditional statements within each other to create more complex decision-making structures.
## NESTED CONDITIONAL STATEMENT EXAMPLE ##
age = 40
if age >= 18:
if age >=35:
print("You can vote and run for president!")
else:
print("You can vote.")
else:
print("You're too young to vote.")
For Loops
For loops are a control flow statement used to iterate over a sequence of values (e.g., elements in a list, characters in a string, or numbers in a range). They provide a convenient way to repeat a block of code multiple times.
Key Points:
for element in sequence:
# Code executed for each element
-
for element in sequence
: This part specifies the variable (element
) that will hold the current value during each iteration, and the sequence of values to iterate over. -
# Code executed for each element
: This block of code will be executed once for each element in the sequence. -
The
for
loop continues to execute as long as there are elements left in the sequence. -
You can use any valid variable name for the
element
. -
The
range()
function is commonly used to create a sequence of numbers. -
You can use the
break
statement to exit the loop prematurely, and thecontinue
statement to skip the current iteration and proceed to the next one.
## RANGE OF NUMBERS EXAMPLE ##
for num in range(5):
print(num)
## LIST EXAMPLE ##
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
## STRING EXAMPLE ##
for character in "hello":
print(character)
## BREAK & CONTINUE EXAMPLE ##
for num in range(20):
if num==10:
break
elif num%2==0:
continue
print(num)
While Loops
While loops are another control flow statement in Python that allows you to repeatedly execute a block of code as long as a specified
condition remains True
. Unlike for
loops, which iterate over a sequence of values, while
loops
continue to execute until a specific condition becomes False
.
Key Points:
while condition:
# Code executed each iteration
-
while condition
: This part specifies the condition that must beTrue
for the loop to continue executing. -
# Code executed each iteration
: This block of code will be executed repeatedly as long as the condition remainsTrue
. -
The
while
loop continues to execute as long as the specified condition isTrue
. -
It's essential to ensure that the condition will eventually become
False
to avoid infinite loops. -
You can use the
break
statement to exit the loop prematurely, and thecontinue
statement to skip the current iteration and proceed to the next one.
## WHILE LOOP EXAMPLE ##
count = 0
while count < 5:
count += 1
print(count)
## BREAK & CONTINUE EXAMPLE ##
num = 0
while True:
num += 1
if num > 10:
break
elif num%2 == 0:
continue
print(num)
Loop and a Half
A "loop and a half" is a programming construct where a loop's termination condition is checked in the middle of the loop's body, rather than at the beginning or end. This allows for a more flexible loop structure, particularly when you need to perform an action before the first iteration of the loop.
How it works:
-
Infinite Loop: The
while True
loop creates an infinite loop that will continue indefinitely unless explicitly broken. - Pre-Loop Code: The code before the condition check is executed once, before the loop's main body.
-
Condition Check: The
if
condition is evaluated. If the condition is true, thebreak
statement is executed, and the loop terminates. - Loop Body: If the condition is false, the code within the loop body is executed.
- Loop Repetition: The loop then repeats, going back to step 2.
## LOOP AND A HALF EXAMPLE ##
sentinel_value = -1
count = 0
quiz_sum = 0
while True:
# Code to be executed before the loop's condition check
score = int(input("Enter a number (-1 to quit): "))
# Condition to check for loop termination
if score == sentinel_value:
break
# Code to be executed repeatedly
count +=1
quiz_sum += score
print("Quiz Average:",round(quiz_sum/count,2))
The "half" in a "loop and a half" refers to the code that is executed once before the main loop starts. This initial execution is considered the "half" part of the loop. The remaining part of the loop, which is executed repeatedly, is the "full" loop. So, while the term "half" might not be explicitly visible in the Python code, it's conceptually present in the structure of the loop and the execution order of the code.
Random Numbers
Random numbers are numbers that are generated in an unpredictable sequence.
In Python, the easiest way to generate random numbers is by using the built-in
random
library.
Core Functions of Random:
random.random()
: Generates a random floating-point number between 0 and 1 (exclusive).random.randint(a, b)
: Generates a random integer betweena
andb
(inclusive).random.randrange(start, stop[, step])
: Generates a random integer from the range[start, stop)
, optionally skipping steps.random.choice(sequence)
: Returns a random element from a sequence (like a list, tuple, or string).
## RANDOM EXAMPLES ##
import random
random_float = random.random()
print(random_float)
random_int = random.randint(1, 10)
print(random_int)
random_even = random.randrange(2, 10, 2)
print(random_even)
fruits = ["apple", "banana", "cherry"]
random_fruit = random.choice(fruits)
print(random_fruit)