【问题标题】:While loop not endingWhile循环没有结束
【发布时间】:2015-02-17 21:54:23
【问题描述】:
def getStocks():
    stockNames = []
    stockPrices = []
    done = 0
    while done != 1:
        stock = input('Enter Stock symbol: ')
        if stock == 'done':
            done = 1

        else:
            price = int(input('Enter Price of Stock: '))
            print("")
            stockNames.append(stock)
            stockPrices.append(price)
    return stockNames, stockPrices

问题是“输入股票代码:”即使在用户键入“完成”后仍出现,我如何才能让无限循环在此时终止?我尝试使用 break 但它没有提供我正在寻找的结果

【问题讨论】:

  • 你输入的是'done'还是done?如果没有包含引号,则不会触发中断条件。
  • 你用的是python 2.7吗?
  • 这很奇怪,我又跑了一遍,似乎还可以。问题出在我没有提供的代码中的“main()”函数中。谢谢。

标签: python windows function loops while-loop


【解决方案1】:

而不是input 使用raw_input 它将解决问题

def getStocks():
    stockNames = []
    stockPrices = []
    done = 0
    while done != 1:
        stock = raw_input('Enter Stock symbol: ')
        if stock == 'done':
            done = 1

        else:
            price = int(input('Enter Price of Stock: '))
            print("")
            stockNames.append(stock)
            stockPrices.append(price)
        return stockNames, stockPrices

python 版本:2.7+

【讨论】:

    【解决方案2】:

    您可能想要raw_input(),因为input() 实际上会尝试评估它返回的表达式。

    【讨论】:

      猜你喜欢
      • 2017-04-03
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 2014-03-15
      • 2017-04-18
      • 2018-09-01
      相关资源
      最近更新 更多