Else Statements

The else statement is the counterpart to the if statement. The else statement contains the code when the if statements evaluates to false. In simpler terms, when the condition for the if statement does not ring true then the code of the else statement is then interpreted.

*Similar to the if statements, the code for the else statements should contain both the colon and the indentation.

[Console]

>>> x = 1

>>> if x == 2

print(“Yes”)

>>> else:

print(“No”)

=====

[Interpreter]

No

Similar to the if statements, certain statements can be nested within each other and as a result certain statements can be chained together.

[Console]

>>> num = 3

>>> if num == 1:

print(“Number is 1”)

>>>> else:

if num == 2:

print(“Number is 2”)

else:

if num == 3:

print(“Number is 3”)

else:

print(“Number is not 1, 2 or 3)

=====

[Interpreter]

Number is 3

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s