2017-09-06 216 views
0

我正在寫程序,需要輸入2個第一個方向&第二個是在一行中的步驟,我通過使用split('')這樣做所有這些輸入需要在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

sidetrack有點,但爲什麼你需要添加一個if x == 0語句,因爲要執行的代碼在if和else中都是相同的(對於y也是一樣的) – chngzm

+0

我想當用戶沒有更多條目時他只需輸入空白行並循環終止 –

回答

0

你可以做你的清單len(),如果你沒有得到任何mo vement你做任何的邏輯,例如

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

移動你的方向=移動[0] .lower()進線if語句,這將讓他們只運行,如果運動!=「」,你需要改變你的if語句,否則它永遠是真的,因爲移動不能同時爲''和0

另外,將分割移入if語句中,以便在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