【问题标题】:Iteration counter Python3x迭代计数器 Python3x
【发布时间】:2018-02-18 20:40:51
【问题描述】:

所以我用 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

【问题讨论】:

  • 因为你一直在while循环中分配counter = 0
  • 请注意 - 您可以使用 answer in ['y', 'Y', 'yes', 'Yes'] 而不是将 answer 与每个可能的值进行比较。

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


【解决方案1】:

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

还有行:

for y in answer:
    counter += 1

确实令人困惑并且肯定是错误的,因为如果您的答案是“是”,您将获得+3的增加。只增加(counter += 1) counter 没有任何for-loop。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 2020-08-09
    相关资源
    最近更新 更多