Day 5: Understanding branching

Amy Sidra
2 min readJul 2, 2024

--

Photo by Roman Synkevych on Unsplash

In programming, branching allows us to make decisions based on certain conditions. It helps us control the flow of our programs by executing different sets of instructions based on specific criteria. In Python, branching is implemented using the if, elif, and else statements.

The if statement means the code below it will be executed if the condition is met.

The else statement means the code below it will be executed if the if condition is not met.

elif is short for else if.

We will use the file from the fourth day and implement if, else, and elif.

In this scenario, John is asked by his mother to buy sugar. If the market is open, John will buy sugar. If it’s closed, John will return home immediately. If the market is open and there is milk, John will buy milk. If there is no milk, John will buy eggs, then buy sugar, and return home. here is the code:

print('hello world')

market_is_open = True # market is open
there_is_milk = True # there is a milk
there_is_egg = True # there is an egg

print('Mother said: John, buy some sugar at the market')
print('John goes to the market')

if market_is_open: # check if market is open
print('market is open')
if there_is_milk: # check if there is a milk
print('there is a milk')
print('John buys a milk')
elif there_is_egg: # if there is no milk then check if there is an egg
print('there is no milk')
print('John buys an egg')
print('John buys sugar')
print('John returns home')
else: # market is closed
print('market is close')
print('John returns home')

The code after # is not executed because it is considered a comment, serving only as an explanation.

press run and here is the result

if we change value market_is_open to False the result wil be change too

you can try with another value

happy coding!

Anyone Can Master Python in Just 7 Days

--

--