我正在尝试制作一个可以添加,删除并查看用户输入的菜肴的程序。但是,看起来很简单,我的while循环遇到了问题。当我键入add时,我可以将项目添加到列表中,但是,当我键入view时,addDish函数将继续循环播放。我以为我用if语句修复了它,但是缺少了某些东西...!
dish_list = []
user_input = ''
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
user_input = input("Please enter a command: ")
while True:
if user_input == '':
user_input = input("Please enter a command: ")
elif user_input == 'add':
addDish(dish_list, user_input)
elif user_input == 'view':
viewDish(dish_list)
答案 0 :(得分:2)
您应该调用一个在处理完先前的输入后要求用户输入的函数,而不是使用while循环。
dish_list = []
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
def get_input():
user_input = input("Please enter a command: ")
if user_input == 'add':
addDish(dish_list, user_input)
elif user_input == 'view':
viewDish(dish_list)
getInput()
getInput()
答案 1 :(得分:1)
更清洁:
dish_list = []
def add_dish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
def view_dish(dish_list):
# for dish in dish_list:
# print(dish)
print('\n'.join(dish_list))
while True:
user_input = input("Please enter a command: ")
if user_input == 'add':
add_dish(dish_list)
elif user_input == 'view':
view_dish(dish_list)
else:
print("Unknown command %s" % user_input)
答案 2 :(得分:0)
您的变量user_input永远不会恢复为空,因此您永远都不能输入新命令,因为它只接受您输入到user_input的最后一个条目,这就是在addDish函数中读取的菜式。此外,您对addDish的调用还有一个额外的参数。我还建议将所有内容都放在主要方法中。
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
def main():
dish_list = []
while True:
user_input = ''
if user_input == '':
user_input = input("Please enter a command: ")
elif user_input == 'add':
addDish(dish_list)
elif user_input == 'view':
viewDish(dish_list)
main()
答案 3 :(得分:0)
以下是上述代码段的固定版本:
def addDish(dish_list):
user_input = raw_input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for dish in dish_list:
print(dish)
dish_list = []
while True:
user_input = raw_input("Please enter a command: ")
if user_input == 'add':
addDish(dish_list)
elif user_input == 'view':
viewDish(dish_list)
elif user_input == 'exit':
print('Over!')
break
else:
print('Wrong entry. Retry...')
执行输出:
$python so.py
Please enter a command: add
Please type the dish you want: Bread
Please enter a command: add
Please type the dish you want: Burger
Please enter a command: view
Bread
Burger
Please enter a command: foo
Wrong entry. Retry...
Please enter a command: exit
Over!
$