我有以下代码:
def main():
list=["chocolate", "jelly", "biscuits"]
eat=input("What do you wanna eat?")
for i in list:
if list.index(eat)==eat:
break
else:
break
print("We have that in tray:", list.index(eat))
main()
在VB.Net中,这在For循环中很容易实现,这是一种惯用的方法。为什么不在这里?另外,这并不是stackoverflow的另一个问题的重复,在这个问题中,用户提供了做类似事情的替代方法/pythonic建议
出于教学目的,我需要使用For循环,并更正上面给出的结构
如果用户输入的不是列表中的内容,我如何添加条件逻辑来打印“该项目不在列表中”。我正在寻找最简单的修复我的原始代码
我确实尝试了以下方法,但结果是出现了逻辑错误。有一个解决方案
试试#1:
def main():
list=["chocolate", "jelly", "biscuits"]
eat=input("What do you wanna eat?")
for i in list:
if list.index(eat)==eat:
break
else:
print("that is not in the list")
print("We have that in tray:", list.index(eat))
main()
错误:
>>>
What do you wanna eat?jelly
that is not in the list
that is not in the list
that is not in the list
We have that in tray: 1
>>>
尝试2
def main():
list=["chocolate", "jelly", "biscuits"]
eat=input("What do you wanna eat?")
for i in list:
if list.index(eat)==eat:
break
else:
break
print("that is not in the list")
print("We have that in tray:", list.index(eat))
main()
错误:
>>>
What do you wanna eat?jelly
that is not in the list
We have that in tray: 1
>>>
试试#3:
def main():
list=["chocolate", "jelly", "biscuits"]
eat=input("What do you wanna eat?")
for i in list:
if list.index(eat)==eat:
break
elif list.index(eat)!=eat:
print("that is not in the list")
print("We have that in tray:", list.index(eat))
main()
错误:
>>>
What do you wanna eat?jelly
that is not in the list
that is not in the list
that is not in the list
We have that in tray: 1
>>>
在这里:
使用
enumerate
相关问题 更多 >
编程相关推荐