Python 使用具有多个输入和选择的 while 循环

Python using while loop with multiple inputs and choices

我是 python 的新手,在执行任务时遇到了一些问题。

我需要编写带有示例输出的代码:

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!

我一直在尝试为此使用 while 循环,但没有任何运气。我只是不太了解 while 循环,看了那么多教程,但它们都是一样的,只有 1 个输入和一个打印行。到目前为止,我已经尝试过这个:(它并没有真正使用 while 循环,甚至不能正常工作:

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)

有谁知道可以解释如何解决这样的任务的好教程吗?我不知道如何不多次复制“打印”部分,而是正确地循环它。

直接的答案是将 'print' 放在开头,在 if 语句之外

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)
    

定义一个方便的函数来收集数字输入

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

定义一个方便的函数来收集选择:(无需将选择转换为 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

定义执行所选操作的函数

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

定义计算器函数:

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}")

运行 你的计算器:

    calculator()

您可以使用一种方法使其更加健壮: 使用 class 并创建可帮助您避免重复代码的可重用函数。

祝你好运



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()