Python - Conditional Statements
In Python, values are considered either truthy or falsy when used in conditional statements. Truthy values are treated as True, while falsy values are treated as False.
Here's an example program illustrating truthy and falsy values:
# Example program
# Truthy values
if 1:
print("1 is truthy")
if "Hello":
print("Hello is truthy")
if [1, 2, 3]:
print("List is truthy")
# Falsy values
if 0:
print("0 is falsy")
else:
print("0 is falsy")
if "":
print("Empty string is falsy")
else:
print("Empty string is falsy")
if []:
print("Empty list is falsy")
else:
print("Empty list is falsy")
1 is truthy Hello is truthy List is truthy 0 is falsy Empty string is falsy Empty list is falsy
In this example:
-
Values like
1,'Hello', and[1, 2, 3]are truthy, and the correspondingifstatements print messages indicating truthiness. -
Values like
0,''(empty string), and[](empty list) are falsy, and the correspondingelsestatements print messages indicating falsiness.
Understanding truthy and falsy values is essential for writing effective conditional statements in Python.
try, except, else, and finally blocks in Python?
In Python, exception handling is done using the try, except, else, and finally blocks. The try block contains the code that may raise an exception, and the except block contains the code to handle the exception.
Here's an example program illustrating the usage of these blocks:
# Example program
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero is not allowed")
else:
print(f"Result: {result}")
finally:
print("This block always executes")
# Example usage
divide_numbers(10, 2)
divide_numbers(5, 0)
Result: 5.0 Error: Division by zero is not allowed This block always executes
In this example:
-
The
divide_numbersfunction attempts to divide two numbers. If the division is successful, theelseblock is executed and prints the result. If aZeroDivisionErroroccurs, theexceptblock is executed, handling the exception. -
The
finallyblock always executes, regardless of whether an exception occurred or not.
This structure allows you to gracefully handle exceptions and ensure that certain code (in the finally block) runs regardless of whether an exception occurred or not.
in and not in operators in Python conditional statements.
The in and not in operators in Python are used to check whether a value is present in a sequence (such as a string, list, or tuple) or not.
Here's an example program illustrating the usage of these operators:
# Example program
# Using 'in' operator
fruits = ['apple', 'orange', 'banana']
if 'apple' in fruits:
print("Apple is present in the list")
else:
print("Apple is not present in the list")
# Using 'not in' operator
colors = ('red', 'green', 'blue')
if 'yellow' not in colors:
print("Yellow is not present in the tuple")
else:
print("Yellow is present in the tuple")
Apple is present in the list Yellow is not present in the tuple
In this example:
-
The
inoperator is used to check if 'apple' is present in thefruitslist. -
The
not inoperator is used to check if 'yellow' is not present in thecolorstuple.
These operators are useful for conditional statements where you want to test the membership of a value in a sequence or its absence.
In Python, the break and continue statements are used within loop structures to alter the flow of the loop based on certain conditions.
Here's an example program illustrating the use of break and continue statements within a while loop:
# Example program
# Using 'break' and 'continue' in a while loop
i = 0
while i < 5:
i += 1
if i == 3:
print("Skipping iteration for i =", i)
continue # Skip the rest of the loop body and move to the next iteration
print("Inside the loop for i =", i)
if i == 4:
print("Breaking out of the loop for i =", i)
break # Exit the loop when i is 4
Inside the loop for i = 1 Inside the loop for i = 2 Skipping iteration for i = 3 Inside the loop for i = 4 Breaking out of the loop for i = 4
In this example:
-
The
continuestatement is used to skip the rest of the loop body wheniis equal to 3. -
The
breakstatement is used to exit the loop wheniis equal to 4.
These statements provide flexibility in controlling the execution of loops based on certain conditions, making the code more efficient and readable.