gpt4 book ai didi

python - 迭代计数器 Python3x

转载 作者:行者123 更新时间:2023-11-30 22:20:22 25 4
gpt4 key购买 nike

所以我用 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。并将此声明移至 while 循环上方。

还有行:

for y in answer:
counter += 1

真的很令人困惑,而且肯定是错误的,因为如果你得到"is"作为答案,你将获得 +3 的增长。只需递增(counter += 1) counter,无需任何for循环。

关于python - 迭代计数器 Python3x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48856359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com