迭代计数器Python3x

时间:2018-02-18 20:40:51

标签: python python-3.x loops counter calculator

所以我在Python中构建了一个简单的计算器,用户输入两个数字和一个运算符,然后给出答案。他们还可以选择再次运行计算器。我想对答案进行编号,以便每个答案都显示“答案1等于x”,“答案2等于x”等,具体取决于计算器运行的次数。每次我尝试格式化计数器来计算迭代次数时,它都不会起作用而且只是一遍又一遍地将它们标记为“答案1”。任何帮助将不胜感激。我是Python的新手。

answer = "y"

while ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
    numones = input ("Give me a number: ")
    numtwos = input ("Give me another number: ")

    numone = float(numones)
    numtwo = float(numtwos)

    operation = input ("Give me an operation (+,-,*,/): ")

    counter = 0
    for y in answer:
        counter += 1

    if (operation == "+"):
        calc = numone + numtwo
        print ("Answer " + str(counter) + " is " + str(calc))
    elif (operation == "-"):
        calc = numone - numtwo
        print ("Answer " + str(counter) + " is " + str(calc))
    elif (operation == "*"):
        calc = numone * numtwo
        print ("Answer " + str(counter) + " is " + str(calc))
    elif (operation == "/"):
        calc = numone / numtwo
        if (numtwo != 0):
            print ("Answer " + str(counter) + " is " + str(calc))
        else:
            print ("You can't divide by zero.")
    else:    
        print ("Operator not recognized.")

    answer = input ("Do you want to keep going? ")
    if ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
        print ()
    else:
        print ("Goodbye.")
        break

1 个答案:

答案 0 :(得分:3)

删除counter = 0循环中的while分配。并将此声明移到while循环上方。

也行:

for y in answer:
    counter += 1

确实令人困惑,肯定是错的,因为如果你得到了“是”'作为答案,你会得到+3的增加。只需增加(counter += 1counter而不添加for - 循环。

相关问题