Tuesday 29 September 2020

Part Two: Exercise 2: A Simple Calculator with if, elif and else Statements

 In this exercise, we build a simple calculator to take in 2 numbers as input from the user. 

Then gives the user the choice to do addition, subtraction, multiplication or division. 
Also, the program should alert the user if they make an invalid entry.
This program should be accomplished using the else, elif and else statements.

You can compare with my solution below:
 
First of all I printed a heading similar to the one in the previous exercise saying this is ‘A Simple Calculator’.

Next the program asks the user to input the first number. After that, it then asks the user for the second number. The inputs are floats.
 
Next we give the user 4 options to choose from, 1. Addition 2. Subtraction 3. Multiplication 4. Division, then ask the user to choose one of the options.
 
The user is alerted if they input anything other than 1, 2, 3 or 4.

Next, we put in our if, elif and else statements. If the user chose option 1, we add, else if they chose option 2, we subtract, if option 3 we multiply and else if option 4 we divide.
 
I did in in 2 ways. You can look at my code below. 
 

print('A Simple Calculator')
print('*' * 20)
print()
x=float(input("Please enter a number : "))
y=float(input("Please enter another number : "))
print()
print("1) Add the two numbers")
print("2) Subtract the two numbers")
print("3) Multiply the two numbers")
print("4) Divide the two numbers")

choice = int(input("Please enter your choice: "))

print("The answer is: ")

if choice == 1:
    print(x+y)
else:
    if choice == 2:
        print(x-y)
    else:
        if choice == 3:
            print(x*y)
        else:
            if choice == 4:
                print(x/y)
            else:
                print("You did not enter a valid choice")

OR
 

print('A Simple Calculator')
print('*' * 20)
print()
x=float(input("Please enter a number : "))
y=float(input("Please enter another number : "))
print()
print("1) Add the two numbers")
print("2) Subtract the two numbers")
print("3) Multiply the two numbers")
print("4) Divide the two numbers")

choice = int(input("Please enter your choice: "))

print("The answer is: ")


if choice == 1:
    print(x+y)
elif choice == 2:
    print(x-y)
elif choice == 3:
    print(x*y)
elif choice == 4:
    print(x/y)
else:
    print("You did not enter a valid choice")



Using the elif statement seem to make the code more compact than relying on just the if and else statements alone.

 

No comments:

Post a Comment