Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔁 Unit 2 – Flow of Control & Functions  ·  Lesson 19

Scope & Modules (math, random)

What is scope?

The scope of a variable is the part of the program where that variable can be used. A variable created inside a function lives only in that function — like a classroom announcement that is heard only inside that classroom, while a school-wide announcement (global) is heard everywhere.

Global scopevariables created outside all functions – visible everywhereLocal scope of a functionvariables created inside the function – visible only inside it
Two levels of scope

Local and global variables

Python
school = 'KV No. 1'           # global variable

def show():
    percent = 88              # local variable
    print('Inside:', school, percent)

show()
print('Outside:', school)
print(percent)                # percent does not exist here
Inside: KV No. 1 88 Outside: KV No. 1 NameError: name 'percent' is not defined

percent was created inside show(), so it is destroyed when the function ends. Parameters of a function are also local variables.

Same name inside and outside

If a function assigns to a name, Python creates a new local variable, even if a global one has the same name. The global stays unchanged.

Python
x = 5

def change():
    x = 50                    # creates a NEW local x
    print('Local x =', x)

change()
print('Global x =', x)
Local x = 50 Global x = 5

The global keyword

To change a global variable inside a function, declare it with global.

Python
count = 0

def visit():
    global count              # use the global variable
    count += 1

visit(); visit(); visit()
print('Visitors =', count)
Visitors = 3
⚠️ Use sparingly

Too many global variables make programs hard to debug. Prefer passing values as arguments and returning results.

The Python standard library

Python comes with hundreds of ready-made modules called the standard library. A module is simply a .py file with useful functions. Related modules grouped in a folder form a package.

📐
mathsqrt, pow, ceil, floor, factorial, pi …
🎲
randomrandom numbers for games, quizzes, OTPs
📊
statisticsmean, median, mode
📅
datetimedates and times
Modules in the CBSE syllabus and beyond

Ways to import a module

Python
from math import sqrt, pi        # import only what you need
print(sqrt(81), round(pi, 2))
import math as m                 # short alias
print(m.floor(9.99))
9.0 3.14 9
StatementHow you call
import mathmath.sqrt(9)
import math as mm.sqrt(9)
from math import sqrtsqrt(9)
from math import *sqrt(9) (imports everything – avoid in big programs)

math module

Python
import math
print(math.sqrt(144), math.pow(2, 5))
print(math.ceil(4.2), math.floor(4.8), math.fabs(-7.5))
print(math.factorial(5), math.gcd(36, 60))
print(round(math.pi, 4), round(math.e, 4))
print(round(math.sin(math.radians(30)), 2), math.log10(1000))
12.0 32.0 5 4 7.5 120 12 3.1416 2.7183 0.5 3.0
FunctionMeaningExample
sqrt(x)Square root (float)sqrt(49) → 7.0
pow(x, y)x to the power y (float)pow(3, 2) → 9.0
ceil(x)Smallest integer ≥ xceil(4.1) → 5
floor(x)Largest integer ≤ xfloor(-4.1) → -5
fabs(x)Absolute value (float)fabs(-3) → 3.0
factorial(n)n!factorial(4) → 24
gcd(a, b)Greatest common divisorgcd(12, 18) → 6
sin, cos, tanTrigonometry (radians)sin(radians(90)) → 1.0

random module

Random values change every run, so your output will differ from the sample below.

Python
import random
print(random.random())          # float 0.0 <= x < 1.0
print(random.randint(1, 6))     # dice: 1 to 6 (both included)
print(random.randrange(10, 50, 5))  # 10, 15, ... 45
print(random.choice(['Red', 'Green', 'Blue']))
0.6394267984578837 4 35 Green
Python
import random
# 4-digit OTP
otp = random.randint(1000, 9999)
print('Your OTP is', otp)
Your OTP is 5832
🧮 Exam favourite

"What are the possible outputs of random.randint(2, 4) * 10?" → 20, 30 or 40. For random.randrange(2, 4) only 2 or 3 (4 is excluded).

statistics module

Python
import statistics
marks = [85, 92, 78, 92, 66, 70]
print('Mean  :', statistics.mean(marks))
print('Median:', statistics.median(marks))
print('Mode  :', statistics.mode(marks))
Mean : 80.5 Median: 81.5 Mode : 92

Mean = sum ÷ count = 483 ÷ 6 = 80.5. Median = middle value of the sorted list [66, 70, 78, 85, 92, 92] = (78 + 85) ÷ 2 = 81.5. Mode = most frequent value = 92.

Frequency of each mark – 92 appears most (mode)0123667078859211112
Mode is the tallest bar

Creating your own module

Save the functions below as shapes.py. In another file in the same folder, write import shapes and call shapes.circle_area(7).

Python
# file: shapes.py  (your own module)
def circle_area(r):
    return 3.14159 * r * r

def square_area(s):
    return s * s
Python
import shapes
print(round(shapes.circle_area(7), 2))
print(shapes.square_area(9))
153.94 81

Summary & practice

  • Local variables live inside a function; global variables live outside.
  • Use global name to change a global inside a function.
  • Import styles: import m, import m as x, from m import f.
  • math, random (random, randint, randrange, choice), statistics (mean, median, mode).
✅ Practice

1) What can random.randrange(1, 10, 3) return? 2) Write a dice game: roll two dice and print "Double!" if both are equal. 3) What is printed? a = 10 → def f(): a = 20 → f(); print(a)

Answers: 1) 1, 4 or 7. 3) 10.

Frequently Asked Questions

What is the difference between a local and a global variable?
A local variable is created inside a function and can be used only inside it; it disappears when the function ends. A global variable is created outside all functions and can be read anywhere in the program.
What is the difference between random.random(), randint() and randrange()?
random() gives a float from 0.0 up to (not including) 1.0. randint(a, b) gives an integer from a to b including both. randrange(start, stop, step) works like range and does not include stop.
What is a module in Python?
A module is a .py file containing functions, variables and classes that can be imported and reused in other programs, for example math or random.
← Class 11 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicStrings: Slicing & Methods Your progress: 19 / 29 (66%) · Lesson 20 / 29 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free