简体   繁体   English

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

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

I'm new to python and having some issues with a task.我是 python 的新手,并且遇到了一些任务问题。

I need to write a code with example output:我需要用示例 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.我一直在尝试为此使用while循环,但没有任何运气。 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.我只是不太了解 while 循环,看了这么多教程,但它们都一样,只有 1 个输入和一个打印行。 I've tried so far this: (which doesn't really use the while looping and doesn't even work properly:到目前为止,我已经尝试过:(它并没有真正使用 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)

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.我不知道如何不多次复制“打印”部分,而是正确循环。

The direct answer is to put the 'print' at the start, outside of the if statement直接的答案是将“打印”放在 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)
    

Define a convenience function to gather number input定义一个方便的 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

Define a convenience function to gather selection: (no need to convert selection to int(eger))定义一个方便的 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

Define a function that performs the selected operation定义一个执行所选操作的 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

Define your calculator function:定义您的计算器 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()

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.您可以使用一种方法使其更加健壮:使用 class 并创建可帮助您不重复代码的可重用函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM