Decision Making and Operators
Learn how superheroes make critical decisions using conditionals and operators in Python.
Python's Decision Trees: Choosing the Path 🌳
Superheroes often face choices that alter their paths.
Question: How does a hero decide between saving the world or saving a friend?
choice = "friend"
if choice == "world":
print("Save the world!")
elif choice == "friend":
print("Save the friend!")
else:
print("Undecided...")
# Output: Save the friend!
Task
Modify the code to handle the choice of "both" where the hero attempts to save both the world and the friend.
Answer
choice = "both"
if choice == "world":
print("Save the world!")
elif choice == "friend":
print("Save the friend!")
elif choice == "both":
print("Attempting to save both!")
else:
print("Undecided...")
# Output: Attempting to save both!
Which Number Reigns Supreme? 🏰
Engage in a royal comparison to crown the greater number.
knight1 = 5
knight2 = 10
# A duel of numbers
if knight1 > knight2:
print("Knight1 rides to victory!")
elif knight1 == knight2:
print("It's a tie!")
else:
print("Knight2 claims the throne!")
# Output: Knight2 claims the throne!
Question: What if both knights have equal strength?
Answer
If knight1
equals knight2
, the program outputs "It's a tie!"
.
Mirror, Mirror, on the Wall 🪞
Invoke the mirror to reveal if both numbers share the same strength.
strength1 = 10
strength2 = 10
if strength1 > strength2:
print("Strength1 is superior.")
elif strength1 == strength2:
print("Both strengths are equal.")
else:
print("Strength2 surpasses the first.")
# Output: Both strengths are equal.
Ice Cream Stock Checker 🍨
Master conditional statements like a superhero making quick decisions.
Flavor Quest
Task
Determine if a customer's favorite flavor is in stock using efficient code.
available_flavors = ["vanilla", "chocolate", "strawberry"]
favorite = "mint"
result = "We have your flavor!" if favorite in available_flavors else "Sorry, out of stock."
print(result)
# Output: Sorry, out of stock.
Question: How can we handle the situation where the customer is willing to accept any flavor?
Answer
favorite = "any"
if favorite == "any":
print("Here are the available flavors:", available_flavors)
elif favorite in available_flavors:
print("We have your flavor!")
else:
print("Sorry, out of stock.")
Operators in Python: Superpowers 🧮
Operators are like superpowers, enabling heroes to perform actions.
Unary Operators: Solo Performers 🎭
# Negate a boolean value
stealth_mode = True
visible = not stealth_mode
print(visible) # Output: False
Example:
# Flip the sign of a number
speed = -100
reverse_speed = -speed
print(reverse_speed) # Output: 100
Binary Operators: Team Efforts 🤝
# Combine powers
strength = 80
speed = 70
total_power = strength + speed # 150
# Logical operations
has_shield = True
has_armor = False
is_protected = has_shield or has_armor # True
Question: What does the and
operator do in logical operations?
Example:
# Both conditions must be True
can_fly = True
has_cape = True
superhero = can_fly and has_cape
print(superhero) # Output: True
Ternary Operator: Swift Decisions ⚖️
# Quick choice
mission = "dangerous"
action = "Proceed with caution" if mission == "dangerous" else "Proceed normally"
print(action)
# Output: Proceed with caution
Question: Can we use the ternary operator for numeric computations?
Example:
# Assign value based on condition
energy = 100
status = "Full power" if energy > 80 else "Need recharge"
print(status) # Output: Full power
Secret Code Extractor 🕵️♂️
Unveil hidden messages like decoding a villain's plan.
Deciphering Steps
- Locate and extract the message after a special symbol.
- Handle cases where the symbol is missing.
- Clean the code from unwanted characters.
- Use method chaining for efficiency.
# Given message
encrypted = "###@@@SECRET_MESSAGE$$$"
# Extraction
start = encrypted.find("@@@") + 3
end = encrypted.find("$$$")
if start != -1 and end != -1:
secret = encrypted[start:end].strip("#")
print(secret)
# Output: SECRET_MESSAGE
Question: How can we handle multiple occurrences of the special symbol?
Answer
We can use find
with a start index or use split
to handle multiple occurrences.
Conclusion
By understanding conditionals and operators, you've learned how superheroes make critical decisions and perform powerful actions. These concepts are fundamental in controlling the flow of your programs and making them respond dynamically to different situations.