0

I have to create a program where the user input asks how many numbers in an array and you have to print those numbers from an array.

Example:

How many values to add to the array:

12

[14, 64, 62, 21, 91, 25, 75, 86, 13, 87, 39, 48]

I don't know how to get all the numbers in one line and how to get different numbers each time. This is what I have so far:

import random


x = int(input("How many values to add to the array: "))

b = random.randint(1,99)
c = random.randint(1,99)

for i in range(x):
    twainQuotes = [random.randint(b,c)]

for i in range(x-1):
    print(twainQuotes)
AMC
  • 2,642
  • 7
  • 13
  • 35

4 Answers4

0

If you are trying to create a list with x random integers 1,99, this should work:

integers = []
for i in range(x):
    integers.append(random.randint(1,99))
WangGang
  • 533
  • 3
  • 15
0

You could use this code:

import random
x = int(input("How many values to add to the array: "))

b = random.randint(1,99)
c = random.randint(1,99)

twainQuotes = [] # Initialize list
for i in range(x):
    twainQuotes.append(random.randint(b, c)) # Add random number to list

print(twainQuotes) # Print list

If you want, you can also use list comprehension:

import random
x = int(input("How many values to add to the array: "))

b = random.randint(1,99)
c = random.randint(1,99)

twainQuotes = [random.randint(b, c) for i in range(x)] # Initialize list
print(twainQuotes)

I would suggest not using the b and c values, as you could just do random.randint(1, 99):

import random
x = int(input("How many values to add to the array: "))

twainQuotes = [random.randint(1, 99) for i in range(x)] # Initialize list
print(twainQuotes)
Ayush Garg
  • 2,234
  • 2
  • 12
  • 28
0

you could use a list comprehension:

if b > c:
    b, c = c, b

twainQuotes = [random.randint(b, c) for _ in range(x)]

to print:

 print(*twainQuotes, sep='\n')

if you want to use for loops:

import random


x = int(input("How many values to add to the array: "))

b = random.randint(1,99)
c = random.randint(1,99)

if b > c:
    b, c = c, b

twainQuotes = []
for i in range(x):
    twainQuotes.append(random.randint(b,c))

for e in twainQuotes:
    print(e)

example output (for input = 2):

52
65
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

First of all, maybe it's a copy-paste error, but you have two variable declarations on the same line which was not written correctly.

# either this :
b = random.randint(1,99)
c = random.randint(1,99)

# or this :
b,c = random.randint(1,99), random.randint(1,99)

But, I think your code will return an error if b is bigger than c.

for i in range(x):
    twainQuotes = [random.randint(b,c)]
    # if b > c ValueError will be raised

Instead, I think you can use the list comprehension method? :)

Check the code below :

import random

x = int(input("How many values to add to the array: "))

array = [random.randint(1,99) for each_number in range(x)]

print(array)
Moby J
  • 561
  • 1
  • 4
  • 8