我需要一个代码,要求输入5个pos号码,然后反向输出这些号码。我想使用while循环。这是我到目前为止提出的,但是第二个while循环不起作用。你知道吗
positiveNum = 0
SIZE = 5
numberList= []
ARRAY_LIMIT = SIZE -1
while len(numberList) < SIZE :
positiveNum = input("Enter a positive number:")
numberList.append(positiveNum)
while int(positiveNum) >= 0:
print(numberList[positiveNum])
positiveNum -= 1
在第二个循环中,如果使用相同的positiveEnum变量,而没有将其重置为数组的大小,请尝试:
您的第一个问题是
input
返回一个string
,因此如果您想用它建立索引,您需要将它强制转换为int
。您可能会遇到以下错误。你知道吗在while循环条件中转换它只对条件有效,它不会将变量中的值更改为
int
,它仍然是string
现在下一个问题是使用
positiveNum
作为索引号。如果输入的最后一个数字大于SIZE
,例如100,这将导致IndexError
。你知道吗这里还有几个for-loop替代方案
您应该迭代numberList的长度,而不是正num。 基本上修改第二个while循环。你知道吗
相关问题 更多 >
编程相关推荐