【问题标题】:While loop, how do I condition for when input equals nothing?While循环,我如何判断输入何时不等于任何内容?
【发布时间】:2022-11-13 04:40:26
【问题描述】:

创建一个程序来跟踪购物清单中的项目。程序应该一直询问新项目,直到没有输入任何内容(没有输入,然后按 enter 键)。然后程序应该显示完整的购物清单

如何编写条件以使其起作用?

我正在编写的代码如下所示:

x = []

i = 0
while i != '':
    x.append(input('what u want?'))
    i = i + 1

print(x)
```
`

【问题讨论】:

    标签: python while-loop conditional-statements


    【解决方案1】:

    查找用户输入的len 并检查是否相应

    x = []
     
    while 1:
        ask= input('what u want?')
        if len(ask)>0:
            x.append(ask)
    
        else:
            print("Good bye")
            break
       
    print(x)
    

    输出 #

    what u want?rice
    what u want?sugar
    what u want?
    Good bye
    ['rice', 'sugar']
    

    【讨论】:

      【解决方案2】:

      最新的 Python:

      items = []
      while item := input('what u want?'):
          items.append(item)
      print(items)
      

      不支持的旧 Python :=

      items = []
      while True:
          item = input('what u want?')
          if not item: break
          items.append(item)
      print(items)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-08
        • 2011-05-25
        • 1970-01-01
        • 2020-03-07
        • 2016-10-28
        • 2020-08-05
        • 1970-01-01
        • 2014-06-26
        相关资源
        最近更新 更多