Python If...Else: Making Decisions in Your Code

Learn how to control your Python program's flow with If, Elif, and Else statements. A beginner-friendly guide to writing smarter, decision-making code. Enroll at CoderCrafter!

Python If...Else: Making Decisions in Your Code
How Your Python Code Can Make Smart Decisions: A Guide to If...Else
Ever watched a movie where the hero is at a crossroads? One path leads to safety, the other to adventure. The story changes based on their choice. Well, what if I told you your Python code can make these same dramatic decisions?
It can’t choose between a dragon or a dungeon, but it can decide whether to send a user a "Welcome!" message or a "Please log in" prompt. It can calculate a discount, verify a password, or recommend a movie—all based on simple conditions.
This magic is performed by the humble if
, elif
, and else
statements. They are the decision-makers of your code, and understanding them is a fundamental step in your software development journey. Let's break them down, not like a robotic textbook, but like a friend explaining it over coffee.
The Basic "If": Your First Crossroad
Think of if
as a bouncer at an exclusive club. It checks a condition (is the person on the list?) and only lets the code inside execute if the condition is True
.
python
age = 20
if age >= 18:
print("You are eligible to vote!")
# Output: You are eligible to vote!
In this case, the bouncer (if
) checks if age
is 18 or more. Since it is (True
), the print statement is executed. If we changed age
to 16, the condition would be False
, and nothing would happen. The code would just walk on by.
Adding an "Else": The Plan B
But what if the person isn't on the list? You don't just want them to vanish into thin air. You want to tell them, "Sorry, not tonight." This is where else
comes in.
python
age = 16
if age >= 18:
print("You are eligible to vote!")
else:
print("Sorry, you are too young to vote.")
# Output: Sorry, you are too young to vote.
The else
statement is a catch-all. It doesn't ask any questions; it just executes its block of code whenever the if
condition turns out to be False
. It’s your program's Plan B.
The Middle Ground: "Elif" for More Choices
Life is rarely a simple yes-or-no choice. Often, there are multiple paths. What if you have a special discount for students and seniors? You need more than one condition to check.
Enter elif
(short for "else if"). It allows you to check multiple conditions in a sequence.
python
age = 70
if age < 18:
print("You pay the child price.")
elif age >= 65:
print("You qualify for the senior discount!")
else:
print("Please pay the standard adult price.")
# Output: You qualify for the senior discount!
The code checks each condition in order:
Is
age
less than 18? No. Move on.Else, if
age
is 65 or more? Yes! Print the senior message and stop checking.The
else
is ignored because one of the conditions above was already met.
You can chain as many elif
statements as you need to handle complex decision trees.
Why This Matters in the Real World
This isn't just academic theory. Every piece of software you use is brimming with if
statements:
Login Systems:
if password == stored_password: grant_access()
E-commerce:
if cart_total > 100: apply_free_shipping()
Social Media:
if user != current_user: show_follow_button()
Mastering conditional logic is like learning the grammar of a language. It's what allows you to move from writing simple scripts to building intelligent, interactive applications.
Ready to write the next chapter of your story? Visit us at codercrafter.in to explore our courses and enroll today!
5 Python Dictionary Exercises to Go From Beginner to Confident
So, you’ve learned about Python dictionaries. You know they’re those cool collections of key-value pairs, wrapped in curly braces {}
. You can get values with keys, maybe add a new item or two.
But then you sit down to write a program, and your mind goes blank. How do you actually use this thing?
Sound familiar? Don't worry, it happens to everyone. The gap between understanding a concept and using it fluently is bridged by one thing: practice.
That’s why we’ve put together these five practical exercises. Don't just read them—open your code editor and try to solve them yourself first! The struggle is where the learning happens.
Exercise 1: The Merged Menu
You're combining two restaurants' menus. Write a function that takes two dictionaries (menu1
and menu2
) and merges them into one. If a dish appears on both menus, keep the one from menu2
.
Your Goal:
python
menu1 = {'pizza': 10, 'pasta': 8}
menu2 = {'pizza': 12, 'salad': 5}
merged_menu = merge_menus(menu1, menu2)
print(merged_menu)
# Should output: {'pizza': 12, 'pasta': 8, 'salad': 5}
Stuck? Here's a solution:
python
def merge_menus(menu1, menu2):
merged = menu1.copy() # Start with a copy of the first menu
merged.update(menu2) # Update it with the second menu, overwriting any duplicates
return merged
# A more beginner-friendly solution:
def merge_menus_simple(menu1, menu2):
merged = {}
for item, price in menu1.items():
merged[item] = price
for item, price in menu2.items():
merged[item] = price # This automatically overwrites the price if the key exists
return merged
Exercise 2: Word Counter
This is a classic! Write a function that counts how many times each word appears in a string. Hint: You'll need to .split()
the string and use a dictionary to keep track of the counts.
Your Goal:
python
text = "apple banana orange apple apple orange"
result = count_words(text)
print(result)
# Should output: {'apple': 3, 'banana': 1, 'orange': 2}
Stuck? Here's a solution:
python
def count_words(text):
word_list = text.split()
count_dict = {}
for word in word_list:
if word in count_dict:
count_dict[word] += 1
else:
count_dict[word] = 1
return count_dict
# The elegant way using .get():
def count_words_elegant(text):
word_list = text.split()
count_dict = {}
for word in word_list:
count_dict[word] = count_dict.get(word, 0) + 1
return count_dict
Exercise 3: The Inverted Dictionary
Create a function that inverts a dictionary. The keys become the values and the values become the keys. Warning: What if the original values aren't unique?
Your Goal:
python
original_dict = {'a': 1, 'b': 2, 'c': 3}
inverted = invert_dict(original_dict)
print(inverted)
# Should output: {1: 'a', 2: 'b', 3: 'c'}
Stuck? Here's a solution:
python
def invert_dict(original):
inverted = {}
for key, value in original.items():
inverted[value] = key # This works for unique values
return inverted
# For non-unique values, we need to store lists:
def invert_dict_safe(original):
inverted = {}
for key, value in original.items():
if value not in inverted:
inverted[value] = [key] # Create a new list if the value is new
else:
inverted[value].append(key) # Append to the existing list
return inverted
Exercise 4: Find the Max Min
Write a function that finds the key with the maximum value and the key with the minimum value in a dictionary.
Your Goal:
python
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 95}
max_key, min_key = find_max_min(student_grades)
print(f"Highest scorer: {max_key}, Lowest scorer: {min_key}")
# Should output: Highest scorer: Diana, Lowest scorer: Charlie
Stuck? Here's a solution:
python
def find_max_min(grades):
max_key = max(grades, key=grades.get) # The key arg tells max to look at the values
min_key = min(grades, key=grades.get)
return max_key, min_key
# The manual way (great for understanding):
def find_max_min_manual(grades):
all_grades = list(grades.values())
all_names = list(grades.keys())
max_index = all_grades.index(max(all_grades))
min_index = all_grades.index(min(all_grades))
return all_names[max_index], all_names[min_index]
Exercise 5: Dictionary Filter
Create a function that filters a dictionary based on a value condition. Return a new dictionary with only the key-value pairs where the value is greater than a specified threshold.
Your Goal:
python
product_prices = {'laptop': 1200, 'mouse': 25, 'keyboard': 80, 'monitor': 300}
filtered = filter_dict(product_prices, 100)
print(filtered)
# Should output: {'laptop': 1200, 'monitor': 300}
Stuck? Here's a solution:
python
def filter_dict(products, threshold):
filtered = {}
for product, price in products.items():
if price > threshold:
filtered[product] = price
return filtered
# The concise way with dictionary comprehension (Pythonic!):
def filter_dict_pythonic(products, threshold):
return {k: v for k, v in products.items() if v > threshold}
At CoderCrafter, our Full Stack Development and MERN Stack Courses are designed to take you from core concepts (just like dictionaries!) to deploying your own professional projects. You'll not only learn the syntax but also the problem-solving mindset of a software developer.
Ready to turn practice into mastery? Visit codercrafter.in to explore our courses and enroll today!