2017-12-04 18 views
-1

ユーザー入力を辞書内のキー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!") 
+0

'spellClassMage'がでユーザ入力のための文字列を、それを超えるので、あなたのループ('です... ')は単一の文字を返します。それはあなたの期待ですか? – donkopotamus

+0

ああ、いいえ。私は単語全体を返そうとしています。ユーザーが「水」を入力すると、水と辞書を比較します。 – Ken

+0

処理したい入力の例を考えてみましょう。たとえば、単一の単語だけですか、複数のスペースで区切られた単語などです。 – donkopotamus

答えて

0

これはif-statementで有効です。しかし、入力が他の変数に影響を与えていないように、残りの部分と一緒にどこに行くのかはわかりません。 'プレイヤーが' dictのであれば

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!") 
+0

他の変数はコードに貼り付けられませんが、私のプログラムには目的があります。また、player [name]の値を角括弧で囲んだ方が良いのはなぜですか? – Ken

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!") 
関連する問題