簡體   English   中英

Python 使用帶有多個輸入和選擇的 while 循環

[英]Python using while loop with multiple inputs and choices

我是 python 的新手,並且遇到了一些任務問題。

我需要用示例 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!

我一直在嘗試為此使用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)

有誰知道一個很好的教程來解釋如何解決這樣的任務? 我不知道如何不多次復制“打印”部分,而是正確循環。

直接的答案是將“打印”放在 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)
    

定義一個方便的 function 來采集數字輸入

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

定義一個方便的 function 來收集選擇:(無需將選擇轉換為 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

定義一個執行所選操作的 function

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

定義您的計算器 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}")

運行你的計算器:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM