Python

Control statements are an important asset in decision making in python. They can determine logic that is to be followed when a certain condition is met.

A real-life example would be:

If it rains outside, I will bring an umbrella with me, or, if it stops raining, we’ll go outside.

Anyway, you get the point. Control statements or in this case if statements can be basically understood as if a condition is met, perform a certain action.

if Statement

is_raining = True

if (is_raining==True):
    print("Its raining")

In the example above we declared a boolean variable with name is_raining, with value as True. The second line is used to check if a condition is met, then perform an operation, in our case print Its raining.

elif

Elif is the abbreviation of the word else-if. You can use elif statements to simultaneously check conditions one after the other.

If the first condition is not met the second condition will follow, if the second is not met the third will follow and so on.

Example

is_raining = False

if (is_raining==True):
    print("Its raining")

elif (is_raining==False):
    print("Its not raining")

else

If neither an if-condition nor an elif condition is met, then you can check for everything else with the else statement. Else statement can be used to execute a code when no other condition is met.

Example:

temp = 40

if (temp<35):
    print("Its hot outside")
elif (temp>18):
    print("Its cold outside")
else:
    print("You sure are having a tough time")

Please follow and like us:
error

Leave a Reply