0
    def __init__(self,name, age, telephone, employee_id):
    self.name = name
    self.age = age
    self.telephone = telephone
    self.student_id = employee_id

@staticmethod
def generate_id():
    
    'create a random new id, which is any number between 1,000 and 5000'
    'return id as a string'
    "Example '2050' "

I have the above code and need to generate and return the random Ids as a string, can someone help please. I am very new to Python

  • `import random` then `return str(random.randint(1000, 5000))` inside `generate_id` – Luatic May 25 '22 at 18:05
  • As asked, the question has been answered, but it should be pointed out that this is not a good way to generate ids. The defining characteristic of an id is that it is unique. Random selections in a small range quickly violate that rule — see the "birthday problem" to get a sense of how quickly. – Raymond Hettinger May 25 '22 at 18:22

2 Answers2

0

Use the random module to generate a new ID and supply the minimum and maximum numbers to the randint method and use the str helper method to convert the integer into a string as such.

from random import randint
id = str(randint(1000, 5000))

You can return the id variable via your generate_id method.

Anm
  • 447
  • 4
  • 15
0

create a random new id, which is any number between 1,000 and 5000 return id as a string

This part is simple:

 str(random.randrange(1000, 5000)) 

Change to 5001 if 5000 is valid possibilty

To make sure the generated id values are unique, most effort is needed. First build a shuffled pool of valid id values.

 id_pool = list(map(str, range(1000, 5000)))
 random.shuffle(id_pool)

Then just assign the shuffled ids consecutively.

This extra effort is needed because the defining characteristic of an id is that it is unique.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485