Onyilimba
Onyilimba

Reputation: 1217

How to run a function multiple times and return different result python

I'm having a problem and I don't know if this is doable but what I wanted to do is call a function multiple times. The idea is I am generating a serial number for tickets, I have a function that generates a number which is 16 in length:

import random
import string

def random_number_generator(size=16, numbers=string.digits):
    return ''.join(random.choice(numbers) for _ in range(size))

Now if I run this function like this print(random_number_generator() * 4) it will return something like this:

1234567890987654
1234567890987654
1234567890987654
1234567890987654

How do I make it to return different numbers instead of the same numbers?

Upvotes: 2

Views: 6157

Answers (3)

Linh Nguyen
Linh Nguyen

Reputation: 3890

The way you using * 4 in print() just make it print the same result from the function 4 times. You can use something simple from python as a loop to run it x times:

for k in range(4):
   print(random_number_generator())

Because the number range so large there less likely to have repeat results, but you can use this to remove duplicate results

output = []
expected_results = []
for k in range(4):
   output.append(random_number_generator())

expected_results = list(dict.fromkeys(output))

print(expected_results)

Upvotes: 8

dannier
dannier

Reputation: 41

You can just loop through your function and append generated numbers to an empty list.

number_of_tickets = 10
ticket_serial_numbers = []
for i in range(number_of_tickets):
    serial_number = random_number_generator()
    ticket_serial_numbers.append(serial_number)

Upvotes: 1

bonobo
bonobo

Reputation: 132

for i in range(4):
    print(random_number_generator())

Upvotes: 1

Related Questions