Conditionals and Nesting

Through the usage of conditionals Python performs different computations or actions depending on whether a specific constraint evaluates to true or false. The syntax looks as following:

So lets say you want to test who scored more goals in the Champions League (CL), Ronaldo or Messi you can do it as follows:

The next step is to use the “else”-Statement. So depending on if our logical expression is right or wrong the “else”-Statement will be executed or not. To make this more practical let’s have a look at an example. Imagine a family dad wants to go to a soocer match, but isn’t sure if his children are old enough to get in and what he has to pay for them. We will solve this through this little program:

Notice the following: We can see a nested if-else here (the yellow part). If the age was 10 the compiler would directly jump to the else at the bottom. If the age is higher or equal to 11 it shows the prices. You can see that nesting is nothing more than placing one or more if statements within another if statement. Furthermore, we see the “or” operator, which is pretty self-explaining.

After we got to know the “if else” structure, now we introduce the “elif”, which is short for else if. It allows us to check for multiple expressions. If the condition for if is False, it checks the condition of the next elif block and so on. If all the conditions are False, body of else is executed. Only one block among the several if...elif...else blocks is executed according to the condition. The if block can have only one else block. But it can have multiple elif blocks.

Lets build an example on this. Assume you know the number of seats, which will be free in the stadium during the soccer game. Now you want to know how the atmosphere in the stadium will be based on this information:

For further information I on conditionals I can recommend this webpage:

#Mastery11 #Mastery12

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s