Def的突破并继续

时间:2019-11-12 08:32:34

标签: python user-defined-functions using

我知道这是行不通的,但是有什么解决方案,而不是为每个选项重复底部?问题是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

2 个答案:

答案 0 :(得分:2)

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

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

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":  # Also changed this since it will continue by default
        break

答案 1 :(得分:2)

扩展@wjandrea的答案,此控制流根本不需要breakcontinue;只需将循环条件从while True:更改为合适的条件即可,例如:

con = "Y"
while con == "Y":
    # ...

    con = input("Do you want to continue Y or N?").title()

con == "Y"时,循环继续,否则停止,这与以前完全相同。