user2832472
user2832472

Reputation: 41

Python random numbers multiple times

import random

def main():
    uinput()

def uinput():
    times = int(input('How many numbers do you want generated?'))
    number1 = int(input('Put in the first number:' ))
    number2 = int(input('Put in the second number:'))
    rnumber = random.randint(number1, number2)
    print (rnumber)



main()

I am messing around in Python, and I want my program to generate random numbers. As you can see I have already accomplished this. The next thing I want to do is have it generate multiple random numbers, depending on how many numbers the "user" wants generated. How would I go about doing this? I am assuming a loop would be required.

Upvotes: 1

Views: 25361

Answers (6)

Timothy Woodard
Timothy Woodard

Reputation: 21

You can define a function to take user input to generate numbers in a given range. You can return the function or print the function.

import random

def ran_nums():
    low_range = int(input('Enter the low end of the range: '))
    high_range = int(input('Enter the high end of the range: '))
    times = int(input('How many numbers do you want to generate? '))
    for num in range(times):
        print(random.randint(low_range,high_range))

Upvotes: 0

John Hartman
John Hartman

Reputation: 21

I would recommend using a loop that simply adds to an existing string:

import random
from random import randint
list=""
number1=input("Put in the first number: ")
number2=input("Put in the second number: ")
total=input("Put in how many numbers generated: ")
times_run=0
while times_run<=total:
    gen1=random.randint(number1, number2)
    list=str(list)+str(gen1)+" "
    times_run+=1
print list

Upvotes: 2

samuel
samuel

Reputation: 1

This code chooses a random number:

import random
x = (random.randint(1, 50))
print ("The number is ", x)

Repeat the code 6 times to choose 6 random numbers.

Upvotes: -2

onemouth
onemouth

Reputation: 2277

Use generators and iterators:

import random
from itertools import islice

def genRandom(a, b): 
    while True:
        yield random.randint(a, b)


number1 = int(input('Put in the first number:' ))
number2 = int(input('Put in the second number:'))
total = int(input('Put in how many numbers generated:'))

rnumberIterator = islice(genRandom(number1, number2), total)

Upvotes: 1

Aesthete
Aesthete

Reputation: 18850

This will produce a list of random integers in range number1 to number2

rnumber = [random.randint(number1, number2) for x in range(times)]

For more information, look at List Comprehension.

Upvotes: 8

Joohwan
Joohwan

Reputation: 2512

Use a "for" loop. For example:

for i in xrange(times):
    # generate random number and print it

Upvotes: 1

Related Questions