简体   繁体   中英

how to repeat while loop but not from beginning

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM