首页 > 解决方案 > 在基本脚本中使用 break 语句

问题描述

下面是一个简单的计算器程序,我在其中使用break语句来控制逻辑,我想知道这对break语句来说是否过分或者是否可以。

while True:
try:
    print("Choose operation(+ | - | * | / | Enter 'e' to exit)")
    op=input()
    if op!="+" and op!="-" and op!="*" and op!="/" and op!="e":
        print("Invalid input, you must choose an option from the menu.")
        break
    elif op=="e":
        break
    else:
        print(">")
        val1=float(input(val1))
        print(">")
        val2=input()
        val2=float(input(val2))
        if op=="+":
            print("= ", val1+val2)
        elif op=="-":
            print("= ", val1-val2) 
        elif op=="*":
            print("= ", val1*val2)
        else:
            print("= ", val1/val2)  
except ValueError:  
    print("Input must be numerical.")  
    break 
except ZeroDivisionError:
    print("Dividing by zero is undefined.")
    break
exit()

标签: python

解决方案


更新:

基本上我所做的是修复缩进,删除两次val2,删除exit()调用,将所有内容放在一个函数中,然后从另一个while True循环调用它。如果输入错误,程序将再次调用该函数并尝试要求用户输入正确。如果用户输入是e,则函数返回“EXIT”,然后程序将终止。

顺便说一句,您可以在没有函数的情况下使用 2 个嵌套的 for 循环来执行此操作,尽管我认为它看起来不会像现在这样好。

def calculator():
    while True:
        try:
            print("Choose operation(+ | - | * | / | Enter 'e' to exit)")
            op=input()
            if op not in ("+", "-", "*", "/", "e"):    # Changed that too, more simple now
                print("Invalid input, you must choose an option from the menu.")
                break
            elif op == "e":
                return "EXIT"
            else:
                print(">")
                val1=float(input())
                print(">")
                val2=float(input())
                if op == "+":
                    print("= ", val1+val2)
                elif op == "-":
                    print("= ", val1-val2)
                elif op == "*":
                    print("= ", val1*val2)
                else:
                    print("= ", val1/val2)
        except ValueError:
            print("Input must be numerical.")
            break
        except ZeroDivisionError:
            print("Dividing by zero is undefined.")
            break
    return "OK"

while True:
    if calculator() == "EXIT":
        break

这就是具有多种功能的解决方案:

def is_valid(user_input):
    if user_input not in ("+", "-", "*", "/", "e"):
        print("Invalid input, you must choose an option from the menu.")
        return False
    return True

def result(val1, val2, op):
    if op == "+":
        print("= ", val1 + val2)
    elif op == "-":
        print("= ", val1 - val2)
    elif op == "*":
        print("= ", val1 * val2)
    else:
        if val2 != 0:
            print("= ", val1 / val2)
        else:
            print("Dividing by zero is undefined.")

def caculater():
    while True:
            op=input("Choose operation(+ | - | * | / | Enter 'e' to exit)\n")
            if not is_valid(op):
                break
            if op == "e":
                return "e"
            else:
                try:
                    val1=float(input("> "))
                    val2=float(input("> "))
                    result(val1, val2, op)
                except ValueError:
                    print("Input must be numerical.")
    return "OK"

while True:
    if caculater() == "e":
        break

推荐阅读