1

My first question here, so if I don't do something correctly, please tell me so I can correct it and/or do it correctly next time.

I am trying to allow a user to input ten numbers, then spit them back out in the reverse order they gave them. I can't get the ranges right, though, because it keeps either asking me for just 9 numbers, or it doesn't assign anything to the last variable in my list.

I am using Python 3.x.

Here is my code:

#Creating my list
myNumbers=[1,2,3,4,5,6,7,8,9,10,11]

#Creating a for loop for inputs
for A in range (1,10):
    myNumbers[A]=input("Enter a number: ")


#Creating a for loop for outputs
for B in range (10,1,-1):
    print(myNumbers[B])

It's only allowing me to input 9 numbers, and then my output is the number 11, then my reverse input.

Any help would be much appreciated.

4

4 回答 4

3

range always omits the last value, and starts from 0 by default (remember that lists are 0-indexed in Python, so a 10-element list has indices 0 through 9).

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Also, instead of using range(10,1,-1), I would recommend just using reversed:

for i in reversed(range(10)): # iterates from 9 down to 0

or, since you are just printing out the items in the list, just iterate over the reversed list items directly:

for item in reversed(myNumbers):
    print(item)
于 2013-03-01T01:51:03.277 回答
1

The reason it's only letting you enter 9 numbers, is that the first element in a list has index of 0, so you should be assigning to A[0]...A[9]

If you start with an empty list, you can append to it as many times as you wish, so you don't need to know the size in advance.

my_numbers = []

for i in range(10):
    my_numbers.append(input("Enter a number: "))

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

Loop variables in Python don't have to be numbers, you can iterate over anything that returns a sequence of objects.

There is a shorthand way of creating a list like this called a list comprehension. Then your program becomes just 3 lines

my_numbers = [input("Enter a number: ") for i in range(10)]

for item in reversed(my_numbers):
    print(item)
于 2013-03-01T01:50:56.147 回答
0

Try using range (0,10) instead of range (1,10)

range (1,10) is similar to for (i=1;i<10;i++) which runs only 9 times(does not run for i=10) also, the array index starts from 0 and not 1

于 2013-03-01T01:53:26.270 回答
0
print( '\n'.join(reversed([input("Enter a number: ") for i in range(10)])) )

or

li = []
for i in xrange(4):
    li.insert(0,input("Enter a number: ")
print( '\n'.join(li) )

This solution doesn't create a new (reversed) list object. We directly construct the desired list.
It can be shortened to

li = []
any(li.insert(0,input("Enter a number: ")) for i in xrange(4))
print( '\n'.join(li) )
于 2013-03-01T02:35:04.700 回答