Reputation: 101
I am trying to get a list of odd numbers between 0 and 100. The length of the list is decided by entering the number.
It should be a list of maximum of 50 elements. If user enters a higher value, the message is "error". This goes ok, but I don't get any other information when the entered value is lower than 50. I can't find the error.
num_impares
represents the vector of the list with the odd numbers.
import random
elementos = int(input("how many elements should be?"))
num_impares = []
if elementos > 50:
print ("Error")
else:
while len (num_impares)!= elementos:
for i in range (elementos-1):
if random.randrange (101) %2 !=0:
num_impares.append(i)
print (num_impares)
Upvotes: 1
Views: 480
Reputation: 1434
I just suggest you to learn itertools
module.
import itertools
import random
def odd_generator(start=0, end=99):
while True:
# you could implement more advanced logic here
x = random.randint(start, end)
yield x | 1
nums_count = 50
res = list(itertools.islice(odd_generator(), nums_count))
print(len(res), res)
assert len(res) == nums_count
assert all(x % 2 == 1 for x in res)
Upvotes: 1
Reputation: 70
Never use !=
, instead, use <=
or <
. Also, you were printing the index not the random number. Here is the fixed code:
import random
elementos = int(input("how many elements should be?"))
num_impares = []
if elementos > 50:
print ("Error")
else:
while len(num_impares) < elementos:
randnum = random.randrange(101)
if randnum %2 !=0:
num_impares.append(randnum)
print (num_impares)
Upvotes: 0
Reputation: 323
You can use this:
import random
elementos = int(input("how many elements should be?"))
num_impares = []
if elementos > 50:
print ("Error")
else:
num_impares=[2*random.randrange (49)+1 for i in range( elementos)]
print (num_impares)
Upvotes: 0