Python Control Statements: Master Program Flow for AI
Learn Python control statements like if, elif, and else to manage program flow, essential for building robust AI and machine learning applications.
Python Control Statements
This document provides a comprehensive overview of control statements in Python, essential for managing the flow of execution within your programs.
2.1 Python if
, elif
, and else
Statements
Conditional statements allow you to execute different blocks of code based on whether certain conditions are true or false.
The if
Statement
The if
statement executes a block of code only if a specified condition evaluates to True
.
if condition:
# Code to execute if condition is True
statement1
statement2
Example:
temperature = 25
if temperature > 30:
print("It's a hot day!")
The if-else
Statement
The if-else
statement executes one block of code if the condition is True
and another block if the condition is False
.
if condition:
# Code to execute if condition is True
statement_if_true
else:
# Code to execute if condition is False
statement_if_false
Example:
score = 75
if score >= 60:
print("You passed!")
else:
print("You failed.")
The if-elif-else
Statement
The if-elif-else
statement allows you to check multiple conditions in sequence. The first condition that evaluates to True
will have its corresponding code block executed. If none of the if
or elif
conditions are True
, the else
block (if present) will be executed.
if condition1:
# Code to execute if condition1 is True
statement1
elif condition2:
# Code to execute if condition1 is False and condition2 is True
statement2
elif condition3:
# Code to execute if condition1 and condition2 are False, and condition3 is True
statement3
else:
# Code to execute if all preceding conditions are False
statement_else
Example:
grade = 'B'
if grade == 'A':
print("Excellent!")
elif grade == 'B':
print("Very Good!")
elif grade == 'C':
print("Good.")
else:
print("Needs Improvement.")
2.2 Python Loops
Loops are used to execute a block of code repeatedly. Python offers two primary types of loops: for
loops and while
loops.
2.3 Python for
Loop
The for
loop iterates over a sequence (like a list, tuple, string, or range) and executes a block of code for each item in the sequence.
for item in sequence:
# Code to execute for each item
statement1
statement2
Example:
Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Iterating using range()
:
# Prints numbers from 0 up to (but not including) 5
for i in range(5):
print(i)
# Prints numbers from 2 up to (but not including) 7
for i in range(2, 7):
print(i)
# Prints numbers from 0 up to 10, with a step of 2
for i in range(0, 10, 2):
print(i)
2.4 Python while
Loop
The while
loop executes a block of code as long as a specified condition remains True
. It's crucial to ensure that the condition eventually becomes False
to avoid infinite loops.
while condition:
# Code to execute as long as condition is True
statement1
statement2
Example:
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # Increment count to eventually terminate the loop
2.5 Python continue
Statement
The continue
statement is used inside loops. When encountered, it skips the rest of the current iteration and moves to the next iteration of the loop.
Example:
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print(i)
Output:
1
3
5
7
9
2.6 Python break
Statement
The break
statement is also used inside loops. When encountered, it immediately terminates the loop, and the program execution continues with the statement immediately following the loop.
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num == 6:
break # Stop the loop when the number 6 is found
print(num)
Output:
1
2
3
4
5
2.7 Python pass
Statement
The pass
statement is a null operation. It does nothing. It's used as a placeholder where a statement is syntactically required but you don't want any code to execute. This is often useful during program development when you plan to implement functionality later.
Example:
Using pass
in an if
statement:
x = 10
if x > 5:
pass # No action needed if x is greater than 5
else:
print("x is not greater than 5")
Using pass
in a function definition (to be implemented later):
def my_function():
pass # Function body will be added later
Using pass
in a loop:
for i in range(5):
pass # Do nothing in each iteration
Python Boolean (bool): Truth Values in AI & ML
Explore Python's bool data type, its truth values (True/False), and how it functions as an int (1/0). Essential for AI & ML logic.
Python If Else: Conditional Logic for AI & ML
Master Python's 'if', 'if-else', and 'if-elif-else' statements for building smart AI and ML applications. Control program flow with Python conditionals.