【发布时间】:2018-08-25 11:48:28
【问题描述】:
我试图让用户在 Python 中操作列表。
number_of_commands = int(input())
x = 0
my_list = []
while x <= number_of_commands:
command, i, e = input().split(' ')
command = str(command)
i = int(i)
e = int(e)
x = x + 1
if command == 'insert':
my_list.insert(i, e)
elif command == 'print':
print(my_list)
elif command == 'remove':
my_list.remove(e)
elif command == 'append':
my_list.append(e)
elif command == 'sort':
my_list.sort()
elif command == 'pop':
my_list.pop()
elif command == 'reverse':
my_list.reverse()
else:
print("goodbye")
当用户输入需要两个整数的命令(例如insert)时,程序可以运行,但是当用户输入print 之类的内容时,我收到错误“没有足够的值来解压”。仅当您将其输入为 print 0 0 时才有效。如何允许用户输入带整数和不带整数的命令?
【问题讨论】:
-
看看Python的内置
range函数。根据定义,知道迭代次数的循环更适合for循环而不是while。for x in range(number_of_comands):将允许您同时删除x = 0和x = x + 1行。另外x = x + 1通常写成x += 1。
标签: python python-3.x