2017-09-06 10 views
0

私は2番目の入力を第1の方向に入力するプログラムを作成しています& 2番目のステップは1行で、split( '')を使ってこれを実行しますwhileループではwhileループ 彼はちょうど空白行を入力し、終了するが、それはなぜ知らないが起こっていないエントリより入力したくない...これは私のコードPython - リスト内のインデックスエラー

while True: 
movement = input().split(' ') 
direction = movement[0].lower() 
step = int(movement[1]) 
if movement != '' or movement != 0: 

    if direction == 'up' or direction == 'down': 
     if y == 0: 
      if direction == 'down': 
       y -= step 
      else: 
       y += step 
     else: 
      if direction == 'down': 
       y -= step 
      else: 
       y += step 
    elif direction == 'left' or direction == 'right': 
     if x == 0: 
      if direction == 'right': 
       x -= step 
      else: 
       x += step 
     else: 
      if direction == 'right': 
       x -= step 
      else: 
       x += step 
else: 
    current = (x, y) 
    print(original) 
    print(current) 
    break 

ですが、私は銀行の入力を入力することは、このメッセージ

Traceback (most recent call last): 
File "C:/Users/Zohaib/PycharmProjects/Python Assignments/Question_14.py", 
line 04, in <module> 
step = int(movement[1]) 
IndexError: list index out of range 
を示しています
+1

*しかし、ユーザーは空白行を入力して終了するだけです。だから、空行に 'movement.split()'を使用しようとするとどうなりますか?結果リストにいくつの要素が作成されますか? –

+0

サイドトラッキングは少しですが、実行するコードがifとelseの両方で同じであるため、なぜx == 0の文を追加する必要がありますか? – chngzm

+0

空白行を入力してループを終了します。 –

答えて

0

あなたのリストのlen()を実行することができます。あなたがmoを取得しない場合if文の中に)(ラインをあなたの方向=運動[0] .lowerを動かし例

if len(movement) == 0: 
    # Your logic when you don't have any input 
    pass 
else: 
    # Your logic when you have at least one input 
    pass 
+0

このケースでは機能しません。 '' print(len( "" split( ''))) ''は '' 1''です(リストには要素が1つあります。 –

+0

私はこの条件を使用しますlen(movement)== 1:break –

0

のために、あなたが任意のロジックを作るvement、これは彼らが実行できるようになります場合にのみ運動!=「」は、以下を行う必要がありif文を変更してください。それ以外の場合は、常に ''と0にすることはできません。

また、if文で比較すると、ちょうど動きを比較する。 ( '' .split()は[]を返します)

while True: 

    movement = input() 
    if movement != '' and movement != '0': 
     movement = movement.split() 
     direction = movement[0].lower() 
     step = int(movement[1]) 
     del movement[1] 
     if direction == 'up' or direction == 'down': 
      if y == 0: 
       if direction == 'down': 
        y -= step 
       else: 
        y += step 
      else: 
       if direction == 'down': 
        y -= step 
       else: 
        y += step 
     elif direction == 'left' or direction == 'right': 
      if x == 0: 
       if direction == 'right': 
        x -= step 
       else: 
        x += step 
      else: 
       if direction == 'right': 
        x -= step 
       else: 
        x += step 
    else: 
     current = (x, y) 
     print(original) 
     print(current) 
     break 
関連する問題