无法中断while循环,该循环正在搜索列出的值

2024-10-04 05:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我很肯定我做错了,但我不知道怎么做。我本来打算用一个数组,但不知道怎么用。我对Python不那么毛茸茸的一面还很陌生(在学校学习) 如果我能帮上忙,我会非常感激的。你知道吗

所以我试着练习设计和编程,我想用这样的图表来比较一下神奇宝贝的类型:

http://i.kinja-img.com/gawker-media/image/upload/s--6gT1hiPW--/fxovveduxtomv4srnqk1.png

所以,我的想法是输入类型,然后输出它的优点和缺点。但就我的一生而言,我无法通过选择一种类型的初始阶段。你知道吗

以下是我的前几句台词:

Elements = "Normal","Fire","Water","Grass","Electric","Bug","Flying","Ground","Rock","Posion","Dragon","Dark","Fairy","Psychic","Steel","Fighting","Ice"
type1 = input("Please input a type")
while type1 != Elements:
    type1 = input("Please input a real type")

print("Good Job, this part works!") # But it doesn't get to this point...

我很抱歉这太糟糕了,但每个人一开始都很天真,对吧? 提前谢谢你能给我的任何帮助!你知道吗


Tags: http类型inputtype编程图表数组elements
3条回答

我想你应该检查type1是否在元素中,而不是是否等于它。元素是一个字符串元组,类型1将只是一个字符串。这两样东西永远不会相等。你知道吗

您可以使用in关键字测试它是否在中,如下所示:

while( type1 not in Elements ):
    type1 = raw_input( "Enter a valid type" )

首先,您需要一个列表来存储所有类型,然后反复请求用户输入,然后将输入与预定义的元素列表进行匹配,如果找到匹配项,则中断while循环,否则继续,这就是本例中要遵循的简单算法。你知道吗

elements = ["Normal","Fire","Water","Grass","Electric","Bug","Flying","Ground","Rock","Posion","Dragon","Dark","Fairy","Psychic","Steel","Fighting","Ice"]
#Initialized the various types in a list.
while True:    #Infinite loop
    type1 = input("Please input a real type")   #Taking input from the user
    if type1 in elements:    #Checking if the input is already present in the given list of elements.
        print("Good Job, this part works!")
        break

你想看看一个词是否等于一个列表,这永远不会是真的,你想看看这个词是否在列表中

elements = "Normal","Fire","Water","Grass","Electric","Bug","Flying","Ground","Rock","Posion","Dragon","Dark","Fairy","Psychic","Steel","Fighting","Ice"
type1 = input("Please input a type")
while type1 not in elements:
    type1 = input("Please input a real type")

print("Good Job, this part works!") # But it doesn't get to this point...

相关问题 更多 >