Advanced Python Module Examples (random, math, sys, os)
RANDOM Module - Advanced Examples
Random OTP with 6 digits:
import random
otp = ''.join([str([Link](0, 9)) for _ in range(6)])
print('Your OTP is:', otp)
Random Sampling from List:
import random
names = ['Ram', 'Ravi', 'Kiran', 'Anu', 'Sara']
print('Selected students:', [Link](names, 3))
Weighted Random Choice:
import random
choices = ['Tea', 'Coffee', 'Juice']
weights = [1, 3, 1]
print('Random drink:', [Link](choices, weights=weights, k=1)[0])
Simulate Coin Toss:
import random
print('Coin toss result:', [Link](['Heads', 'Tails']))
Generate Random Even Numbers:
import random
print('Random even number between 2 and 100:', [Link](range(2, 101, 2)))
MATH Module - Advanced Examples
Calculate Logarithm:
import math
print('Log base 10 of 1000:', math.log10(1000))
Check Prime Using isqrt:
import math
n = 29
is_prime = all(n % i != 0 for i in range(2, [Link](n)+1))
print(f'{n} is prime:', is_prime)
Hypotenuse Calculator:
import math
a, b = 3, 4
print('Hypotenuse is:', [Link](a, b))
Factorial Calculator:
import math
print('Factorial of 5:', [Link](5))
Degrees to Radians Conversion:
import math
print('180 degrees in radians:', [Link](180))
SYS Module - Advanced Examples
Check Platform Info:
import sys
print('Platform:', [Link])
Recursion Limit:
import sys
print('Recursion limit:', [Link]())
Set New Recursion Limit:
import sys
[Link](2000)
print('New recursion limit:', [Link]())
Check Memory Size of Object:
import sys
num = 12345
print('Memory size of variable:', [Link](num), 'bytes')
Redirect Output to a File:
import sys
[Link] = open('[Link]', 'w')
print('This goes to file')
[Link]()
OS Module - Advanced Examples
Check OS Name:
import os
print('OS Name:', [Link])
Run Shell Command:
import os
[Link]('echo Hello from shell')
Get Environment Variables:
import os
print('PATH:', [Link]('PATH'))
Walk Through Directory:
import os
for root, dirs, files in [Link]('.'):
print('Current Path:', root)
print('Folders:', dirs)
print('Files:', files)
break
Create Nested Directories:
import os
[Link]('parent/child', exist_ok=True)
print('Nested folders created')