繁体   English   中英

如何回到python循环的开始?

[英]How to go back to the beginning of a loop in python?

我的代码:

b="y"

ol=[]

#operations list

OPERATIONS = ["-", "+", "*", "/"]

op = input ("Please enter your first calculation\n")

while b=="y":



    ops = op.split(" ")

    #add arguments to list

    for x in ops:
        ol+=x

    if ol[1] in OPERATIONS:

        #make sure operator is an operator

        print()

        #make sure not dividing by zero

        if ol[1] == "/" and ol[2] == "0":

            print("Error")

            b = input("Would you like to do another calculation (y/n)?\n")

            if b == "y":

                op = input("Please enter your calculation:\n")

                continue

            else:
                break
        else:

            n1 = float(ol[0])
            n2 = float(ol[2])

            #calculations done here

            if ol[1] == '-':

                calc = n1-n2

            if ol[1] == '+':

                calc = n1+n2

            if ol[1] == '/':

                calc = n1/n2

            if ol[1] == '*':

                calc = n1*n2

            print("Result: " + str(calc))

            b = input("Would you like to do another calculation (y/n)?\n")

            if b == "y":

                op = input("Please enter your calculation:\n")

                continue

            else:
                break



    else:
        print("Error")

如何确保程序将新操作带到循环的开始,而不是继续打印原始计算?

您需要在while循环中重置ol=[]

使用从变量ops生成的操作ol列表执行计算,该ops通过将输入ops除以空格来获取。

您可以通过将ol=[]移入循环来实现:

b="y"
# Remove ol=[]

#operations list
OPERATIONS = ["-", "+", "*", "/"]

op = input ("Please enter your first calculation\n")

while b=="y":
    ol = [] # Add here

但是,有一种更简单的方法。 变量ops包含一个来自split的操作列表( str.split生成一个列表),然后将该值复制到列表ol 相反,您可以将字符串直接拆分为变量ol ,如下所示:

b="y"

#operations list
OPERATIONS = ["-", "+", "*", "/"]

op = input ("Please enter your first calculation\n")

while b=="y":
    ol = op.split(" ")

这样比较整洁,因为您不需要多余的ops变量。

暂无
暂无

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

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