To summarize everything that has been said and not said: (considering that you seem to be a beginner, let's start in order):
- As @insolor noted: it is not necessary to increase the variable
i by one each time; it will increase anyway. - There is no need
for while , the for loop itself should be completed after 10 iterations (“repetitions” if it is easier to express it). And there is also no point in the if construct - it is quite logical that after the completion of the cycle, the variable i will be equal to 10: there is simply no options.
Those. The code can be simplified to this:
array = [] import random for i in range(10): random_number = random.randint(1,100) array.append(random_number) print(array)
Further, there is such a thing as “List Generators”, if you don’t know that you should read about it, it’s not difficult.
A simple example of list generators:
array = [1, 2, 4, 5, 6, 98, 123, 45] # % — операция вычисления остатка от деления # если остаток от деления на 2 равен единице, то число нечетно only_odd_numbers = [n for n in array if n % 2 == 1] print(only_odd_numbers ) # [1, 5, 123, 45]
Using the list generators, you can further simplify the code:
import random array = [random.randint(1,100) for i in range(10)] print(array)
UPDATE:
There is also a function such as random.choices . The essence of this function is by examples:
import random arr1 = random.choices([1, 2], k=10) arr2 = random.choices(range(1, 10)) arr3 = random.choices(range(1, 100), k=10) arr4 = random.choices(range(1, 10), k=20) print(arr1) # [1, 1, 1, 2, 2, 1, 2, 1, 2, 2] print(arr2) # [8] print(arr3) # [60, 35, 80, 26, 7, 65, 58, 9, 77, 2] print(arr4) # [1, 1, 6, 4, 2, 6, 7, 2, 2, 2, 2, 1, 1, 6, 1, 7, 8, 3, 5, 3]
Note: arr1 contains only one and two.
Thus: random.choices returns a list consisting of a certain number (determined by the parameter k ) of elements, each of which is a random element of the sequence that we passed in the first argument.
UPDATE An important remark was made by @jfs: “ randint includes the right border, and range does not”