Python Module2
Python Module2
Boolean expressions in Python are expressions that evaluate to either True or False. They
are fundamental to decision-making and control flow in Python programs.
Boolean Values:
Comparison Operators:
Equal to: ==
Not equal to: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=
Example:
Python
x = 10
y = 5
Logical Operators:
Example:
Python
a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False
Boolean expressions are crucial for controlling the flow of execution in Python programs.
They are commonly used in if, else, and while statements:
Python
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
Key Points:
A simple if statement in Python allows you to execute a block of code only if a certain
condition is true.
Basic Syntax:
Python
if condition:
# Code to be executed if the condition is True
Example:
Python
x = 10
if x > 5:
print("x is greater than 5")
Explanation:
An if-else statement allows you to execute different code blocks based on whether a
condition is True or False.
Basic Syntax:
Python
if condition:
# Code to be executed if the condition is True
else:
# Code to be executed if the condition is False
Example:
Python
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Explanation:
Python
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
else:
print("The number is negative or zero.")
Key Points:
Indentation: The code within the if and else blocks must be indented.
Condition: The condition must be a Boolean expression.
Code Execution: The code within the if block is executed if the condition is True;
otherwise, the code within the else block is executed.
You can nest if-else statements to create more complex decision-making structures:
Python
x = 10
y = 5
if x > y:
print("x is greater than y")
else:
if x == y:
print("x is equal to y")
else:
print("x is less than y")
The if-elif-else statement is a versatile control flow statement that allows you to execute
different code blocks based on multiple conditions. It's a more flexible alternative to nested
if-else statements.
Basic Syntax:
Python
if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition1 is False and condition2 is True
else:
# Code to be executed if all conditions
are False
Explanation:
Example:
Python
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number == 0:
print("The number is zero.")
else:
print("The number is negative.")
Key Points:
Indentation: The code within each if, elif, and else block must be indented.
Conditions: Each condition is a Boolean expression.
Execution: The first condition that evaluates to True will execute its corresponding
code block.
else Block: The else block is optional and is executed only if none of the previous
conditions are True.
Compound Boolean expressions are created by combining simple Boolean expressions using
logical operators. These operators allow you to create more complex conditions for decision-
making.
Logical Operators:
Example:
Python
age = 25
has_license = True
# Using `and`
if age >= 18 and has_license:
print("You are eligible to drive.")
else:
print("You are not eligible to drive.")
# Using `or`
if age < 18 or not has_license:
print("You cannot drive.")
else:
print("You can drive.")
Complex Conditions:
Python
x = 10
y = 5
z = 20
When you need to make decisions based on multiple conditions, the if-elif-else ladder is
a powerful tool in Python. It allows you to test multiple conditions sequentially and execute
different code blocks based on the first condition that evaluates to True.
Basic Syntax:
Python
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False and condition2 is True
elif condition3:
# Code to execute if condition1 and condition2 are False,
but condition3 is True
else:
# Code to execute if none of the above conditions are True
Example:
Python
grade = int(input("Enter your grade: "))
How it Works:
1. Condition 1: The first if statement checks if the grade is greater than or equal to 90.
If it is, the message "Excellent!" is printed, and the rest of the conditions are skipped.
2. Condition 2: If the first condition is False, the elif statement checks if the grade is
greater than or equal to 80. If it is, the message "Very Good!" is printed, and so on.
3. Default Condition: If none of the previous conditions are True, the else block is
executed, and the message "Below Average" is printed.
Key Points:
Loops in Python
Loops are used to execute a block of code repeatedly. Python offers two primary types of
loops: for loops and while loops.
1. For Loops
A for loop is used to iterate over a sequence of items, such as a list, tuple, string, or range of
numbers.
Basic Syntax:
Python
for item in sequence:
# Code to be executed for each item
Example:
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Python
for i in range(5):
print(i)
2. While Loops
A while loop repeatedly executes a block of code as long as a given condition is true.
Basic Syntax:
Python
while condition:
# Code to be executed while the condition is True
Example:
Python
count = 0
while count < 5:
print(count)
count += 1
A nested loop is a loop within another loop. This structure is often used to iterate over multi-
dimensional data structures or to perform repetitive tasks that require multiple levels of
iteration.
Basic Structure:
Python
for outer_loop_variable in outer_sequence:
for inner_loop_variable in inner_sequence:
# Code to be executed for each iteration of the inner loop
Python
for i in range(1, 10):
for j in range(1, 10):
print(i * j, end="\t")
print()
Explanation:
1. Break Statement
The break statement immediately terminates the loop it's inside, regardless of whether the
loop's condition is still True.
Python
for i in range(10):
if i == 5:
break
print(i)
In this example, the loop will iterate from 0 to 4, and then the break statement will be
executed, stopping the loop.
2. Continue Statement
The continue statement skips the current iteration of the loop and moves on to the next
iteration.
Python
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
In this example, the loop will print only odd numbers from 1 to 9, as the continue statement
skips even numbers.
Key Points:
break and continue are used to control the flow of for and while loops.
break immediately exits the loop.
continue skips the current iteration and moves to the next.
Use these statements judiciously to avoid unintended consequences.
Infinite loop
An infinite loop is a loop that continues to execute indefinitely without any termination
condition. In Python, infinite loops can be created using both while and for loops.
While Loop:
Python
while True:
print("This loop will run forever.")
In this example, the condition True is always true, so the loop will continue indefinitely.
For Loop:
Python
for i in range(float('inf')):
print(i)
While infinite loops can be useful in certain scenarios, it's important to have a mechanism to
break out of them. This can be done using the break statement.
Python
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
print("You entered:", user_input)
In this example, the loop continues until the user enters "quit".
Caution:
Be careful when using infinite loops. If not controlled properly, they can lead to program
crashes or resource exhaustion. Always ensure that there's a clear termination condition to
avoid unintended consequences.