Skip to main content

CS - Grade XII - Random Module Notes

 

Random Module

The randrange() function in Python is used to generate a random number from a specified range. It is part of the random module. Here are a few examples to demonstrate how it works.

import random

# Random number from 0 to 9

num = random.randrange(10)

print(num)  # Output: Any number from 0 to 9

 

# Random number from 5 to 14

num = random.randrange(5, 15)

print(num)  # Output: Any number from 5 to 14

 

# Random even number from 0 to 18

num = random.randrange(0, 20, 2)

print(num)  # Output: 0, 2, 4, ..., 18

 

for i in range(5):

    print(random.randrange(1, 100))

# Output: 5 random numbers between 1 and 99

 import random


#EG:

fruits = ['apple', 'banana', 'cherry', 'date', 'fig']

# Get a random index within the list

index = random.randrange(len(fruits))

# Access the list using the random index

print("Random fruit:", fruits[index])


The random() function in Python is used to generate a random floating-point number between 0.0 and 1.0 (not including 1.0). It is also part of the random module.

import random

num = random.random()

print(num)  # Output: Random float between 0.0 and 1.0

 

# Random float between 0 and 10

num = random.random() * 10

print(num)

Example:

If random.random() gives 0.6345, then:

0.6345×10=6.3450.6345 \times 10 = 6.345

 

 # Random float between 5 and 10

num = 5 + (random.random() * 5)

print(num)

 

for i in range(3):

    print(random.random())

# Output: 3 random floats between 0.0 and 1.0

 

The randint() function in Python is used to generate a random integer between two specified values inclusive (meaning both end values are included).

It’s part of the random module

 

import random

num = random.randint(1, 10)

print(num)  # Output: Random integer from 1 to 10 (inclusive)

 

dice = random.randint(1, 6)

print("Dice roll:", dice)  # Output: 1 to 6

 

student_roll = random.randint(1001, 1020)

print("Random roll number:", student_roll)

 

neg_num = random.randint(-10, -1)

print("Random negative number:", neg_num)  # Output: between -10 and -1

 

for _ in range(5):

    print(random.randint(10, 20))

# Output: 5 random integers between 10 and 20

 

Q1. Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).

import random

def roll_dice():
   print(random.randint(1, 6)) 

print("""Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.""")

flag = True
while flag:
   user_prompt = input(">")
   if user_prompt.lower() == "quit":
      flag = False
   else:
     print("Rolling dice...\nYour number is:") 
     roll_dice()

CBSE BOARD NOTES

Python Modules

Importing and using built-in modules — math, random, statistics

1. Importing Modules

 A module is a file containing Python definitions and functions. Use the import statement to load a module.

 Method 1 — import statement

Imports the entire module. Access functions using module.function() syntax.

import math

import random

import statistics

 

result = math.sqrt(25)   # must prefix with module name

 

Method 2 — from … import statement

Imports specific items directly. No prefix needed when calling.

from math import sqrt, pi

from random import randint

 

result = sqrt(25)   # no prefix needed

print(pi)           # 3.141592653589793

 

Method 3 — import all (use with caution)

from math import *   # imports everything from math

print(floor(3.7))    # 3

 

Note: Avoid using 'import *' in large programs — it can cause name conflicts when two modules have functions with the same name.

 

2. The math Module

The math module provides mathematical functions and constants. It is part of Python's standard library.

 Constants

Constant

Value

Description

math.pi

3.141592653589793

The mathematical constant pi (π)

math.e

2.718281828459045

Euler's number (base of natural log)

Functions

Function

Returns

Description

sqrt(x)

float

Square root of x

ceil(x)

int

Smallest integer ≥ x (rounds up)

floor(x)

int

Largest integer ≤ x (rounds down)

pow(x, y)

float

x raised to the power y

fabs(x)

float

Absolute value of x (always float)

sin(x)

float

Sine of x (x in radians)

cos(x)

float

Cosine of x (x in radians)

tan(x)

float

Tangent of x (x in radians)

 Examples

import math

 

print(math.sqrt(49))        # --> 7.0

print(math.ceil(4.2))        # --> 5

print(math.floor(4.9))       # --> 4

print(math.pow(2, 10))       # --> 1024.0

print(math.fabs(-7.5))       # --> 7.5

print(math.sin(math.pi/2))   # --> 1.0

print(math.cos(0))           # --> 1.0

print(math.tan(math.pi/4))   # --> ~1.0

3. The random Module

The random module generates pseudo-random numbers. Results change each time the program runs.

Functions

Function

Returns

Description

random()

float

Random float in [0.0, 1.0) — includes 0, excludes 1

randint(a, b)

int

Random integer from a to b (both inclusive)

randrange(start, stop)

int

Random integer from start up to (not including) stop

randrange(start,stop,step)

int

Random integer from range with given step

 Examples

import random

print(random.random())            # --> e.g. 0.5731  (changes each run)

print(random.randint(1, 6))       # --> 1 to 6  (like rolling a die)

print(random.randrange(0, 10, 2)) # --> 0, 2, 4, 6, or 8

Note: Key difference: randint(1, 6) includes both 1 and 6. randrange(1, 6) gives 1 to 5 only — 6 is excluded.

 

4. The statistics Module

The statistics module provides functions for calculating basic statistical measures on numeric data.

Functions

Function

Returns

Description

mean(data)

float

Arithmetic average of all values

median(data)

float/int

Middle value when data is sorted

mode(data)

value

The most frequently occurring value

Examples

import statistics

data = [4, 7, 2, 9, 7, 5, 3]

print(statistics.mean(data))    # --> 5.285714...

print(statistics.median(data))  # --> 5   (sorted: 2,3,4,5,7,7,9)

print(statistics.mode(data))    # --> 7   (appears most often)

 

Note: mode() raises StatisticsError if no single value appears most often (Python < 3.8). In Python 3.8+, it returns the first mode found.

 

Quick Reference Summary

Module

Import

Key Items

math

import math

pi, e, sqrt, ceil, floor, pow, fabs, sin, cos, tan

random

import random

random(), randint(a,b), randrange(start,stop,step)

statistics

import statistics

mean(data), median(data), mode(data)

 

 

i

Comments

Popular posts from this blog

GRADE XII - Python Connectivity with MySQL

  Python Connectivity with MySQL In real-life applications, the data inputted by the user and processed by the application needs to be saved permanently, so that it can be used for future manipulation. Usually, input and output data is displayed during execution but not stored, as it resides in main memory , which is temporary — i.e., it gets erased once the application is closed. This limitation can be overcome by sending the data to be stored in a database , which is made accessible to the user through a Front-End interface . Key Concepts Database A database is an organized collection of data that is stored and accessed electronically from a computer system. DBMS (Database Management System) A DBMS is software that interacts with end-users, applications, and the database to capture and analyze data. Front-End The Front-End is the user interface of the application, responsible for input/output interaction with the user. Back-End The Back-End refe...

GRADE XI | DESIGN THINKING & INNOVATION (848) | INTRO | CH-1

  DESIGN THINKING &  INNOVATION (848)  INTRODUCTION LINK : INTRODUCTION PPT PPT LINK Notes: Design Thinking and Innovation Grade XI Introduction Section   I. What is Design? (0.1.1) Definitions from Experts: John Maeda: "Design is solution to a problem". Saul Bass: "Design is thinking made visual". Charles Eames:   “Design is a plan for arranging elements in such a way as best to accomplish a particular purpose.” Steve Jobs:  "Design is not just what it looks like and feels like. Design is how it works". Prof. Sudhakar Nadkarni:  "Essentials of design are— purity, precision, details". Design is a way of understanding needs, identifying problems, and creating appropriate and innovative solutions. It is not only about appearance, but also about usefulness and sustainability. Design is explained as something that helps solve problems and make a positive difference. Key ...