So, let's break down the the assignment:
Write a program that reads a list of integers, one per line
This means that you should have a loop that reads in values, converts them into an integer and adds them to a list.
But:
until an * is read
This means that you first have to check that the user's input was equal to "*"
. But, you'll have to be careful to not try to convert the user's input into an integer before you check if it's an asterisk, otherwise an error will be thrown. So, your loop would look like the following:
- Get the user's input
- Check if it's an asterisk. If so,
break
the loop.
- If the user's input is not an asterisk, convert it to an
int
, and then add it to your list of inputted integers.
That's all you need for your first loop.
For the second loop, let's refer to the assignment:
then outputs those integers in reverse
This means that you will need a second loop; a for
loop would work - you can have the loop go over a range()
, except counting backwards. Here is a post about this exact thing.
- Your range would start at the length of your list, minus one, because the last index of the list is one less than the number of items, since list indices start at zero.
- Then, you end the range at -1, meaning the range will go down to zero, and stop, because it stops before it gets to the specified end.
- Your range will count down by -1, instead of the implicit +1 by default. Refer to that post I linked if you're not sure how to do this.
Lastly, we need to actually print the items at those indices.
follow each integer, including the last one, by a comma.
To me this means that either we could output one integer per line, with a comma at the end of each line, or we could print them all in one line, separated by commas.
If you want everything to print on one line, you can just do a regular print()
of the item at the current index, followed by a comma, like print(my_list[a] + ',')
.
But, if you want to output them on separate lines, you can set the end
argument of print()
to be a comma. This post explains this.
And that's it!
There are other ways to go about this, but that should be a pretty straightforward and clear way to do it.