Python Basics Tutorial 8 – Python else Statements

Notes from the video Python Course Singapore | Learn Python Programming | Tutorial 8 – Python else Statements’:

 

In the previous tutorial, we learnt about if statements.

Let’s look at the code from the previous video again.

if country == “Singapore”:
        print(“Yes”)

We learnt that this code tells Python to display Yes when the string “Singapore” is assigned to the variable country. Otherwise, nothing would be displayed.

What if we wanted Python to do something if the string “Singapore” wasn’t assigned to the variable country?

That’s where the keyword else comes in.

We can use the else statement to tell Python what to do when the if-test fails.

Now, we can tell Python to display No, by adding two more lines of code here.

if country == “Singapore”:
        print(“Yes”)

else:
        print(“No”)

 

By adding these two lines of code, Python would display No if the if-test fails – that is, when the string “Singapore” is not assigned to the variable country.

 

Now, let’s take a closer look at these two lines of code:

else:
        print(“No”)

Notice that the keyword else is in lowercase like other keywords print and if.

You might also notice that else is not indented, has its own line and a colon at the end just like the if statement.

 

Next, we look at the next line, print(“No”). The line is indented and is executed if the else-test passes.

 

Like the if statement, you can get Python to execute more than one line of code if the else statement is true. Let’s try this out.

 

For example, if we were to include one more line of code after print(“No”), for example print(5). If the string “Singapore” isn’t assigned to the variable country, Python would display No and 5.

Get FREE LESSONS and TIPS on how YOU can excel at programming and business

Awesome! Thank you for subscribing!