Day 5: Calcutron 3000 – a simple shell calculator with validation

Our calculator takes in two numbers (float) and a type (sum, substract, multiplication and division). The Output looks like this


The program is pretty self explaining. We put all the logic into the calc-function. When the User has finished his calculation we ask him if he wants to make another calculation or exit the program.

def calc():
    print("******* Calcutron 3000 *******")
    val1 = (input("Enter first value: "))
    val2 = (input("Enter second value: "))
    type = (input("Choose your operation: 1 = sum, 2 = substract, 3 = multiplication, 4 = division: "))
    val1 = float(val1)  #change input string to float
    val2 = float(val2)  #change input string to float
    type = int(type) #change input string to int
    #check if both val1/val2 are valid float numbers and if type is in the range between 1 and 4
    if (isinstance(val1, float)) and (isinstance(val2, float)) and (1 <= type <= 4):
        if (type==1):
            print(val1 + val2)
        elif (type==2):
            print(val1 - val2)
        elif (type==3):
            print(val1 * val2)
        elif (type==4):
            print(val1 / val2)
        print("Please enter valid numbers!") # handle wrong inputs
    if (input("Another calculation? (y/n) " )=="y"):

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.