【问题标题】:the loop runs only once循环只运行一次
【发布时间】:2018-05-02 03:08:08
【问题描述】:

我的代码有问题。该循环仅运行一次,对应于用户输入的数字。感谢您的帮助。

#create an empty list and ask the user how many items they want to add  
# take the items the user entered and add it to the empty list.
print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user entered.
    items = input (">") #taking the items from the user 
    empty = ""
    if (items == empty):# checking if the user added nothing
        print("no items added")
    break
else:
    fitems.append(items) #add the list of items the user entered to the 
empty list
    print("hello here is your food items: \n",fitems) #output user items

【问题讨论】:

  • 无论for 循环中发生什么,break 的缩进保证它在第一次迭代后中断。也许您打算将其缩进到 if 条件内。
  • 您的break 命令位于for 循环内的主级别,因此它肯定会在第一次执行循环并结束时执行。尝试将break 语句再缩进一级,将其放在前面的if 语句中,看看是否能解决您的问题。

标签: python python-3.x


【解决方案1】:

这会起作用,因为你没有在 for 循环中缩进“break”

#create an empty list and ask the user how many items they want to add  
 # take the items the user entered and add it to the empty list.
 print("enter the number of items")
 x = int(input(">")) #take number of user input with the type int
 print("thanks")
 print("enter your food items")
 fitems = [] # empty list
 for i in range(x): #range to limit the number of iteration the user entered.
    items = input (">") #taking the items from the user 
    empty = ""
    if (items == empty):# checking if the user added nothing
       print("no items added")
       break #your error corrected
    else:
       fitems.append(items) #add the list of items the user entered to the 
  empty list
    print("hello here is your food items: \n",fitems) #output user items

【讨论】:

  • 效果很好,但我希望打印语句在用户输入项目后打印所有内容,而不是打印一个并最终打印所有内容。
【解决方案2】:

我认为你的代码中唯一的问题是标识,所以你应该这样改变:

print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user ente red.
    items = input (">") #taking the items from the user 
    empty = ""
    if (items == empty):# checking if the user added nothing
        print("no items added")
        break
    else:
        fitems.append(items) #add the list of items the user entered to the 

print("hello here is your food items: \n",fitems)

【讨论】:

  • 效果很好,但我希望在用户没有输入任何内容后不要打印最后一个打印语句
【解决方案3】:

您的代码中缺少一些缩进,并且还有一些其他错误。这是(我认为)正确的代码:

print("enter the number of items")
x = int(input(">"))
print("thanks")
print("enter your food items")
fitems = []
for i in range(x):
    items = input(">").strip() # there was a space before first bracket in your code, it's possible to have it there, but this is better
    # edit: added .strip(), it removes extra whitespace from beginning and end
    if items == "": # no need to create empty string variable, compare simply with empty string,
    # edit: you can also use 'if not items:', because empty string evaluates to false
        print("no items added")
        break # break only if nothing added, so indent break to be only executed if empty
    fitems.append(items) # you don't have to have else here, break ends the loop, so this is not executed then
print("hello here are your food items: \n",fitems) # remove 1 indent, print only after loop ended

【讨论】:

  • if (items == ""): 有不必要的括号,在大多数情况下,最好只检查一些虚假的东西。 if not items: 更 Pythonic。
  • 效果很好,但我希望打印语句在用户输入项目后打印所有内容,而不是打印一个并最终打印所有内容。
  • @roganjosh 括号在那里是因为我最近在写一些 JS。至于not items,我爸爸(python 程序员)说我滥用了这种行为,我应该使用比较,因为它对任何阅读代码的人都是透明的。
  • @JonathanAkweteyOkine 我不确定我是否理解你...现在,代码在循环结束后打印所有项目。如果您希望它在每次用户添加项目时打印所有项目,请在最后一个 print 语句之前添加一个缩进级别(4 个空格),以便它进入循环并在每次迭代中执行。
  • @JonathanAkweteyOkine 我知道您是 Stack Overflow 的新手,所以这里有一个提示 - 如果这个(或任何其他,当然)答案解决了您的问题并且您认为它是最好的,请将其标记为已接受(打钩)。见What does it mean when an answer is "accepted"?
【解决方案4】:

首先,break 语句和 else 语句的意图不正确。此外,当您使用 .append() 时,您应该添加一个 i+=1 来循环 x 用户输入的内容。

这将起作用:

for i in range(x): #range to limit the number of iteration the user entered.
    items = input (">") #taking the items from the user
    empty = ""
    if (items == empty):# checking if the user added nothing
        print("no items added")
        break
    else:
        fitems.append(items) #add the list of items the user entered to the
        i += 1

【讨论】:

    【解决方案5】:

    如果没有输入,这将导致不打印:

    print("enter the number of items")
    x = int(input(">")) #take number of user input with the type int
    print("thanks")
    print("enter your food items")
    fitems = [] # empty list
    for i in range(x): #range to limit the number of iteration the user entered.
        items = input (">") #taking the items from the user 
        empty = ""
        if (items == empty):# checking if the user added nothing
            print("no items added")
            break
        else:
            fitems.append(items) #add the list of items the user entered to the\
                                                                    empty list
    if len(fitems)==0:
        pass
    else:
        print("hello here is your food items: \n",fitems)
    

    【讨论】:

      【解决方案6】:

      我冒昧地做了一些改变。试试这个:

      # create an empty list and ask the user how many items they want to add  
      # take the items the user entered and add it to the empty list.
      
      fitems = []
      
      # Define valid input for amount of items
      valid = [str(i) for i in range(1,10)] # ["1","2"...."9"]
      
      # If item is not in the list of valid, continue asking
      while True:
          print("enter the number of items [1-9]")
          x = input(">")
          if x in valid:
              break
      
      # Convert to int
      itemamount = int(x)
      print("thanks\nenter your food items")
      
      # Now ask for inputs using while > 0 and remove itemamount in each loop
      while itemamount > 0:
          while True:
              item = input (">")
              if item:
                  break
              print("Blank input")
          fitems.append(item)
          itemamount-=1
      
      print("hello here is your food items: ")
      for ind,i in enumerate(fitems,1):
          print("{}. {}".format(ind,i))
      

      【讨论】:

        猜你喜欢
        • 2011-11-02
        • 2013-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-29
        • 2021-06-15
        • 2014-12-07
        • 1970-01-01
        相关资源
        最近更新 更多