【问题标题】:Create a program without infinite loop创建一个没有无限循环的程序
【发布时间】:2021-09-17 18:28:21
【问题描述】:

我必须创建一个程序,将所有从 1 到 n 的数字按照一个等式相加。然后我想在total_bis 列表中添加这些迭代的总数,并让它再次询问用户多次迭代并重新计算它们。无需进入无限循环(这就是发生在我身上的事情)。当用户发出完成命令时,程序结束。

谢谢。

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)

【问题讨论】:

  • 您的意思是将while True: 移到程序顶部吗?
  • 一旦你的while 循环循环,你将永远无法退出,因为它正在测试循环不变的n_iteraciones(它永远不会在循环内改变)。所以要么在循环内更改n_iteraciones,要么更改退出测试。
  • 另外,n_iteraciones != 0 行没有任何作用。它将n_iteraciones0 进行比较,检查是否不相等,然后丢弃比较结果而不使用它。因此,要么将该行更改为有用的内容,要么将其删除。

标签: python list while-loop infinite-loop


【解决方案1】:

您可以在循环中请求用户输入。如果用户改为选择 q,则循环中断:

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")

【讨论】:

    【解决方案2】:

    我认为这是您想要实现的目标:

    while True:
    
        total_bis = []
        total = 0
        n_iteraciones = int(input('Especifique el numero de iteraciones:'))
    
        if n_iteraciones != 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')
        else:
            break
    

    【讨论】:

      猜你喜欢
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多