如何有条件地更新计数器并在最后打印结果(Python)?

问题描述 投票:0回答:1

我正在尝试循环并在循环结束时打印出成绩(例如

2
)。因此,如果满足
if
声明标准,成绩将会提高(因此存在
counter
listt
)。

我尝试初始化一个计数器,附加到一个列表,并将打印语句移到循环之外。该列表会随着每个正确的输入打印出 10 个“y”,并且不会随着每个正确的答案而增加。柜台也一样。我已经注释掉了一些尝试。

int1 = random.randrange(1, 3)
int2 = random.range(1,3)
aa = int1 * int2
gg = int(input("Guess? :"))
listt = []
counter = 0
wronggg = 0
for i in range(1,6):
        if gg == aa:
            #counter = counter+ 1
            pass
            #listt.append('y')
        elif guess != aa and wronggg< 3:
            wronggg +=1
            print('wrong answer')
            guess = int(input(f"{int1} * {int2} = "))
        else:
            break
    #print(i)
    #print((listt))
    #print(len(list))
    #print(counter)


有人可以澄清为什么这不能正确打印以及我可以做什么来在循环结束时打印预期值吗?我想了解“为什么”,以便我可以学习。预先感谢您。

即使为我指明正确的方向也会有帮助。

python loops if-statement counter
1个回答
0
投票

您需要确保您的代码在您期望的位置退出。

您的代码当前如下所示:

Loop five times

If the answer is correct, keep looping (pass)

If the answer is incorrect and there have been three or fewer wrong attempts, log a wrong attempt and have the user try again. 

If the answer has more than three wrong attempts and it is still wrong, break out of the loop.

乍一看我会说你需要

break
而不是
pass
在正确的步骤。

int1 = random.randrange(1, 3)
int2 = random.range(1,3)
aa = int1 * int2
gg = int(input("Guess? :"))
listt = []
counter = 0
wronggg = 0
for i in range(1,6):
        if gg == aa:
            counter += 1
            listt.append('y')
            break  # note the placement comes after listt.append
        elif wronggg < 3:
            wronggg += 1
            print('wrong answer')
            guess = int(input(f"{int1} * {int2} = "))
        else:
            break
    print(i)
    print(listt)
    print(len(list))
    print(counter)
© www.soinside.com 2019 - 2024. All rights reserved.