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

Python Module2

Uploaded by

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

Python Module2

Uploaded by

alakanandha826
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Control Statements in Python

Boolean Expressions in Python

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:

 True: Represents a true value.


 False: Represents a false value.

Comparison Operators:

These operators compare values and return a Boolean result:

 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

print(x == y) # Output: False


print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False

Logical Operators:

These operators combine Boolean values to form more complex expressions:

 and: Returns True if both operands are True.


 or: Returns True if at least one operand is True.
 not: Inverts the truth value of an operand.

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 in Control Flow:

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:

 Boolean expressions are essential for decision-making and control flow.


 Comparison operators compare values and return Boolean results.
 Logical operators combine Boolean values to form more complex expressions.
 Boolean expressions are used in if, else, and while statements to control the
execution of code.

Simple If Statement in Python

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:

1. Condition: x > 5 is a Boolean expression that evaluates to True or False.


2. Code Block: If the condition is True, the code inside the indented block will be
executed. In this case, the message "x is greater than 5" will be printed to the console.
If-else Statement in Python

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:

1. Condition: x > 5 is evaluated.


2. If True: The code inside the if block is executed.
3. If False: The code inside the else block is executed.

Example with User Input:

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.

Nested if-else Statements:

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

if-elif-else Statement in Python

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:

1. Condition 1: The first if statement checks the condition1.


2. If Condition 1 is True: The code block under the if statement is executed, and the
rest of the elif and else blocks are skipped.
3. If Condition 1 is False: The elif statement is checked.
4. Condition 2: The elif statement checks the condition2.
5. If Condition 2 is True: The code block under the elif statement is executed, and the
else block is skipped.
6. If Condition 2 is False: The else block is executed if it's present.

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 in Python

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:

Python provides three main logical operators:

1. and: Returns True if both operands are True.


2. or: Returns True if at least one operand is True.
3. not: Inverts the truth value of an operand.

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:

You can combine multiple logical operators to create complex conditions:

Python
x = 10
y = 5
z = 20

if (x > y and x < z) or (y > z):


print("Complex condition is True")
else:
print("Complex condition is False")
Key Points:

 Use parentheses to group expressions and control the order of evaluation.


 Remember operator precedence: not has the highest precedence, followed by and,
and then or.
 You can use compound Boolean expressions in if, elif, and while statements to
create sophisticated decision-making logic.
 By mastering compound Boolean expressions, you can write more flexible and
expressive Python code.

Multi-Way Decisions in Python: The if-elif-else Ladder

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

if grade >= 90:


print("Excellent!")
elif grade >= 80:
print("Very Good!")
elif grade >= 70:
print("Good")
elif grade >= 60:
print("Average")
else:
print("Below Average")

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:

 The elif keyword is used to introduce additional conditions.


 The else block is optional and is executed only if none of the previous conditions are
True.
 The conditions are evaluated sequentially, and the first condition that evaluates to
True will trigger its corresponding code block.
 You can have as many elif blocks as needed to check multiple conditions.

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)

Iterating over a Range of Numbers:

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

Nested Loops in Python

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

Example: Printing a Multiplication Table

Python
for i in range(1, 10):
for j in range(1, 10):
print(i * j, end="\t")
print()

Explanation:

1. Outer Loop: Iterates over numbers from 1 to 9.


2. Inner Loop: For each iteration of the outer loop, the inner loop iterates from 1 to 9.
3. Multiplication: Inside the inner loop, the product of i and j is calculated and printed.
4. Newline: After each inner loop completes, a newline character is printed to move to
the next row.

Break and Continue Statements in Python

These statements are used to control the flow of loops in Python.

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)

Here, range(float('inf')) generates an infinite sequence of numbers, causing the loop to


run forever.

Breaking an Infinite Loop:

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.

You might also like