Conditional statement in python

Conditional statement in python (if, elseif, else)

Check the below code and see what can you make out of it

x = 8

if x > 0:

    print('it is true')

elif x == 0:

    print('it is zero')

else:

    print('unknown')

it is true

if is a conditional statement

elif (else if) provides you option to verify any other conditions and we can use elif as many times as we need to.

else provides you with the last option if any of the defined conditions are not true


Let's say in your dataframe, there is a column for province and it lists province name for that row.


For your analysis, you don't need to go by every province but you decide to create 3 regions from these provinces. Eastern, Central  and Western

And you want to list provinces under each region

Eastern

new_brunswick, nova_scotia, prince_edward_island

Central

ontario, quebec, manitoba

Western

alberta, british_columbia, saskatchewan


Using conditional statement, you can create a new column 'region'


if (province=='alberta') or (province == 'british_columbia') or (province == 'saskatchewan'):

        region.append('western_canada')

        

    elif (province=='ontario') or (province == 'manitoba') or (province == 'quebec'):

        region.append('central_canada')

    else:

        region.append('eastern_canada')

       



As we can see, conditional statements are very useful in classifying or grouping the data into segments which can be easily visualized.

No comments:

Post a Comment

Complex query example

Requirement:  You are given the table with titles of recipes from a cookbook and their page numbers. You are asked to represent how the reci...