Check multiple conditions using else if in C# vs Python

In the previous lesson, we developed a program that decided whether the user could purchase a car based on their account balance. The program simply compared the user’s balance to a threshold and printed one of the two possible messages. But what if we wanted to have a more diverse set of messages? For example, we might want to have different messages for an account balance below 10000, between 10000 and 50000 and above 50000. What we require is an else-if (or elif in Python) statement.

Else if statement

C# code

 

The second condition  balance >= 10000  is evaluated only if the first condition  balance >= 50000 returns False. Each else-if/elif condition is evaluated in this manner if all the conditions above it return False. If one of the conditions return true, the corresponding block of code is executed and the following conditions are never evaluated. If none of the conditions is met, the block of code under else statement is executed.

Python code

Combine multiple conditions using logical operators

We can combine multiple conditions using logical operators to create more complex and useful conditions. The logical operators available is C# and Python are given in the table below. Combining two conditions using the AND operator returns true if both the conditions are true. The OR operator, on the other hand, results true if any of the two conditions is true. The NOT operator takes in a single condition and reverses its logical state.

Operation

Logical AND

Logical OR

Logical NOT

C#

&&

||

!

Python

and

or

not

Suppose there is a club that only allows entry to people between the ages of 25 and 50. At the entrance of the club runs the following program that asks the user for their age and decides whether they can enter or not.

C# code

Python code

The condition in the if-statement returns true if the user has an age greater than or equal to 25 and less than or equal to 50. In all other cases the else statement executes.

Suppose our club’s age restriction is only for men, while women can always enter irrespective of their age.

C# code

Python code

 

The condition in the if-statement will now return true when either the user’s age is between 25 and 50 or the user is a woman.

What we learnt

  1. Simple conditions can be combined using logical operators to create more complex conditions
  2. Symbols for logical operators differ in C# and Python.

< Decision making and branching               Programming a basic calculator >

You may also like: