防御并中断并继续

问题描述 投票:0回答:1

我知道这是行不通的,但是有什么解决方案,而不是为每个选项重复底部?问题是continuebreak无法放入def

while True:
    print (" For + press A, - press B, X press C , / press D\n")
    choice = input ("Enter either A, B, C or D \n").title()
    number1 = int(input ("Now enter the first number(s) of the calculation\n"))
    number2 = int(input ("Now enter the second number(s) of the calculation\n"))
    if choice == "A":
        print (number1,"+",number2,"=",(number1+number2))
        again()
    elif choice == "B":
        print (number1,"-",number2,"=",(number1-number2))
        again()
    elif choice == "C":
        print (number1,"X",number2,"=",(number1*number2))
        again()
    elif choice == "D":
        if number2 == 0:
            print("Error")
        print (number1,"/",number2,"=",(number1/number2))
        again()
    else:
        print ("Error!")
        again()

def again():
    con = input ("Do you want to continue Y or N?".title())
    if con =="Y":
        continue
    else:
        break
python user-defined-functions using
1个回答
0
投票

基本上,功能只能影响其自身的流程。

现在,我想不出一种简单的方法来完成您想要的事情,但是这仅仅是您可以将代码从函数移至循环末尾的问题。 (我还修复了您的代码的其他一些问题。)

while True:
    ...
    if choice == "A":
        print(number1, ...)
    elif choice == "B":
        print(number1, ...)
    elif choice == "C":
        print(number1, ...)
    elif choice == "D":
        if number2 == 0:
            print("Error: can't divide by zero")  # Also clarified this
        else:  # Also added this
            print(number1, ...)
    else:
        print("Error: Unrecognized command")  # Also clarified this

    con = input("Do you want to continue Y or N?").title()  # Also fixed typo here
    if con == "Y":
        continue
    else:
        break
© www.soinside.com 2019 - 2024. All rights reserved.