PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Random Data Generation Exercise

Python Random Data Generation Exercise

Updated on: June 5, 2025 | 13 Comments

This Python exercise will help you practice random data generation techniques. This exercise focuses on generating random numbers, choices, and samples using the random module and secrets module.

Also Read: Python Random Data Generation Quiz

This exercise includes:

  • There are 10 coding questions.
  • The solution is provided at the end of each question.
  • As you complete each question, you will become more familiar with random data generation techniques in Python

Refer to the following tutorials to solve the exercise.

  • Generating Random data in Python.
  • Secure Random data in Python.

Use Online Code Editor to solve each question.

Table of contents

  • Exercise 1: Generate 3 Random Integers
  • Exercise 2: Random Lottery Pick
  • Exercise 3: Generate 6 digit Random Secure OTP
  • Exercise 4: Pick Random Character
  • Exercise 5: Generate Random String
  • Exercise 6: Generate Random Password
  • Exercise 7: Calculate Multiplication
  • Exercise 8: Generate Random Token and URL
  • Exercise 9: Dice Roll
  • Exercise 10: Generate Random Date

Exercise 1: Generate 3 Random Integers

Write a code to generate 3 random integers between 100 and 999 which is divisible by 5

Reference article for help: Python get a random number within a range

Show Solution
import random

print("Generating 3 random integer number between 100 and 999 divisible by 5")
for num in range(3):
    print(random.randrange(100, 999, 5), end=', ')Code language: Python (python)

Exercise 2: Random Lottery Pick

Write a code to generate 100 random lottery tickets and pick two lucky tickets from it as a winner.

Note you must adhere to the following conditions:

  • The lottery number must be 10 digits long.
  • All 100 ticket number must be unique.
+ Hint

Generate a random list of 1000 numbers using randrange() and then use the sample() method to pick lucky 2 tickets.

Show Solution
import random

lottery_tickets_list = []
print("creating 100 random lottery tickets")
# to get 100 ticket
for i in range(100):
    # ticket number must be 10 digit (1000000000, 9999999999)
    lottery_tickets_list.append(random.randrange(1000000000, 9999999999))
# pick 2 luck tickets
winners = random.sample(lottery_tickets_list, 2)
print("Lucky 2 lottery tickets are", winners)Code language: Python (python)

Exercise 3: Generate 6 digit Random Secure OTP

Reference article for help:

  • Python secrets module to generate secure numbers
  • Python get a random number within a range
Show Solution
import secrets

#Getting systemRandom class instance out of secrets module
secretsGenerator = secrets.SystemRandom()

print("Generating 6 digit random OTP")
otp = secretsGenerator.randrange(100000, 999999)

print("Secure random OTP is ", otp)Code language: Python (python)

Exercise 4: Pick Random Character

Write a code to select a random character from a given string name = 'pynative'.

Reference article for help: random.choice()

Show Solution
import random

name = 'pynative'
char = random.choice(name)
print("random char is ", char)Code language: Python (python)

Exercise 5: Generate Random String

Write a code to generate random string of length 5.

Note: String must be the combination of the UPPER case and lower case letters only. No numbers and a special symbol.

Reference article for help: Generate random String in Python.

Show Solution
import random
import string

def randomString(stringLength):
    """Generate a random string of 5 charcters"""
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(stringLength))

print ("Random String is ", randomString(5) )Code language: Python (python)

Exercise 6: Generate Random Password

Write a code to generate a random password which meets the following conditions.

  • Password length must be 10 characters long.
  • It must contain at least 2 upper case letters, 1 digit, and 1 special symbol.

Reference article for help: Generate random String and Password in Python

Show Solution
import random
import string

def randomPassword():
    randomSource = string.ascii_letters + string.digits + string.punctuation
    password = random.sample(randomSource, 6)
    password += random.sample(string.ascii_uppercase, 2)
    password += random.choice(string.digits)
    password += random.choice(string.punctuation)

    passwordList = list(password)
    random.SystemRandom().shuffle(passwordList)
    password = ''.join(passwordList)
    return password

print ("Password is ", randomPassword())Code language: Python (python)

Exercise 7: Calculate Multiplication

Write a code to calculate multiplication of two random float numbers.

Note:

  • First random float number must be between 0.1 and 1
  • Second random float number must be between 9.5 and 99.5

Reference article for help: Generate a random float number between a float range

Show Solution
import random

num1  = random.random()
print("First Random float is ", num1)
num2 = random.uniform(9.5, 99.5)
print("Second Random float is ", num1)

num3 = num1 * num2
print("Multiplication is ", num3)Code language: Python (python)

Exercise 8: Generate Random Token and URL

Write a code to generate random secure token of 64 bytes and random URL.

Reference article for help: Python secrets module to generate a secure token and URL

Show Solution
import secrets

print("Random secure Hexadecimal token is ", secrets.token_hex(64))
print("Random secure URL is ", secrets.token_urlsafe(64))Code language: Python (python)

Exercise 9: Dice Roll

Write a code to roll dice in such a way that every time you get the same number.

Dice has 6 numbers (from 1 to 6). Roll dice in such a way that every time you must get the same output number. do this 5 times.

Given:

import random

dice = [1, 2, 3, 4, 5, 6]Code language: Python (python)

Reference article for help:

  • How to seed random number generator
  • random.choice()
Show Solution
import random

dice = [1, 2, 3, 4, 5, 6]
print("Randomly selecting same number of a dice")
for i in range(5):
    random.seed(25)
    print(random.choice(dice))Code language: Python (python)

Exercise 10: Generate Random Date

Write a code to generate a random date between given start and end dates.

Given:

import random
import time

def getRandomDate(startDate, endDate ):
    # Your code here

print ("Random Date = ", getRandomDate("1/1/2016", "12/12/2018"))Code language: Python (python)
Show Solution
import random
import time

def getRandomDate(startDate, endDate ):
    print("Printing random date between", startDate, " and ", endDate)
    randomGenerator = random.random()
    dateFormat = '%m/%d/%Y'

    startTime = time.mktime(time.strptime(startDate, dateFormat))
    endTime = time.mktime(time.strptime(endDate, dateFormat))

    randomTime = startTime + randomGenerator * (endTime - startTime)
    randomDate = time.strftime(dateFormat, time.localtime(randomTime))
    return randomDate

print ("Random Date = ", getRandomDate("1/1/2016", "12/12/2018"))
Code language: Python (python)

Filed Under: Python, Python Exercises, Python Random

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Exercises Python Random

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Mohammad says

    July 5, 2022 at 9:24 am

    Q7:

    You have num1 instead of num2.

    import random
    
    num1  = random.random()
    print("First Random float is ", num1)
    num2 = random.uniform(9.5, 99.5)
    print("Second Random float is ", num1)   ----> SHOULD BE NUM2
    
    num3 = num1 * num2
    print("Multiplication is ", num3)
    Reply
  2. alcebytes says

    January 3, 2022 at 10:23 am

    
    import datetime
    import random
    
    def date_generated(d1, d2):
        start = datetime.datetime.strptime(d1, '%d-%m-%Y')
        end = datetime.datetime.strptime(d2, '%d-%m-%Y')
        intervalo = [start + datetime.timedelta(x) for x in range(int ((end-start).days)+1)]
        datas = []
        for data in intervalo:
            datas.append(data.strftime('%d-%m-%Y'))
        print(*random.sample(datas, 1))
    
    date_generated('03-12-2021','03-01-2022')
    
    # saída
    03-01-2022
    Reply
  3. Bill says

    November 27, 2021 at 9:19 am

    This solution would never have a 0 as the first digit. So piecing together strings of 0-9’s is more accurate and chances of a dup are almost 0.

    Reply
  4. cub8 says

    July 17, 2021 at 4:27 pm

    I think your solution of Q10 is unnecessarily too complicated. Here’s my idea of solving this problem:

    import datetime
    import random
    def getRandomDate(startDate : datetime.date, endDate : datetime.date) -> datetime.date:
        print(f'Generating random date between {startDate} and {endDate}.')
        rangeEnd = (endDate - startDate).days
        delta = random.randint(0, rangeEnd)
        randomDate = startDate + datetime.timedelta(days=delta)
        return randomDate
        
    startDate = datetime.date(2016, 1, 1)
    endDate = datetime.date(2018, 12, 31)
    randomDate = getRandomDate(startDate, endDate)
    print(f'The random date is {randomDate}!')
    Reply
  5. Ali says

    July 19, 2019 at 1:05 am

    I think I may have found a simpler solution for Q10 as yours was difficult to follow:

    def random_dates(start_date,end_date):
         start_date = start_date.split('-')
         end_date = end_date.split('-'))
         random_day = random.randint(int(start_date[1]),int(end_date[1]))
         random_month = random.randint(int(start_date[0]),int(end_date[0]))
         print ('Date = ' + str(random_month) + ' - ' + str(random_day) + ' - ' + '2019')
    
    Reply
  6. Vitaliy says

    June 23, 2019 at 9:59 pm

    Q5

    print("".join(random.choices(string.ascii_letters, k=5)))
    Reply
  7. Bill Hardwick says

    May 21, 2019 at 6:23 pm

    Q10 – I think your solution is unnecessarily complicated. I offer my simpler solution:

    import random, datetime as dt
    start_date = dt.date(2019, 1, 1)
    print(f'Start of period = {start_date}')
    end_date = dt.date(2019, 12, 25)
    print(f'End of period   = {end_date}')
    delta = (end_date - start_date).days
    r = random.randint(0, delta)
    r_date = start_date + dt.timedelta(days = r)
    print(f'Random date  = {r_date}')
    Start of period = 2019-01-01
    End of period   = 2019-12-25
    Random date  = 2019-04-14
    
    Reply
  8. Bill Hardwick says

    May 18, 2019 at 6:51 pm

    Q6 – Hmm. I hadn’t come across the shuffle function, so rather than code one myself, I arrived at this alternative solution. It is obviously less efficient than your answer, but given the scale of the problem the timing difference is not of practical significance.

    import string, secrets
    s = string.ascii_letters + string.digits + string.punctuation
    pw = ''
    uc = 0
    dg = 0
    sp = 0
    while len(pw) < 10:
      z = secrets.choice(s)
      if z in string.ascii_uppercase: uc += 1
      elif z in string.digits: dg += 1
      elif z in string.punctuation: sp += 1
      pw += z
      if len(pw) == 10:
        #Does it meet the criteria?  If not, ditch it and try again
        if uc < 2 or dg < 2 or sp < 2: 
          pw = ''
          uc = dg = sp = 0
    print(pw)
    
    Reply
    • Rishikesh Shah says

      April 19, 2022 at 11:04 am

      Exercise 6: I have also similar solution like you.

       num = 0
      upper_let = 0
      special_char = 0
      while True:
          random_password = ''.join(random.choice(string.ascii_letters + string.digits + string.punctuation ) for i in range(10))
          for item in random_password:
              if item.isupper():
                  upper_let += 1
              if item.isnumeric(): 
                  num += 1
              if not (item.isalpha() or item.isdigit() or item.isspace()):
                  special_char += 1
          if upper_let >=2 and num >=1 and special_char >= 1:
              print("Random password is:", random_password)
              break 
      Reply
  9. Bill Hardwick says

    May 18, 2019 at 6:00 pm

    Q5 – badly worded. “String must be the combination of the UPPER case and lower case letters only. No numbers and a special symbol.”
    Thus can only be interpreted as requiring a string comprised of letters (any case – or arguably a mix of cases) plus a special symbol. (A slightly more difficult problem which I addressed.)
    I suggest re-wording it as “The string must contain only upper and/or lower case alphabetic characters..” There is no need for your second sentence.

    Reply
  10. Bill Hardwick says

    May 18, 2019 at 4:50 pm

    Q2 – Sorry, but I’m afraid your solution is incorrect: it does not preclude duplicate ticket numbers being generated. For example, substituting smaller values into your solution for demonstration purposes:

    import random
    lottery_tickets_list = []
    print("creating 10 random lottery tickets")
    for i in range(10):
        lottery_tickets_list.append(random.randrange(10, 20))
    print(lottery_tickets_list)
    

    typically results in duplicate-riddled output like this:
    creating 10 random lottery tickets
    [18, 16, 13, 13, 16, 10, 10, 14, 11, 16]

    My solution uses a set rather than a list to achieve the correct result:

    import random
    tickets  = set()
    while len(tickets) < 100:
      tickets.add(random.randrange(1000000000, 10000000000))
    print('Drum roll...')
    print('and the lucky winners are numbers:')
    winners = random.sample(tickets, 2)
    print(f'{winners[0]} and {winners[1]}')
    

    which outputs
    Drum roll…
    and the lucky winners are numbers:
    8975225689 and 1386699143
    Note also the use of 10000000000 as the top of the range value rather than your 9999999999 because the end-point for the range is exclusive. (The same comment applies to Q1, although this does not affect the outcome.)

    Reply
    • vahlo says

      October 23, 2020 at 12:29 pm

      Hi, I believe your conclusion about the original solution is correct but your code could be simplified as well. This code has done the trick for me:

      import random
      tickets = random.sample(range(1000000000, 9999999999), 100)
      winners = random.sample(tickets, 2)
      print('Winners are:',winners)

      I believe as random.sample generates unique choices it can be used for the tickets as well.

      Reply
      • Igor says

        July 25, 2022 at 4:45 pm

        Yep, the answer to Q2 is incorrect.
        Your solution is slick and concise.
        Bill’s idea with the set() was smart, too (although sampling from a set is now deprecated).
        I’ve solved it in the following way (which is a bit verbose):

        
        tickets = []
        tickets_amount = 100
        counter = 0
        while True:
        	ticket = random.randrange(int(1e9), int(1e10))
        	if ticket not in tickets:
        		tickets.append(ticket)
        		counter += 1
        		if counter == tickets_amount:
        			break
        Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Exercises Python Random
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com