将用户输入与字典中的键进行比较

时间:2017-12-04 00:12:10

标签: python loops dictionary for-loop if-statement

我正在尝试将用户输入与字典中的键,magicSpells进行比较。但是,当我尝试运行此代码时,for循环默认为else语句,而不是按照我打算执行的操作。我该如何调整此代码?

谢谢。

spellClassMage = raw_input("What type of mage? ").lower() 

for userinput in spellClassMage:
            if userinput in magicSpells: 
                player[name] = randHealthMage, spellClass, score    
            else:
                print("That isn't a listed type!")

2 个答案:

答案 0 :(得分:1)

我找到了解决问题的方法。我不得不将字典中的键更改为全部大写以匹配附加到spellClassMage的.upper():

spellClassMage = raw_input("What type of mage? ").upper() 

userinput = spellClassMage.split()

for word in userinput:
            if word in magicSpells: 
                player[name] = randHealthMage, spellClass, score    
            else:
                print("That isn't a listed type!")

答案 1 :(得分:0)

这应该适用于if语句。但我真的不知道,你在哪里使用Rest,因为输入似乎不会影响其他变量。

spellClassMage = raw_input("What type of mage? ").lower() 

if spellClassMage in magicSpells: 
    player[name] = randHealthMage, spellClass, score    
else:
    print("That isn't a listed type!")

另外,如果'玩家'是一个词典,你应该试试这个:

player[name] = [randHealthMage, spellClass, score]

哦,还有一件事。如果处理输入,那可能是错误的,while循环很方便。所以它在以后的程序中不会导致错误。

while True:
    spellClassMage = raw_input("What type of mage? ").lower() 

    if spellClassMage in magicSpells: 
        player[name] = [randHealthMage, spellClass, score]
        break
    else:
        print("That isn't a listed type, try again!")
相关问题