如何重复 while 循环但不从头开始

发布于 2025-01-18 09:50:14 字数 651 浏览 0 评论 0原文

现在,我已经学习了python大约2周了。我想解决此代码。

number = 0
while True:
    input_1 = int(input('First Number: '))
    number += 1
    if input_1 == 1:
        input_2 = int(input('Second Number: '))
        number += 2
        if input_2 == 2:
            input_3 = int(input('Third Number: '))
            number += 3
            if input_3 == 3:
                break
            else:
                number -= 6
                continue
        else:
            number -= 3
            continue

    else:
        number -= 1
        continue
print(number)

因此,基本上,我想在循环时重复启动,例如当im input_2中的im和条件进入时,我希望代码再次循环到Input_2。感谢您的所有答案

right now i have been learning python like 2 weeks. and i want to solve this code.

number = 0
while True:
    input_1 = int(input('First Number: '))
    number += 1
    if input_1 == 1:
        input_2 = int(input('Second Number: '))
        number += 2
        if input_2 == 2:
            input_3 = int(input('Third Number: '))
            number += 3
            if input_3 == 3:
                break
            else:
                number -= 6
                continue
        else:
            number -= 3
            continue

    else:
        number -= 1
        continue
print(number)

so basically i want to repeat while loop not for beginning, as example when im in input_2 and the condition get in to else, i want the code is looping to input_2 again. thanku for all of ur answer

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

压抑⊿情绪 2025-01-25 09:50:14

因为您所有的循环都具有相似的行为,所以最好的方法是根据当前阶段循环循环,而不是嵌套循环:

stage = 1
final_stage = 3
prompts = ['First Number: ', 'Second Number: ', 'Third Number: ']
increment = [1, 2, 3]
decrement = [1, 3, 6]

number = 0
while True:
    input_num = int(input(prompts[stage - 1]))
    number += increment[stage - 1]
    if input_num == stage:
        if stage == final_stage:
            break

        stage += 1
    else:
        number -= decrement[stage - 1]

print(number)

Because all your loops share similar behavior, the best approach to this would be to loop through variables based on the current stage rather than have nested loops:

stage = 1
final_stage = 3
prompts = ['First Number: ', 'Second Number: ', 'Third Number: ']
increment = [1, 2, 3]
decrement = [1, 3, 6]

number = 0
while True:
    input_num = int(input(prompts[stage - 1]))
    number += increment[stage - 1]
    if input_num == stage:
        if stage == final_stage:
            break

        stage += 1
    else:
        number -= decrement[stage - 1]

print(number)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文