0

I'm doing a programming question and I need a bit of help. I have a variable where I type in a number and then that number and all the numbers before it go in a list.

For example: I pick 10 and put it in a variable

And all numbers from 1 - 10 are put in a list

Here is my code:

 Top_Num = int(input('Top Number'))
 Nums = []

Now lets say I chose 10 for the Top_Num, how do I put 10 numbers into the list? Thanks.

0

2 Answers 2

3

You can actually use Pythons built in range(int) function to do exactly this.

If you want the array to start at 1 and include the input number, you can use

Nums = list(range(1, Top_Num + 1))

The first argument of 1 indicates the start value of the array, and the second argument Top_Num + 1 is the number that the array goes up to (exclusive).

Sign up to request clarification or add additional context in comments.

1 Comment

On Python 3, you'll need to explicitly cast your range to a list: list(range(1, Top_Num+1))
2
Nums = [num for num in range(1, Top_Num + 1)]

It uses list comprehensions too, which is (kinda) an important concept in python.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.