-2

I have to ask the user for a number and then produce exactly as many random numbers as specified by the user using a while loop.

import random

x = int(input("Write a number: "))
y = random.randint(0, 10)

while x != 0:
    print(y)
    y = random.randint(0, 10)
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
r.abn
  • 5
  • 2
  • It's much better to check whether the input is a number rather than blindly using `int(input(...))`, which can fail with a runtime error if the input does not represent a number (e.g., if the user typed in the word "nonsense" or the string "xyz".) See [this question](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). – Peter O. Nov 11 '19 at 23:48

4 Answers4

1

Little modification to your code. You were not decreasing x

import random

x = int(input("Write a number: "))

while x != 0:
    y = random.randint(0, 10)
    print(y)
    x-=1

1

Your while loop is going to spin forever because you never decrement x. You could fix this by adding this to the body of your loop:

x -= 1

If you don't want it to spin forever when the user enters a negative number (since then it will decrease forever without ever hitting 0), you could change your while to:

while x > 0:

The more easy/standard/idiomatic way of doing this type of loop would be to use for ... in range:

for _ in range(x):
    print(random.randint(0, 10))
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • The last suggestion is easily the best way to do it. Beware though that using ```_``` as a dummy variable may break its use in interactive shells. – Antimon Nov 11 '19 at 22:05
1

You can use random.choices to select 10 values from a range.

x = int(input("Write a number: "))
values = list(random.choices(range(11), k=x))

For a larger range, you would probably rather make repeated calls to random.randint.

values = [random.randint(0,10) for _ in range(x)]
chepner
  • 497,756
  • 71
  • 530
  • 681
0

I wanted to point out that a for loop is far preferable to a while loop here, but Sam Stafford beat me to it! The list comprehension solution is also good.

I know your code is just an example, but those variable names are really poor, be careful. Anyway, here is a numpy solution, it might come in handy some day!

import numpy as np

num_to_gen = int(input("Choose how many random numbers to generate: "))

rand_nums = np.random.randint(low=0, high=11, size=num_to_gen).tolist()

print(rand_nums)
AMC
  • 2,642
  • 7
  • 13
  • 35