|
| 1 | +# How to Run? Open Terminal> python3 libEg1.py |
| 2 | +# Read the code comments and output on the terminal |
| 3 | + |
| 4 | +# Objective: Know about standard built-in library |
| 5 | + |
| 6 | +# Note: avoid using 'from os import *'. |
| 7 | +# This will keep 'os.open()' from shadowing the built-in 'open()' function |
| 8 | +import os |
| 9 | + |
| 10 | +# Return the currect directory |
| 11 | +print('Current Directory: ', os.getcwd()) |
| 12 | + |
| 13 | +# Run command mkdir in the system shell |
| 14 | +# Return '0' means directory got created successfully |
| 15 | +# Return '256' means directory got created failed because its already exists |
| 16 | +print('Create directory "temp": ', os.system('mkdir temp')) |
| 17 | + |
| 18 | +# Change current working directory |
| 19 | +print('Change currect directory to "temp": ', os.chdir('temp')) |
| 20 | + |
| 21 | +print('\n') |
| 22 | + |
| 23 | +# Return a list of all module functions |
| 24 | +print('List of all module functions: ', dir(os)) |
| 25 | + |
| 26 | +print('\n') |
| 27 | + |
| 28 | +# System libraries |
| 29 | +import sys |
| 30 | + |
| 31 | +# Arguments are stored in the sys module's argv attributes as a list |
| 32 | +print('Argv list: ', sys.argv) # python3 libEg1.py Hello => ['libEg1.py', 'hello'] |
| 33 | + |
| 34 | +print('\n') |
| 35 | + |
| 36 | +# Output |
| 37 | +sys.stdout.write('[STDOUT]: This is ok\n') |
| 38 | + |
| 39 | +# Error output redirection and program termination |
| 40 | +sys.stderr.write('[STDERR]: This is not ok\n') |
| 41 | + |
| 42 | +print('\n') |
| 43 | + |
| 44 | +# Mathematics |
| 45 | +import math |
| 46 | + |
| 47 | +print( math.cos(math.pi / 4) ) |
| 48 | +print( math.log(1024, 2) ) |
| 49 | + |
| 50 | +print('\n') |
| 51 | + |
| 52 | +# Random |
| 53 | +import random |
| 54 | + |
| 55 | +print('Random choice: ', random.choice(['JavaScript', 'Python', 'Go']) ) # execute multiple times to see the output |
| 56 | + |
| 57 | +# Statistics |
| 58 | +import statistics |
| 59 | + |
| 60 | +data = [2.5, 1.57, 4.32, 5.67, 8.45] |
| 61 | +print('Statistics mean: ', statistics.mean(data) ) |
| 62 | + |
0 commit comments