0

I'm new to python and having some issues with a task.

I need to write a code with example output:

Calculator
Give the first number: 50
Give the second number: 5
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 50 5
Please select something (1-6): 1
The result is: 55
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 50 5
Please select something (1-6): 2
The result is: 45
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 50 5
Please select something (1-6): 4
The result is: 10.0
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 50 5
Please select something (1-6): 6
Thank you!

I've been trying to use while loop for this but without any luck. I just don't understand the while loop well enough, watched so many tutorials but theyre all the same with 1 input and a single print line. I've tried so far this: (which doesn't really use the while looping and doesn't even work properly:

print("Calculator")
number1 = int(input("Give the first number:"))
number2 = int(input("Give the second number:"))
print("(1) +")
print("(2) -")
print("(3) *")
print("(4) /")
print("(5) Change numbers: ")
print("(6) Quit")
print("Current numbers: ", number1, number2)
while True:
    selection = (int(input("Please select something (1-6):")))
    if selection == 1:
        print("The result is:", number1 + number2)
        print("(1) +")
        print("(2) -")
        print("(3) *")
        print("(4) /")
        print("(5) Change numbers: ")
        print("(6) Quit")
        print("Current numbers: ", number1, number2)
    selection = (int(input("Please select something (1-6):")))
    if selection == 2:
        print("The result is:", number1 - number2)
        print("(1) +")
        print("(2) -")
        print("(3) *")
        print("(4) /")
        print("(5) Change numbers: ")
        print("(6) Quit")
        print("Current numbers: ", number1, number2)
    selection = (int(input("Please select something (1-6):")))
    if selection == 3:
        print("The result is:", number1 * number2)
        print("(1) +")
        print("(2) -")
        print("(3) *")
        print("(4) /")
        print("(5) Change numbers: ")
        print("(6) Quit")
        print("Current numbers: ", number1, number2)
    selection = (int(input("Please select something (1-6):")))
    if selection == 4:
        print("The result is:", number1 / number2)
        print("(1) +")
        print("(2) -")
        print("(3) *")
        print("(4) /")
        print("(5) Change numbers: ")
        print("(6) Quit")
        print("Current numbers: ", number1, number2)

Does anyone know a good tutorial that would explain how to solve a task like this? I can't figure out how to not copy the "print" parts so many times but instead loop it correctly.

0

3 Answers 3

0

The direct answer is to put the 'print' at the start, outside of the if statement

print("Calculator")
number1 = int(input("Give the first number:"))
number2 = int(input("Give the second number:"))

while True:
    print("(1) +")
    print("(2) -")
    print("(3) *")
    print("(4) /")
    print("(5) Change numbers: ")
    print("(6) Quit")
    print("Current numbers: ", number1, number2)
    selection = (int(input("Please select something (1-6):")))
    if selection == 1:
        print("The result is:", number1 + number2)
        
    if selection == 2:
        print("The result is:", number1 - number2)
        
    if selection == 3:
        print("The result is:", number1 * number2)
        
    if selection == 4:
        print("The result is:", number1 / number2)
    
Sign up to request clarification or add additional context in comments.

Comments

0

Define a convenience function to gather number input

def number_entry(which="first"):
    entry = None
    while not entry and len(entry) < 1:
        entry = input(f"Give the {which} number:")
        if not entry:
            print(f"need {which} number")
        # could check for number here
    return entry

Define a convenience function to gather selection: (no need to convert selection to int(eger))

OP_ADD="1"
OP_SUB="2"
OP_MUL="3"
OP_DIV="4"
OP_PICK="5"
OP_QUIT="6"

def operator_entry():
    while not entry:
        print("(1) +")
        print("(2) -")
        print("(3) *")
        print("(4) /")
        print("(5) Change numbers: ")
        print("(6) Quit")
        entry = input("Please select something(1-6):")
        if not entry:
            print("try again...")
            continue
        if entry not in ["1", "2", "3", "4", "5", "6"]:
            print(f"invalid entry {entry}")
            continue
    return entry

Define a function that performs the selected operation

def action(operator,operand1,operand2):
    result = 0
    if OP_ADD == operator:
        result = operand1 + operand2
    elif OP_SUB == operator:
        result = operand1 - operand2
    elif OP_MUL == operator:
        result = operand1 * operand2
    elif OP_DIV == operator:
        result = operand1 / operand2
    else:
        print(f"invalid operator {operator}")
    return result

Define your calculator function:

def calculator():
    done = False
    while not done:
        input1 = int(number_entry("first"))
        input2 = int(number_entry("second"))
        print("Current numbers: ", number1, number2)
        selection = operator_entry()
        if OP_PICK == selection:
            continue
        if OP_QUIT == selection:
            done = True
            continue
        result = action(selection,input1,input2)
        print("The result is: {result}")

Run your calculator:

    calculator()

Comments

0

One approach that you can use to make it a bit more robust: using a class and creating reusable functions that help you not to repeat code.

Good Luck



import operator
from time import sleep

class Calculator:
    CHANGE_NUMBER = 5
    QUIT = 6

    math_operations = {
        1: operator.add,
        2: operator.sub,
        3: operator.mul,
        4: operator.truediv,
    }

    options = {
        1: "+",
        2: "-",
        3: "*",
        4: "/",
        5: "Change Number", 
        6: "Quit"
    }

    def __init__(self):
        self.n1 = None
        self.n2 = None
        print("Calculator")
    
    def run(self):
        while True:
            operation = self.operation()
            if not operation:
                break # We go out of the while loop

    def operation(self):
        if self.n1 is None or self.n2 is None:
            self.get_numbers()
        else:
            print(f"\n Current numbers: {self.n1}, {self.n2}")
        
        return self.procces_operation(self.get_operation())

    def print_options(self):
        for i, option in self.options.items():
            print(f"({i}) {option}")
    
    def get_operation(self):
        self.print_options()
        option =  (int(input("Please select something (1-6): ")))
        if option <= 0 or option > len(self.options):
            print("Please select a valid option")
            sleep(1)
            self.get_operation()
        
        return option

    def get_numbers(self):
        self.n1 = int(input("Give the first number: "))
        self.n2 = int(input("Give the second number: "))
    
    def procces_operation(self, operation: int):
        if operation == self.QUIT:
            return

        if operation == self.CHANGE_NUMBER:
            self.get_numbers()
            return True # We still get other operation

        result =  self.math_operations.get(operation)(self.n1, self.n2)
        print(f"The result is: {result}")
        sleep(1)
        return True # We still get other operation

def main():
    calculator = Calculator()
    calculator.run()

if __name__ == '__main__':
    main()
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.