If...
This time, we will learn how to ask the computer a question.
To ask a question, we use the word if.
if means “if…” in plain English.
Asking the computer a question
First, decide what you want to ask. For example, what if you want to ask: “Is this number greater than 10?”
Type this into PyCharm.
number = 15
if number > 10:
print("It is greater than 10!")
In plain English:
Remember that number is 15
If number is greater than 10:
print "It is greater than 10!"
When you run it, you will see It is greater than 10!.
The magic of indentation
There is one very important rule here:
the blank space before print on the next line.
In Python, this is called indentation. It tells the computer, “Only run this line if the answer to the question is yes.”
If you do not indent, Python will show an error (red underline). PyCharm handles indentation automatically when you press Enter, so do not worry.
So how do we tell Python that the if block is done?
You do not need a special ending word.
Just return to the original indentation (all the way to the left),
and Python understands, “Ah, the question ended here.”
In the code above, once the print line ends and the next line is unindented,
it means it is no longer part of the if.
Answering “no” (else)
If you want to do something else when the answer is no, use else.
number = 5
if number > 10:
print("It is greater than 10!")
else:
print("It is 10 or less!")
That means:
Remember that number is 5
If number is greater than 10:
print "It is greater than 10!"
Otherwise:
print "It is 10 or less!"
More questions (elif)
If you want to ask another question in the middle, use elif.
money = 5000
if money >= 10000:
print("Let us eat chicken!")
elif money >= 5000:
print("Let us eat tteokbokki!")
else:
print("Let us just skip the meal...")
That translates to:
Remember that money is 5000
If money is greater than or equal to 10000:
print "Let us eat chicken!"
Otherwise, if money is greater than or equal to 5000:
print "Let us eat tteokbokki!"
If none of those:
print "Let us just skip the meal..."
Symbols you use in questions (comparison operators)
These are similar to what you learned in math.
>: greater than<: less than>=: greater than or equal to<=: less than or equal to==: equal to (remember=means “store”, so use==when you want to ask “is it the same?”)!=: not equal to
Now you can tell the computer to act differently depending on the situation!