-
Notifications
You must be signed in to change notification settings - Fork 1
Python for Young Students: Conditionals
A conditional is used to run code only if some condition is met. An example using plain english might be this:
If you finish eating your dinner, you can watch some tv.
In the above example, watching tv depends on whether or not you've finished eating dinner. In other words, having eaten dinner is the condition that must be met before you can watch tv. So, if you've finished eating dinner, you can watch TV. Conversely, if you haven't finished eating dinner, you can't watch TV.
If you can use plain english to describe a conditional, you're a third of a way to writing a conditional in using python. But before we do that, we're going to use pseudo code. Pseudo code is a term that describes something that is half english and half code. It's a stepping stone to turning plain english into code.
Let's turn our plain english sentence into pseudo code:
if you finished eating dinner:
you can watch TV
The above pseudo code still reads like a sentence, but it's formatted like code. You can breakdown the pseudo code into the following sections:
- the if keyword
- the boolean expression (In this case you finished eating dinner)
- the colon :
- an indentation
- the (one or more) command(s) (In this case you can watch TV)
Those are the five parts to a python if-statement.
So, we're ready to turn our pseudo code into a real python conditional. Here it is:
if dinner.finished == True:
watchTV()
You can see we've kept some of the same parts from our pseudo code conditional: the if keyword, the colon, and the indentation. But we've completely changed the boolean expression and the command.
We've turned you finished eating dinner into dinner.finished == True
And we've turned you can watch tv into a pretend python function watchTV()
A boolean expression is a statement that is either true or false. Here are some true statements:
- the world is round
- three is greater than two
- Adele is a better singer than Taylor Swift
Here are some false statements:
- the world is flat
- three is less than two
- Adele is not as good a singer as Taylor Swift
Here are some true statements using code:
- 5 == 5
- 3 > 2
- 10 > 5 + 2
Some false statements using code:
- 8 > 18
- 45 == 11
- 25 < 6 * 10
So, if the boolean expression is true, then the indented command block will be run. If it is not true, the indented command block will NOT run.