Search code examples
pythonlistwhile-loopinfinite-loop

Create a program without infinite loop


I have to create a program that adds all the numbers from 1 to n following an equation. Then I want to add the total for those iterations in the total_bis list and have it again ask the user for a number of iterations and recalculate them. Without going into an infinite loop (which is what is happening to me). When the user gives the order to finish, the program ends.

Thanks.

n_iteraciones = int(input('Especifique el numero de iteraciones:'))

total_bis = []
total = 0
for elem in range(1, n_iteraciones + 1):
    total += elem * (elem +1) /2
    total_bis.append(total)
    
print(f'total: {total} para {n_iteraciones} iteraciones')

while True:
    n_iteraciones != 0
    print(n_iteraciones)
    
    if n_iteraciones == 0:
        break

n = len(total_bis)
print(n)

Solution

  • You can ask for the user input inside a loop. If the user selects q instead, the loop breaks:

    while True:
        n_iteraciones = input("Especifique el numero de iteraciones (pulse q para salir): ")
        if n_iteraciones == "q":
            break
    
        total_bis = []
        total = 0
        for elem in range(1, int(n_iteraciones) + 1):
            total += elem * (elem + 1) / 2
            total_bis.append(total)
    
        print(f"total: {total} para {n_iteraciones} iteraciones")