A simple calculator program using nested if statements

We now possess enough knowledge to program a basic calculator of our own in either C# or Python. We will solidify the concepts covered thus far and also learn a few new tricks. Our basic calculator will be able to perform addition, subtraction, multiplication and division operations.

C# code

First of all, we take two operands and the operation to be performed as input from the user. The operands are stored in the float variables  num1 and num2 while the single character representing the operation to be performed is stored in the string variable operation. The if-statements then compare the contents of the variable operation against the allowed characters and performs the corresponding operation if the condition returns true. Notice how the program checks for both small letter and capital letter input using the logical OR operator. If the input character does not represent a valid operation, the else statement is executed displaying the message “Invalid operation”.

Nested if statements

Lets zoom in and focus on the following block from the above example.

There is an if-else statement to check if the second operand is zero, nested within the else-if statement. This kind of nesting is sometimes useful if you want to check another condition after the condition in the outer if-statement has returned true. We can nest code up to as many levels as we like, however, nesting leads to code that is messy and difficult to follow. Therefore, it is usually recommended to try and limit the nesting to a level that is absolutely necessary. An alternative implementation of the code above without the nesting would be as follows.

This concludes the implementation of our basic calculator in C#. Translating the C# code to Python should be fairly simple at this point and should be attempted as an exercise.

< Multiple conditions and else if statement               Multiplication table using for loop >

You may also like: