输出向后输入的数字的Python列表

2024-10-01 02:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个代码,要求输入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

Tags: 代码posnumberinputsizelenarray号码
3条回答

在第二个循环中,如果使用相同的positiveEnum变量,而没有将其重置为数组的大小,请尝试:

SIZE = 5
numberList= []
ARRAY_LIMIT = SIZE -1

while len(numberList) < SIZE :
    positiveNum = input("Enter a positive number:")
    numberList.append(positiveNum)
index = SIZE - 1
while index >= 0:
    print(numberList[index])
    index -= 1

您的第一个问题是input返回一个string,因此如果您想用它建立索引,您需要将它强制转换为int。您可能会遇到以下错误。你知道吗

TypeError: list indices must be integers or slices, not str

# Won't work with string
numberList[positiveNum]
positiveNum -= 1
# Need to cast to int first
positiveNum = int(input("Enter a positive number:"))

在while循环条件中转换它只对条件有效,它不会将变量中的值更改为int,它仍然是string

# Works only once
while int(positiveNum) >= 0:

现在下一个问题是使用positiveNum作为索引号。如果输入的最后一个数字大于SIZE,例如100,这将导致IndexError。你知道吗

SIZE = 5
number_lst = []

while len(number_lst) < SIZE:
    # Should perform error checking if you must have positive numbers
    num = int(input("Enter a positive number: "))
    number_lst.append(num)

# Output backwards using while
i = len(number_lst) - 1
while i >= 0:
    print(number_lst[i])
    i -= 1

这里还有几个for-loop替代方案

# Output backwards using for
for item in number_lst[::-1]:
    print(item)

for item in reversed(number_lst):
    print(item)

for i in range(len(number_lst) - 1, -1):
    print(number_lst[i])

for i in reversed(range(len(number_lst))):
    print(number_lst[i])

您应该迭代numberList的长度,而不是正num。 基本上修改第二个while循环。你知道吗

 i = SIZE; 
 while i>0: 
        print(numberList[i-1])
        i=i-1

相关问题 更多 >