gpt4 book ai didi

python - 循环只运行一次

转载 作者:太空宇宙 更新时间:2023-11-03 14:29:57 25 4
gpt4 key购买 nike

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

#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

最佳答案

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

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

关于python - 循环只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47365898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com