Python Network Programming
上QQ阅读APP看书,第一时间看更新

Nested and multiple conditions

Sometimes we need to check multiple conditions in a single if condition.

Let's see an example of this:

Here, we are checking the range of the marks. The flow of the program is as follows:

Assign a value of 85 to the marks variable. If marks is less than or equal to 45, print Grade C, else if marks is greater than 45 and less than equal to 75, print Grade B, else if marks is greater than 75, print Grade A, else if none of the preceding conditions match, then print Unable to determine.

The PowerShell sample code for the preceding Python task is as follows:

#PowerShell sample code:
$marks=85
if ($marks -le 45)
{
write-host "Grade C"
}
elseif (($marks -gt 45) -and ($marks -le 75))
{
write-host "Grade B"
}
elseif ($marks -gt 75)
{
write-host "Grade A"
}
else
{
write-host "Unable to determine"
}

Similarly, here is an example of a nested condition (note the indentation that differentiates it from the earlier example of multiple conditions):

As we can see in the condition, the internal conditions will only be executed if its parent condition evaluates to true. If there is a false, the corresponding else action will be taken. In the example, if the car_details variable contains Car, contains blue, and it contains sedan, only then will the action I will buy this car be performed. If any of those conditions are not met, the relevant else action will be performed.