簡體   English   中英

Python-列表中的索引錯誤

[英]Python - index error in list

我正在編寫一個程序,它接受一個輸入2的第一個方向,第二個是一行,我通過使用split('')來執行此操作,所有這些輸入都在while循環中輸入,但是用戶不想輸入更多的輸入,他只是輸入空行並終止,但是沒有發生,不知道為什么...這是我的代碼

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

您可以對列表進行len()處理,如果不作任何動作,就可以進行邏輯運算,例如

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

將您的direction = moving [0] .lower()行移至if語句中,這將使它們僅在運動!=時才運行,您需要更改if語句o否則它將始終為true不能同時為”和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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM