Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vijayanandrp/ffa9f999bacf32753a16915ff204bac0 to your computer and use it in GitHub Desktop.
Save vijayanandrp/ffa9f999bacf32753a16915ff204bac0 to your computer and use it in GitHub Desktop.
How to learn Python in a 15 Minutes !! Believe its very cool language to have fun and learn :)
#!/usr/bin/env python
# I have learned these codes from Learning Python O'reilly
# Python 2.7
"""
#! is often called hash bang or shebang
/user/bin/python - path of the python executable
#!/usr/bin/python - Unix Styled Executable Scripts (If u know exact path of the python binary)
#!/usr/bin/env python - No matter python lives on your system
"""
def about_python():
"""
@desc Some facts about the python
"""
interesting_python = """
Few Interesting facts about the Python
=================================================================================================
[*] The Standard implementation of Python is written in portable ANSI C
(Python code runs close to C speed anyhow that involves C code in the interpreter)
[*] Written By Guido Van Rossum
(Python named after comedy series 'Monty Python's Flying Circus')
[*] Python is the Object-Oriented Scripting Language.(Python sees the everything as a object)
[*] Python is a general purpose programming language that blends procedural (statement-based),
functional and object-oriented (class-based) paradigms
[*] Top Down Approach - step by step control flow
[*] Python Source code is compiled to the intermediate format called 'Byte Code' (using interpreter)
then routed to 'Python Virtual Machine' (PVM) runtime engine of python
--------------------------------------------------------------
| Python(.py) --> Byte Code (.pyc) --> Python Virtual Machine |
--------------------------------------------------------------
[*] Byte Code (Low level ) provides the portability, as it a platform independent
[*] Python code must always be run by this interpreter
[*] Python's standard library comes with POSIX bindings and support for all Operating Systems
(Portable Operating Systems Executable)
[*] Apart from the polymorphism, operator overloading and multiple inheritance
Python includes generators, comprehensions, closures, maps, decorators, anonymous functions
lambdas and first class functions objects
[*] PowerFul tool, Mixable and relatively easy to use
[+] Dynamic Typing (auto types identification)
[+] Automatic Memory Management
[+] Programming in the large support
[+] Built-in Object types
[+] Built-in tools
[+] Library utilities
[+] 3rd party utilities
"""
print interesting_python
company_uses_python = """
Famous Company or Organization that uses Python Today
=================================================================
[*] Google
[*] DropBox
[*] Raspberry Pi
[*] Google App Engine
[*] Maya
[*] NASA (Cryptography and Intelligence)
[*] Bit Torrent
[*] Intel, Cisco, HP, Seagate and Qualcomm (Hardware testing)
[*] JP Morgan
"""
print company_uses_python, '\n'
python_concepts = """
The Python Conceptual Hierarchy
================================================================
In python, data takes the form of objects. Everything is an object in a python script.
Objects are the most fundamental notion in python programming.
Python can be decomposed into modules, statements, expressions and object as follows:
1. Programs are composed of modules
2. Modules contain statements
3. Statements contain expressions
4. Expressions create and process objects
---------------------------------------------------------------------------------
| program -> modules -> statements -> expressions -> create and process objects |
---------------------------------------------------------------------------------
"""
print python_concepts, '\n'
python_data_types = """
Object Type Examples literals/creation
===========================================================================
Number 1234, 3.145, 3+4j, 0b111, Decimal(), fraction()
Strings 'spam', Bob's", b'a\x01c', u'sp\xc4m'
Lists [1, [2, 'three'], 4.5], list(range(10))
Dictionaries {'food': 'spam', 'taste': 'yum'}
Tuples tuple('spam'), ('1', 'spam', 4, 'U')
Files open('eggs.txt'), open(r'C:\ham.bin', 'wb')
Sets set('abc')
Other core types Boolean, types, None
Program unit types Functions, modules, classes
Implementation Compiled code, stack tracebacks
related types
"""
print python_data_types, '\n'
# In-built commands or options
def printing_comments():
"""
@desc This function shows the different methods for printing the values
"""
about = "\nprint and comments \n================================="
print about
'''
Multiple Line Comments
You can type your function description or anything you want
'''
print 'Hello World!'
print('Printing the string as a calling function')
print(2**8)
print 'Spam!' * 8 # Single line Comments can be given here
x = 'Py'
print(x*8)
print '%s, eggs and %s' % ('Spam', 'SPAM!')
print '{}, eggs and {} '.format('Spam', "SPAM!")
print '{0}, eggs and {1}'.format('Spam', 'SPAM!')
print '{:,.2f}'.format(296999.23674)
print '%.2f | %+05d' % (3.14159, -42)
run_time_value = raw_input("Enter some value here : ") # Use input() in python 3.x
print "You have entered, ", run_time_value
try:
import os
executable_value = input("Enter vulnerable value here : ")
# Don't use input() is vulnerable functions as it execute the commands directly without any input validation
# Example: enter os.getcwd()
print "You have entered, ", executable_value
except Exception as error:
print "Error: ", str(error)
def use_of_imports():
about = "\n importing modules \n=============================================="
print about
import os
print "os.getcwd() --> ", os.getcwd()
from os import getcwd # Directly calling the function
# from myfile import title is not recommended
# as the namespace replace the other functions names without any warnings
from imp import reload # Used to reload the module namespaces
reload(os)
print "getcwd() --> ", getcwd()
vijay = 'Wait for the myscript1 module'
file_path ='/not/a/correct/path/'
print "Vijay = ", vijay
print 'Loading the value from myscript1.py'
with open("myscript1.py", 'w+') as file:
file.write("#!/usr/bin/python \n")
file.write("import os \n")
file.write('''file_path = os.getcwd(); \n''')
file.write('''vijay = "My Name is Vijay Anand"''')
file.close()
exec(open('myscript1.py').read()) # Another Method loading the module the program
print "Look here now -->>> ", vijay
print "File_path -->>> ", file_path
def help_option():
about = "\n Help Options \n=============================================="
print about
import sys
print "Directory Options", dir(sys), '\n'
print "List of options for sys.path, ", dir(sys.path)
print "Usage of sys.path : ", help(sys.path)
def for_loop():
about = "\n for loop conditions \n=============================================="
print about
for x in 'spam':
print x
def python_numbers():
about = "\n Python Number Data types \n=============================================="
print about
print '123 + 222 = ', 123 + 222, type(123 + 222)
temp = 1.5 * 25
print '1.5 * 25 = ', temp, type(temp)
print '2 * 100 = ', 2 ** 100
print 'len(str(2 ** 1000000)) = ', len(str(2 ** 1000000))
def python_strings():
about = "\n Python String Data types \n=============================================="
print about
S = 'Spam!'
print S[0]
print S[1]
print "Reverse of the String, ", S[::-1]
print(S[-2])
print S[:] # String slicing concept in python
print S[1:3]
print S[:3]
print S[1:]
print len(S)
print S + 'xyz'
print S * 8
S = 'Z' + S[1:] # Concatenation
print S
S = 'nobody cares nobody'
print S
L = list(S)
print L
L = list('every') + L[2:]
print ''.join(L)
B = bytearray('spam')
B.extend('eggs!')
print 'ByteArray = ', B
print B.decode()
S = 'SpamSpam'
print S.find('pam')
print S.replace('pa', 'ABCD')
print S.upper()
print S.lower()
print S.isalpha()
line = 'aaa,bbb,ccc,ddd'
print line.split(',')
line = 'aaa,bbb,ccc,dd\n\t'
print line.rstrip()
S = 'A\nB\tC'
print len(S)
print "ord(\\n) = ", ord('\n') # \n byte with binary value 10 in ASCII
S = 'A\0B\0C'
print len(S), S
print 'spam'.encode('utf8')
print 'spam'.encode('utf16').decode('utf16')
def python_lists():
about = "\n Python List Data types \n=============================================="
print about
L = [123, 'spam', 1.23]
print len(L)
print L[0]
print L[:-1]
L = L + [4, 5, 6]
L.reverse()
print 'Reverse: ', L
L.sort()
print 'Sort = ', L
print L * 2
L.append('NI')
print L
L.pop(4) # Pop the 4th element
print L
print L[::-1]
def python_comprehensions():
about = "\n Python Comprehension Data types \n=============================================="
print about
M = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print M
print M[1][2]
for row in M:
print row
col2 = [row[1] for row in M]
print col2, '\n'
col3 = [row[1] + 1 for row in M]
print col3
print [row[1] for row in M if row[1] % 2 == 0]
diagonal_matrix = [M[i][i] for i in [0, 1, 2]]
print 'Diagonal Matrix = ', diagonal_matrix
doubles = [c * 2 for c in 'spam']
print 'Doubles = ', doubles
print list(range(10))
print list(range(-6, 7, 2))
print [[x**2, x**3] for x in range(4)]
print [[x, x/2, x*x] for x in range(-6, 7, 2) if x > 0]
G = (sum(row) for row in M) # Generator
print next(G)
print next(G)
print next(G)
# print next(G) Throws an error
print list(map(sum, M)) # Function Mapping
print {sum(row) for row in M}
print {i: sum(M[i]) for i in range(3)}
print [ord(x) for x in 'VijayAnand']
print {ord(x) for x in 'VijayAnand'}
print {x: ord(x) for x in 'VijayAnand'}
def python_dict():
about = "\n Python Dictionary Data types \n=============================================="
print about
D = {'food': 'Noodles', 'quantity': 4, 'color': 'pink'}
print D['food']
D['quantity'] += 1
print D
# Method 1 for creating dictionary
D = {}
D['name'] = 'Bob'
D['job'] = 'dev'
D['age'] = 40
print D
# Method 2 for creating dictionary
bob1 = dict(name='Bob', age=40, job='dev')
print bob1
# Method 3 for creating dictionary
bob2 = dict(zip(['name', 'age', 'job'], ['Bob', 40, 'dev']))
print bob2
# Nested Dictionaries
rec = {'name': {'first': 'Bob', 'last': 'Smith'},
'jobs': ['dev', 'mgr'],
'age': 40.5}
print rec['name']
print "Last Name is %s " % (rec['name']['last'])
print rec['jobs']
rec['jobs'].append('CEO')
print rec['jobs']
print rec['jobs'][-1]
def python_tuples():
about = "\n Python Tuples Data types \n=============================================="
print about
T = (1, 2, 3, 4)
print len(T)
T = T + (5, 6)
print T
print T.index(5)
print T.count(4)
T = 'spam', 3.0, [11, 22, 33]
print T
# Library or Modules
def lib_math():
about = "\n math module \n=============================================="
print about
try:
import math
print "Importing Math module"
except ImportError, error:
print "Error: ", str(error)
return -1
print math.pi
print math.sqrt(85)
def lib_random():
about = "\n random module \n=============================================="
print about
try:
import random
print "Importing random module"
except ImportError, error:
print "Error: ", str(error)
print random.random()
print random.randint(25, 35)
print random.choice([1, 2, 3, 4])
def lib_os():
about = "\n os (Operating System) module \n=============================================="
print about
import os
print "Current Working directory ", os.getcwd()
print "To execute the commands in operating system os.system()"
os.system("type chmod")
# type is used to locate the path of the builtin options binary in terminal
def lib_sys():
about = "\n sys (System) module \n=================================================="
print about
import sys
print("Your Operating System is "+sys.platform)
def main():
about_python()
printing_comments()
use_of_imports()
help_option()
python_numbers()
python_strings()
python_lists()
python_comprehensions()
python_dict()
python_tuples()
for_loop()
lib_math()
lib_random()
lib_os()
lib_sys()
if __name__ == '__main__':
try:
main()
except Exception, er:
print "Error: ", str(er)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment