Python Modules
#Python Module example
def add(a, b):
"""this program adds two
numbers and return the
result"""
result=a+b
return result
>>>import example
>>>example.add(4,5.5)
9.5
>>import math
>>print("the value of pi
is",math.pi)
when you run the program,the output will be:
the value of pi is 3.141592653589793
import with renaming
import math as m
print("the value of pi is",
m.pi)
python
from..import statement
from math import pi
print("the value of pi
is",pi)
>>>from math import pi, e
>>>pi
3.141592653589793
>>>e
2.718281828459045
Import
all names
Python Module Search Path
>>> import sys
>>> sys.path
['', 'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
the dir() built-in function
>>>dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']
python numbers, type conversion and mathematics
a=5
#output:<class'int'>
print(type(a))
#output:<class'float>
print(type(5.0))
#output:(8+3j)
c=5+3j
print(c+3)
#output:true
print(isinstance(c ,complex))
Type Conversion
>>>1+2.0
3.0
>>>int(2.3)
2
>>>int(-2.8)
-2
>>>float(5)
5.0
>>>complex('3+5j')
(3+5j)
Python Decimal
import decimal
>>>print(0.1)
0.1
>>>print(decimal.Decimal(0.1))
decimal('0.1000000000000000055511151231257827021181583404541015625')
from decimal import decimal as D
>>>print(D('1.1')+D('2.2'))
decimal('3.3')
>>>print(D('1.2')*D('2.50''))
decimal('3.000')
Python Fractions
import fractions
print(fractions.Fraction(1.5))
print(fractions.Fraction(5))
print(fractions.Fraction(1,3))
OUTPUT
3/2
5
1/3
import fractions
print(fractions.Fraction(1.1))
#As float
#output:24769797950553773/2251799813685248
print(fractions.Fraction('1.1'))
#As string
#output:11/10
from fractions import
Fraction as F
#output:2/3
print(F(1,3)+F(1,3))
#output:6/5
print(1/F(5,6))
#output:false
print(F(-3,10)>0)
#output:true
print(F(-3,10)<0)
Python Mathematics
import math
#output: 3.141592653589793
print(math.pi)
#output: -1.0
print(math.cos(math.pi))
#output: 22026.465794806718
print(math.exp(10))
#output: 3.0
print(math.log10(1000))
#output: 1.1752011936438014
print(math.sinh(1))
#output: 720
print(math.factorial(6))
import random
#output: 16
print(random.randrange(10,20))
x=['a','b','c','d','e']
#get random choice
print(random.choice(x))
#shuffle x
random.shuffle(x)
#print the shuffled x
print(x)
0 comments:
Post a Comment