In Python, branching refers to the ability to control the flow of your program based on certain conditions. This allows your code to make decisions and execute different blocks of code depending on the outcome of those conditions.
There are three main types of branching statements in Python:
1. if
statement:
The if
statement allows you to execute a block of code only if a certain condition is True. The basic syntax is:
if condition:
# code to execute if condition is True
Here's an example:
age = 25
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
2. if...elif...else
statement:
This allows you to check multiple conditions and execute different code blocks for each condition. The elif
branches are checked sequentially until one of them is True. If none are True, the else
block is executed (optional).
score = 85
if score >= 90:
print("Excellent!")
elif score >= 80:
print("Very good!")
elif score >= 70:
print("Good job!")
else:
print("Keep practicing!")
3. for
and while
loops:
These are not technically branching statements, but they can be used to achieve similar decision-making logic.
for
loop: Iterates over a sequence of items, executing a block of code for each item.while
loop: Continues to execute a block of code as long as a condition is True.
Here's an example of a for
loop used for conditional execution:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
if fruit == "banana":
print("I love bananas!")
else:
print(f"I like {fruit}.")
More Examples of Branching in Python:
Here are some additional examples to solidify your understanding of branching in Python:
1. Nested if
Statements:
temperature = 20
if temperature > 30:
print("It's hot! Wear sunscreen and stay hydrated.")
elif temperature > 20:
print("It's pleasant. Enjoy the outdoors!")
else:
print("It's cold. Dress warmly and stay cozy.")
# Nested `if` can be used for more complex decision-making:
if grade >= 90:
print("Excellent work! You earned an A.")
if grade == 100:
print("Perfect score! Outstanding achievement.")
elif grade >= 80:
print("Great job! You earned a B.")
else:
print("Keep practicing and improving.")
2. if
with Comparisons and Operators:
password = "secret123"
user_input = input("Enter your password: ")
if password == user_input:
print("Welcome back!")
elif len(user_input) < 8:
print("Password is too short. It must be at least 8 characters.")
else:
print("Incorrect password. Please try again.")
# Combine comparisons with operators:
if age >= 18 and is_verified:
print("You are eligible to vote.")
3. Looping with if
for Conditional Execution:
# Check if a number is even or odd
number = 13
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
# Loop through elements and apply condition:
for item in shopping_list:
if item in stock:
print(f"Adding {item} to your cart.")
else:
print(f"{item} is out of stock.")
4. while
Loop with break
for Conditional Termination:
# Guessing game:
number = 42
guess = 0
while guess != number:
guess = int(input("Guess a number between 1 and 50: "))
if guess > number:
print("Your guess is too high.")
elif guess < number:
print("Your guess is too low.")
else:
print("Congratulations, you guessed it right!")
break # Exit the loop if guess is correct
# Using `break` in a loop can exit based on a condition
Remember: Choose the right branching structure (if-else, elif, for, while) based on your specific problem and desired behavior. Experiment with different examples to solidify your understanding and gain confidence in using them effectively in your Python projects.
- Indentation is crucial in Python. The code blocks after
if
,elif
, andelse
must be indented at the same level. - Use logical operators like
and
,or
, andnot
to combine conditions. - Use comments to explain your logic and improve code readability.
By effectively using branching statements, you can write more flexible and responsive Python programs that adapt to different situations.
Comments
Post a Comment