Posts

Showing posts from February, 2018

Installing a module using pip

Install through  pip . syntax pip install <modulename> Example pip install py-term pip install mysqlclient Learn Python with Dr B P Sharma Facebook:  https://www.facebook.com/drbpsharma.in Mobile    : +91 9810849501 Email      : bpsharma@gmail.com

Formatting String Output

Use + as concatenation operator Example Write a program to input a number and show factorial of it Solution 1 import math n=int(input("Enter a number")) msg="Factorial of " + str(n) + " is " + str(math.factorial(n)) print(msg) Solution 2 Using format specifiers like %d, %s, %f import math n=int(input("Enter a number")) msg="Factorial of %d is %d" % (n,math.factorial(n)) print(msg) Solution 3 Using placeholders {} with format() function import math n=int(input("Enter a number")) msg="Factorial of {0} is {1}".format(n,math.factorial(n)) print(msg)

Using math module

>>> import math >>> dir(math) ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc'] >>> print(math.factori...

Getting list of all functions in a module

First import the module and then use dir() function Example >>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', ...

User Defined Modules in Python

A module is a collection of function stored in a .py file like header file in C Example: Creating a module file # mymath.py module file def sum(a,b):     return a+b def product(a,b):     return a*b Using the functions from the module using import command import mymath as m s=m.sum(5,6) p=m.product(5,6) print(s) print(p) Learn Python with Dr B P Sharma Facebook:  https://www.facebook.com/drbpsharma.in Mobile    : +91 9810849501 Email      : bpsharma@gmail.com