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.
Local and global variables
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 herepercent 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.
x = 5
def change():
x = 50 # creates a NEW local x
print('Local x =', x)
change()
print('Global x =', x)The global keyword
To change a global variable inside a function, declare it with global.
count = 0
def visit():
global count # use the global variable
count += 1
visit(); visit(); visit()
print('Visitors =', count)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.
Ways to import a module
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))
| Statement | How you call |
|---|---|
import math | math.sqrt(9) |
import math as m | m.sqrt(9) |
from math import sqrt | sqrt(9) |
from math import * | sqrt(9) (imports everything – avoid in big programs) |
math module
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))
| Function | Meaning | Example |
|---|---|---|
| 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 ≥ x | ceil(4.1) → 5 |
| floor(x) | Largest integer ≤ x | floor(-4.1) → -5 |
| fabs(x) | Absolute value (float) | fabs(-3) → 3.0 |
| factorial(n) | n! | factorial(4) → 24 |
| gcd(a, b) | Greatest common divisor | gcd(12, 18) → 6 |
| sin, cos, tan | Trigonometry (radians) | sin(radians(90)) → 1.0 |
random module
Random values change every run, so your output will differ from the sample below.
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']))
import random
# 4-digit OTP
otp = random.randint(1000, 9999)
print('Your OTP is', otp)"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
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 = 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.
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).
# file: shapes.py (your own module)
def circle_area(r):
return 3.14159 * r * r
def square_area(s):
return s * simport shapes print(round(shapes.circle_area(7), 2)) print(shapes.square_area(9))
Summary & practice
- Local variables live inside a function; global variables live outside.
- Use
global nameto 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).
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.
