Python Learning Series · @onlysamarrr · Day 28 / 30

Day 28: Modules

Day 28 teaches modules. A module is code from another file: import math and import random give you their functions. Never name your own file random.py or math.py, or Python will hide the real module behind yours.

Phase: Intermediate · Reels: 136/450 – 140/450

Quick Answer

Day 28 teaches modules. A module is code from another file: import math and import random give you their functions. Never name your own file random.py or math.py, or Python will hide the real module behind yours.

What You Will Learn

Code

import math, random
print(math.pi > 3, math.sqrt(16))
random.seed(0)
dice = random.randint(1, 6)
print(dice)
otp = "".join(random.choices("0123456789", k=6))
print(len(otp))
print(otp)
if __name__ == "__main__":
    print("Only on direct run")

Output

True 4.0
4
6
742547
Only on direct run

Code Explained, Line by Line

  1. import math gives you functions like pi and sqrt.
  2. random.randint(1, 6) gives a random number from 1 to 6, like a dice roll.
  3. random.seed(0) in the example makes the output repeatable so the dice and OTP pattern can be followed. Do not seed in a real program.
  4. random.choices(..., k=6) picks 6 random digits to build an OTP-like string.
  5. if __name__ == "__main__" runs only when the file is run directly, not when it is imported.
Common Mistake: Never name your file random.py or math.py: Python will treat your file as the real module and the real module will be hidden.

Real-Life Use

Dice games, OTP generators and shuffling all use the random module.

Practice Task: Build a dice roller with randint and an OTP generator with choices.

Test Yourself — MCQs

Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.

Q1. What does random.randint(1, 6) return?

Q2. Why not name your file random.py?

Q3. When does if __name__ == "__main__" run?

Today's 5 Reels (from the 90-Day Plan Excel)

136/450Conceptimport kaise kaam karta
137/450Live demorandom aur math demo
138/450Common mistakeFile ka naam random.py mat rakho
139/450QuizQuiz: dice roller
140/450Interview / real lifeReal life: OTP generator
← Day 27Day 29 →