Decision Making in Python

“What have you done?!” she asked you.

Your head went numb. You watched as the phone sank into the water closet. Your head was floating. Her screams rented the entire atmosphere. You know at that moment that you must buy her a new phone.

Your stomach went flat inside of you. You just remembered that you only have $400 in your savings account. What will you do?

Now, you have two options. Your girlfriend’s lost phone is a Huawei, and she likes LG. That means you want to either buy an LG phone or a Huawei phone. However, you only have $400.

That means if Huawei costs more than $400, you will buy her a Huawei phone, or else, you will get her an LG phone.

This is a way you can write your condition:

If the price is less than $400,
     I will buy her a Huawei phone
else
     she will make do with the LG phone.

If you think about this situation well, programmers put the computer in situations like that. We call it the if-else statement, which is used in decision-making.

For Python, you can code a conditional with an if-else statement like this:

if price < 500:
print ("She gets the Huawei phone")
else
    print ("She will make do with the LG")

The computer reads this as “I will check the variable called price and see that the value is less or greater than 500 dollars. Then I will display either of the two sentences.

Do you notice that the first and third lines started at different paces than the other two?

If you watch closely, you will notice that the second and fourth lines started four clear spaces after the beginning of the line. This creates something like a paragraph.

In coding, when a line of code does not start the same way as the line it follows, we say that line is indented. Mostly, pressing the tab key on your keyboard will indent a line. The best and safest way is to press the space bar 4 times.

Just as your English teacher taught you that paragraphing is vital in writing, indentation is essential in Python coding. We will do more with indentation as we move.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials