-2
#this is my very first python attempt
#Getting the name
print ""
name = raw_input("Hello, adventurer. Before we get started, why don't you tell me your name.")
while name in (""):
    print "Sorry, I didn't get that."
    name = raw_input("What is your name?")

if len(name) > 0:
    print ""
    print "%s? Good name! I hope you are ready to start your adventure!" % name

#getting right or left
print ""
print "Well %s, we are going to head north along the river, so get a move on!" % name
print ""
question = "As you head out, you quickly come across a fork in the road.  One path goes right, the other goes left. Which do you chose: right or left?"
lor = raw_input(question).strip().lower()
while not "left".startswith(lor) and not "right".startswith(lor):
    print "That's not a direction."
    lor = raw_input(question).strip().lower()

if len(lor) > 0:
    if "left".startswith(lor):
        print "You went left"
    elif "right".startswith(lor):
        print "You went right"
else:
    print "That's not a direction."
    lor = raw_input(question).strip().lower()

私が間違っていることを理解していません。このコードを実行すると、question. raw_input として。何も入力しないと、「それは方向ではありません」と正しく表示され、もう一度質問が表示されます。ただし、次に何かを入力すると、何を入力しても空白の回答が表示されます。ループが継続しないのはなぜですか?

4

2 に答える 2

4

問題は、それ"left".startswith("")が True を返すことです。つまり、最初に応答しないと、( で"left"始まるため"") while ループから抜け出し、if/else に進むことになります。

if ステートメントでは、の値がloris である""ため、elseフォークに行き着きます。その時点で再度質問が行われますが、ユーザーが応答すると、新しい値の は何も行われませんlor

while ループを編集して読むことをお勧めします。

while lor == "" or (not "left".startswith(lor) and not "right".startswith(lor)):

このようにして、答えが「左」または「右」で始まり、空の文字列でない場合にのみ、while ループから抜け出します。

elseまた、何も役に立たないため、最終ステートメントを削除する必要があります:)

于 2013-06-11T20:58:16.773 に答える
2

"left".startswith(lor)逆にする必要があります。lor.startswith('left')
同じことが にも当てはまり"right".startswith(lor)ます。

于 2013-06-11T21:01:44.473 に答える