Python Basics Tutorial 7 – Python if Statements
Notes from the video ‘Python Course Singapore | Learn Python Programming | Tutorial 7 – Python if Statements’:
Let’s say you want to know whether the string “Singapore” is assigned to the variable country
You would have to key in this code:
if country == “Singapore”:
If the string “Singapore” was assigned to the variable country, Python would display Yes. If the string wasn’t assigned to the variable, then nothing is displayed.
Now, let’s take a closer look at the code.
The code starts with the keyword if. Notice that if is in lowercase like other keywords we have used in our earlier videos. If the keyword was in uppercase, the program won’t run.
Next, let’s look at the two equal signs (==).
In our previous videos, we learnt that one equal sign (=) is used to assign a value to a variable.
In the code name = “Jack”, the string “Jack” is assigned to the variable name.
When we are testing whether one thing is the same as another thing, we have to use two equal signs. This sign is also called the ‘equal to’ sign. We use it to compare whether a variable is equal to a string, or a variable is equal to a number or perhaps another variable.
At the end of the first line, we would need to end it with a colon.
In the next line, you would tell Python the codes to execute if the string “Singapore” was assigned to the variable country.
You can get Python to do various things if the answer to the if question was yes.
In this case, we told Python to print the word Yes if the string was assigned to the variable.
You may also notice that this line of code is indented by one tab and the first line wasn’t indented.
In general, the indented lines after a line that ends in a colon takes orders from the line that ends in the colon.
We can get Python to do more than one thing if the if statement is true, for example, we can add one more line of code, print(“I live in Singapore.”) after the second line of code.
Again, this line of code is indented by one tab.
Now if the string “Singapore” was assigned to the variable country, Python would execute the indented lines after the colon.
In this case, Python would display Yes and I live in Singapore.