次のコードは、Lukeという名の英雄を作成します。ルークは、彼が見つけた食物のテーブルからリンゴやハムを食べたいかどうかを選択する必要があります。Python:答えが正しくない場合にクラスを使用してプロンプトを再入力する
ユーザーが「apple」または「ham」を選択しない場合、「apple」または「ham」を選択するようにユーザーに再質問できるようにするにはどうすればよいですか?
私はクラス内でこれを行う方法を学びたいと思います。私は他の中でprintステートメントの下で何かする必要があるかのように感じますが、self.food()
はstrが呼び出し可能でないというエラーにつながります。
class Hero():
def __init__(self, name):
self.name = name
self.health = 100
self.food = raw_input("You encounter a table full of apples and ham. Which do you eat first? ")
def eat(self):
x = True
while x == True:
if (self.food == 'apple'):
self.health -= 100
print "%s has %d health points" % (self.name, self.health)
x = False
elif (self.food == 'ham'):
self.health += 20
print self.health
print "%s has %d health points" % (self.name, self.health)
x = False
else:
print "Incorrect. Please try again"
break
char_1 = Hero("Luke")
char_1.eat()
編集:アレックスの助けを借りた後
変更。
class Hero():
def __init__(self, name):
self.name = name
self.health = 100
def eat(self):
while self.health > 0:
food = raw_input("You encounter a table full of apples and ham. Which do you eat first? ")
if (food == 'apple'):
self.health -= 10
print "%s has %d health points" % (self.name, self.health)
elif (food == 'ham'):
self.health += 20
print self.health
print "%s has %d health points" % (self.name, self.health)
else:
print "Incorrect. Please try again"
char_1 = Hero("Luke")
char_1.eat()
ありがとうアレックス! whileループがイニシャライザメソッドでどのように動作するのかは分かりませんでした。そのため、代わりに私のraw_inputステートメントをwhileの条件の下でeatメソッドで移動し、それが動作しました。 "x"変数名ポインタをありがとう。私は今夜練習していて、それについて本当に考えなかった。しかし、私は習慣に入るだろう! – staredecisis