DEV Community

Md Manawar Iqbal
Md Manawar Iqbal

Posted on

Python Cheat Sheet 1

Here is list of some important Python code snippet

Python Cheat Sheet 1

1:Check python version:

import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)

Enter fullscreen mode Exit fullscreen mode

2:Current Date and Time:

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Enter fullscreen mode Exit fullscreen mode

3:Print the documents of Python built-in function(s)

print(abs.__doc__)


Enter fullscreen mode Exit fullscreen mode

4:Print the calendar of a given month and year

import calendar
y = int(input("Input the year : "))
m = int(input("Input the month : "))
print(calendar.month(y, m))


Enter fullscreen mode Exit fullscreen mode

5:Create a histogram from a given list of integers

def histogram( items ):
    for n in items:
        output = ''
        times = n
        while( times > 0 ):
          output += '*'
          times = times - 1
        print(output)

histogram([2, 3, 6, 5])


Enter fullscreen mode Exit fullscreen mode

6:Check whether a file exists using Python

import os.path
print(os.path.exists('main.txt'))
print(os.path.exists('main.py'))

Enter fullscreen mode Exit fullscreen mode

7:Check whether Python shell is executing in 32bit or 64bit mode on OS

import platform, struct
print(platform.architecture()[0])
print(struct.calcsize("P") * 8)


Enter fullscreen mode Exit fullscreen mode

7:Get OS name, platform and release information

import platform
import os
print("Name of the operating system:",os.name)
print("\nName of the OS system:",platform.system())
print("\nVersion of the operating system:",platform.release())

Enter fullscreen mode Exit fullscreen mode

8:Locate Python site-packages

import site; 
print(site.getsitepackages())
Enter fullscreen mode Exit fullscreen mode

9:Call an external command in Python

from subprocess import call
call(["ls", "-l"])
Enter fullscreen mode Exit fullscreen mode

10:Get the path and name of the file that is currently executing

import os
print("Current File Name : ",os.path.realpath(__file__))
Enter fullscreen mode Exit fullscreen mode

11:Find out the number of CPUs using

import multiprocessing
print(multiprocessing.cpu_count())

Enter fullscreen mode Exit fullscreen mode

12:Determine profiling of Python programs

import cProfile
def sum():
    print(1+2)
cProfile.run('sum()')

Enter fullscreen mode Exit fullscreen mode

13:Access environment variables

import os
# Access all environment variables 
print('*----------------------------------*')
print(os.environ)
print('*----------------------------------*')
# Access a particular environment variable 
print(os.environ['HOME'])
print('*----------------------------------*')
print(os.environ['PATH'])
print('*----------------------------------*')

Enter fullscreen mode Exit fullscreen mode

14:Get the current username

import getpass
print(getpass.getuser())

Enter fullscreen mode Exit fullscreen mode

15:Find local IP addresses using Python's stdlib
import socket

print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] 
if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), 
s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, 
socket.SOCK_DGRAM)]][0][1]]) if l][0][0])

16:Get height and the width of console window
def terminal_size():
    import fcntl, termios, struct
    th, tw, hp, wp = struct.unpack('HHHH',
        fcntl.ioctl(0, termios.TIOCGWINSZ,
        struct.pack('HHHH', 0, 0, 0, 0)))
    return tw, th

print('Number of columns and Rows: ',terminal_size())

Enter fullscreen mode Exit fullscreen mode

17:Get execution time

import time
def sum_of_n_numbers(n):
    start_time = time.time()
    s = 0
    for i in range(1,n+1):
        s = s + i
    end_time = time.time()
    return s,end_time-start_time

n = 5
print("\nTime to sum of 1 to ",n," and required time to calculate is :",sum_of_n_numbers(n))

Enter fullscreen mode Exit fullscreen mode

18:Get the command-line arguments passed to a script

import sys
print("This is the name/path of the script:"),sys.argv[0]
print("Number of arguments:",len(sys.argv))
print("Argument List:",str(sys.argv))

Enter fullscreen mode Exit fullscreen mode

19:Test whether the system is a big-endian platform or little-endian platform

import sys
print()
if sys.byteorder == "little":
    #intel, alpha
    print("Little-endian platform.")
else:
    #motorola, sparc
    print("Big-endian platform.")
print()

Enter fullscreen mode Exit fullscreen mode

20:Get the ASCII value of a character

print()
print(ord('a'))
print(ord('A'))
print(ord('1'))
print(ord('@'))
print()

Enter fullscreen mode Exit fullscreen mode

21:Create a copy of its own source code

def file_copy(src, dest):
    with open(src) as f, open(dest, 'w') as d:
        d.write(f.read())
        file_copy("untitled0.py", "z.py")
        with open('z.py', 'r') as filehandle:
            for line in filehandle:
                print(line, end = '')
Enter fullscreen mode Exit fullscreen mode

22:Get the system time:

import time
print()
print(time.ctime())
print()

Enter fullscreen mode Exit fullscreen mode

23:Get the name of the host on which the routine is running

import socket
host_name = socket.gethostname()
print("Host name:", host_name)

Enter fullscreen mode Exit fullscreen mode

24:Convert an integer to binary keep leading zeros

x = 12
print(format(x, '08b'))
print(format(x, '010b'))

Enter fullscreen mode Exit fullscreen mode

25:Convert decimal to hexadecimal:

x = 30
print(format(x, '02x'))
x = 4
print(format(x, '02x'))


Enter fullscreen mode Exit fullscreen mode

Top comments (0)