首页 > 解决方案 > 我们究竟如何在 Python 中使用“继续”?

问题描述

i=0
while (i==0):

    n1=float(input("Enter the first number: \n"))
    n2=float(input("Enter the second number: \n"))
    a=str(input("Choose the operation: \n 1.) + \n 2.) - \n 3.) * \n 4.) / \n 5.) % \n"))
    if(a==1):
        print("The addition of the inputted numbers is ", sum(n1,n2),"\n")
    elif(a==2):
        print("The difference between the inputted numbers is ", diff(n1,n2),"\n")
    elif(a==3):
        print("The multiplication of the inputted numbers is ", product(n1,n2),"\n")
    elif(a==4):
        print("The division of the inputted numbers is ", div(n1,n2),"\n")
    elif(a==5):
        print("The modulus of the inputted numbers is ", modulus(n1,n2),"\n")
    else:
        print("Do you want to quit the calculator?")
        b=int(input("Press 00 for 'Yes' and 11 for 'No'\n"))
        if(b==00):
            break 
        else:
            print("Enter a valid option for the operation number.\nThe calculator is re-starting.")
            continue

这是我的python代码。我已经定义了这里使用的所有函数。

我得到的输出是:

在此处输入图像描述

当我在图像中圈出的位置输入正确的操作编号 3 时,为什么输出没有给我最终计算出的答案?为什么它一次又一次地重复相同的循环?

请帮助我。

标签: pythonpython-3.x

解决方案


Hacker 已经为您提供了所有需要完成的更改。您需要查看整数与字符串的比较、while 循环的使用情况以及 Try-Except 选项。

为了帮助您有一个参考点,这里有修改后的代码供您比较:

while True:

    while True:
        try:
            n1=float(input("Enter the first number: \n"))
            break
        except:
            print ('Enter a number. It can be integer or float')

    while True:
        try:
            n2=float(input("Enter the second number: \n"))
            break
        except:
            print ('Enter a number. It can be integer or float')

    while True:
        try:
            a=int(input("Choose the operation: \n 1.) + \n 2.) - \n 3.) * \n 4.) / \n 5.) % \n"))
            if 1 <= a <= 5:
                break
            else:
                print ('Enter a number within range 1 and 5')
        except:
            print ('Not a number. Please enter an integer')
    
    if   (a==1):
        print("The addition of the inputted numbers is ", (n1+n2),"\n")
    elif (a==2):
        print("The difference between the inputted numbers is ", (n1-n2),"\n")
    elif (a==3):
        print("The multiplication of the inputted numbers is ", (n1*n2),"\n")
    elif (a==4):
        print("The division of the inputted numbers is ", n1/n2,"\n")
    elif (a==5):
        print("The modulus of the inputted numbers is ", int(n1%n2),"\n")

    print("Do you want to quit the calculator?")

    while True:
        try:
            b=int(input("Press 00 for 'Yes' and 11 for 'No'\n"))
            if b==0: break
            elif b!= 11: print ('Enter a valid option: 00 or 11')
        except:
            print ('Not a number. Please enter an integer')

推荐阅读