0% found this document useful (0 votes)
36 views4 pages

Advanced Python Library Examples

The document provides advanced examples of using Python's RANDOM, MATH, SYS, and OS modules. It includes code snippets for generating random OTPs, calculating logarithms, checking platform info, and creating nested directories. Each example demonstrates practical applications of the respective modules in Python programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views4 pages

Advanced Python Library Examples

The document provides advanced examples of using Python's RANDOM, MATH, SYS, and OS modules. It includes code snippets for generating random OTPs, calculating logarithms, checking platform info, and creating nested directories. Each example demonstrates practical applications of the respective modules in Python programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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')

Common questions

Powered by AI

To generate a random even number within a specific range using Python, you can use the 'random.choice' function from the 'random' module along with the 'range' function. By specifying the start, stop, and step of the range, you ensure all values are even. For example, to generate a random even number between 2 and 100, you provide the range parameters as (2, 101, 2) so the range includes only even numbers. Then, 'random.choice' selects randomly from those numbers .

The 'os.name' attribute in Python identifies the operating system Python is running on, such as 'posix' for UNIX-based systems and 'nt' for Windows. By using this attribute in conditional statements, scripts can execute different commands or code paths depending on the detected OS, which aids in ensuring the script can run correctly across different platforms without manually modifying OS-specific code segments .

The 'math.hypot()' function simplifies the calculation of a hypotenuse by automatically performing the Pythagorean theorem under the hood. When given the lengths of two sides of a right triangle as arguments, such as 3 and 4, 'math.hypot(3, 4)' directly computes the square root of the sum of the squares of these numbers, yielding the hypotenuse length, 5, which simplifies the process compared to manually coding the calculation .

Logging to a console involves printing outputs directly to the command line interface where the script is run, which is the default behavior for 'print' statements. Redirecting output to a file using sys involves changing the file object that 'sys.stdout' references. By doing 'sys.stdout = open('output.txt', 'w')', all subsequent print statements write to 'output.txt' instead of displaying on the console, allowing persistent logging and subsequent review independent of the runtime environment .

The 'random.choices()' function within the 'random' module can implement weighted random choices by providing a list of choices and a corresponding list of weights that specify the relative likelihood of each choice. For instance, if you have a list of drinks ['Tea', 'Coffee', 'Juice'] and you want 'Coffee' to be more likely than 'Tea' and 'Juice', you can assign weights like [1, 3, 1]. Calling random.choices with these parameters will result in a higher probability of selecting 'Coffee'. In the example, the code 'random.choices(choices, weights=weights, k=1)[0]' randomly selects one item considering the assigned weights .

Changing the recursion limit in Python using the sys module by calling 'sys.setrecursionlimit()' allows deeper recursion than the default, which can be useful for algorithms requiring significant recursion levels. However, this increases the risk of a stack overflow since each recursive call consumes stack space. Setting a high limit without corresponding increases in stack size can crash the Python interpreter if the actual recursion exceeds available memory .

A number can be checked for primality using the 'math.isqrt' function from the math module for efficient calculation. For instance, to determine if 29 is a prime number, you divide 29 by all integers up to the integer square root of 29 (inclusive), which significantly reduces the number of divisions needed compared to checking up to 29 itself. The code snippet 'all(n % i != 0 for i in range(2, math.isqrt(n)+1))' evaluates to True if none of the numbers divide 29 evenly, confirming it is prime .

The 'os.walk()' function provides a method for systematic traversal of a directory tree by yielding a tuple for each directory it encounters. This tuple includes the current directory path, a list of the directories within, and a list of the files within. Typically used within a loop, 'os.walk' facilitates actions such as reading, modifying, or analyzing files across entire directory structures when combined with file-handling logic .

The 'os.makedirs()' function offers the advantage of creating an entire directory tree in one call, whereas 'os.mkdir()' creates only a single directory. With 'os.makedirs()' and the 'exist_ok=True' parameter, Python can create directories without raising an error if the target directory structure already exists, providing a more robust and versatile solution for setting up directory hierarchies with minimal code .

Environment variables in Python can be accessed using 'os.environ.get()', which retrieves the value of a specified environment variable. For example, 'os.environ.get('PATH')' obtains the system's PATH environment variable. This access is useful for obtaining system configuration details and customizing script behavior based on the specific environment, such as setting different file paths or URLs in development versus production environments .

You might also like