【问题标题】:Not sure why loop does not break不知道为什么循环不会中断
【发布时间】:2013-10-22 17:57:20
【问题描述】:

所以我在这里遗漏了一些东西。当用户用完他们所拥有的所有积分并被提示他们是否想向池中添加更多积分时,并且用户选择“n”时,他们会不断被提示向池中添加更多积分。这不应该发生。我试过摆弄休息的位置,但无济于事。当用户输入“n”时,整个循环应该停止。任何帮助,将不胜感激。谢谢。

# Char Creator- pool of 30 pts, spend on Str, Health, Wisdom, Dex
# Spend points in pool on attr, take points and put them back into pool

pool = 30

attr = {'Strength' : 0, 'Health' : 0, 'Wisdom' : 0, 'Dexterity' : 0}

while True:
    while pool > 0:
        print('\t\t Time to spend some points! You have', pool, 'to spend')
        spend = input('Where would you like to spend your points?')
        if spend in attr:
            amount = int(input('How many points would you like to spend?'))
            if amount > pool:
                print('You do not have that many points! You have', pool, 'points!')
            else:
                attr[spend] += amount
                pool -= amount
                print(attr)
        else:
            print('Not a valid input. Please correct.')

    print('\t\t You have no more points! Add some to the pool!')

    while pool == 0:
        confirm = input('Would you like to add points back into the pool?')
        if confirm == 'y':
           take =  input('Where would you like to take points from?')
           if take in attr:
                number = int(input('How many points would you like to take?'))
                if attr[take] >= number:
                    pool += number
                    attr[take] -= number
                    print ('There are now', pool, 'points remaining') 
                elif attr[take] < number:
                    print('You dont have enough points to do that! You have', attr[take], 'points in', take)
           else:
               print('Please make a valid selection.')
        elif confirm == 'n':
            print('Goodbye!')

    break

【问题讨论】:

  • 看起来你的一些 while 循环应该是 if 语句或省略
  • @cmd:由于print('Not a valid input. Please correct.')print('Please make a valid selection.') 路径,它们是while 循环

标签: python python-3.x while-loop break


【解决方案1】:

您的break 没有缩进到elif 语句中(或在内部while 循环中):

        elif confirm == 'n':
            print('Goodbye!')

    break

break前面再添加两个标签。

为了让你的程序可以在跳出内循环后结束,你可能还想改变

while True:

while points > 0:

【讨论】:

  • 感谢您的回复 - 显然它被认为是一个愚蠢的问题。我只是一个初学者。我自己试过了,但由于某种原因,仍然提示用户向池中添加更多点。
  • @Zack:那是因为你的break 语句只跳出了内部的while循环,而不是外面的循环。将while True: 行更改为while points &gt; 0,您将解决该问题。您还必须在print ('There are now', pool, 'points remaining') 之后添加一个break 行,这样您才能摆脱该循环。
猜你喜欢
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 2020-07-13
相关资源
最近更新 更多