【问题标题】:While loop not working properly when condition is met满足条件时,while循环无法正常工作
【发布时间】:2021-12-25 19:01:08
【问题描述】:

我正在尝试将项目附加到列表中,当我输入单词“退出”时,循环应该停止,然后打印我在列表中的项目,但循环继续并仍然问我关于循环,我认为不应该发生。

itemName = ''
itemPrice = '0.0'
while itemName != 'quit'.lower().strip():
    itemName = input('What item would you like to add?')
    items.append(itemName + ' $' + itemPrice)
    itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
    print(item) 

【问题讨论】:

  • 我把它放在有人用空格或小写字母输入“退出”这个词的情况下。
  • 您似乎希望循环在有人键入“退出”时立即停止,但这不是它的工作原理。如果没有breakcontinue 语句,整个循环体都会执行。
  • 但是您在文字字符串'quit' 上调用.lower().strip(),这是没有用的,因为它显然已经小写并被剥离了。

标签: python while-loop append


【解决方案1】:

我发现一个问题,您的.lower().strip 放在错误的一侧。 另外,我建议使用break,这样如果输入了退出,您的代码就不会询问价格。

items=[]
itemName = ''
itemPrice = '0.0'
while True:
    itemName = input('What item would you like to add?')
    if itemName.lower().strip() == 'quit':
      break
    items.append(itemName + ' $' + itemPrice)
    itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
    print(item) 

【讨论】:

    【解决方案2】:

    代码仅在询问两个问题后检查您是否编写了退出。此外,您应该将.lower().strip() 放在input() 函数之后。您的代码总是小写并去除字符串'quit'。您可以在第一个问题之后放置一个 if 语句并加上一个换行符,以防止您的代码在您为第一个问题输入 'quit' 后询问您第二个问题。

    【讨论】:

      【解决方案3】:

      试着研究一下。

      items = []  # storage
      totalPrice = 0.0
      
      while True:
          itemName = input('What item would you like to add? ')
          if itemName.lower() == 'quit':
              break
      
          itemPrice = input(f'What is the price of {itemName}? ')  # ask the price before saving the item
          if itemPrice.lower() == 'quit':
              break
      
          totalPrice += float(itemPrice)  # convert str to float
          items.append(f'{itemName} $ {itemPrice}')  # Save to storage
      
      
      print('items:')
      for item in items:
          print(item)
      
      print()
      print(f'total price: $ {totalPrice}')
      

      输出

      What item would you like to add? shoes
      What is the price of shoes? 600.75
      What item would you like to add? bag
      What is the price of bag? 120.99
      What item would you like to add? quit
      items:
      shoes $ 600.75
      bag $ 120.99
      
      total price: $ 721.74
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-12
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 1970-01-01
        • 2019-01-29
        相关资源
        最近更新 更多