We have been seeing programs which consist of a list of statements, one after another, where the "flow of control" goes from one line to the next, top to bottom, and so on to the end of the list of lines. There are more useful ways of breaking up the "control flow" of a program. Python has several conditional statements that the programmer do things based on conditions in the data.
The first conditional statement is the if statement.
if (something-is-true):
doSomething()Here are a few simple examples.
if (speed > speedLimit) :
driver.getsATicket()
if (x <= -1) :
print("Cannot have negative numbers!")
if (account.balance >= amountRequested) :
subtract(account, amountRequested)
produceCash(amountRequested)
printReceipt(amountRequested)Python also has an else part to the if statement. When the if condition is False, the else part gets run. Here, if the account doesn’t have enough money to fulfill the amountRequested, the else part of the statement gets run, and the customer gets an insufficient funds receipt.
if (account.balance >= amountRequested):
# customer has the money
else:
printReceipt("Sorry, you don't have enough money in your account!")Python can also "nest" if statements, making them very flexible for complicated situations. You can also see here how the elif works.
There can be zero or more elif parts, and the else part is optional.
timeOfDay = "Afternoon"
if (timeOfDay === "Morning"):
print("Time to eat breakfast")
eatCereal()
elif (timeOfDay === "Afternoon"):
print("Time to eat lunch")
haveASandwich()
else:
print("Time to eat dinner")
makeDinner()
eatDinner()
doDishes()Notice how this becomes a 3-way choice, depending on the timeOfDay.
|
Tip
|
Write code to check if a user is old enough to drink.
|
You should use an if statement for your solution!
Finally, make sure to change the value of the age variable in the repl, to output out different results and test that all three options can happen. What do you have to do to make the else clause happen?
userAge = 17
if userAge < 18:
print("Cannot party with us")
elif userAge >= 18:
print("Party over here")
else:
print("I do not recognize your age")If statements are one of the most commonly used statements to express logic in a Python program. It’s important to know them well.