[英]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.