Wednesday 1 April 2015

Python Django and stuff - Simply Amazing

http://www.bogotobogo.com/python/Django/Python_Django_tutorial_introduction.php    **

http://www.bogotobogo.com/python/pytut.php

Diff Frameworks:
http://www.sitepoint.com/top-10-front-end-development-frameworks/

Py frameworks: https://www.airpair.com/python/posts/django-flask-pyramid

Saturday 1 November 2014

Python Django Setup stuff

1. https://www.youtube.com/watch?v=uHCeLlD1le8
Good one.. short and clear..

2. install vitualenv: http://docs.python-guide.org/en/latest/dev/virtualenvs/
Cmd: pip install virtualenv
Django Version: https://www.djangoproject.com/
Steps to install Python:
1. Install Python
2. Install setuptools
3. install pip
4. install virtualenv.. **
5. install django

Friday 31 October 2014

String example in python

from string import lstrip


Str1="Welcome to PythoN"
strReplace="PYTHON"
strFind="Wel-come"

# Get sub-strings from main string..

print "Get first character at index '0': "+ Str1[0]
print "get entire string starting from index 2: "+ Str1[2:]
## Here second parameter is optional. if ignored, it give whole string.
print "get 2 characters from 0 index: "+ Str1[0:2]
print "get first 9 characters: "+ Str1[0:9]
print "get string from index 2-6: "+ Str1[2:9]
##Here first parameter is starting index and the second one is (index-1
print "get first 4 characters: "+ Str1[:4]
##here if first parameter is ignored, it gives 4 characters starting from index 0
print "Last character at index -1: "+ Str1[-1]

#Output:**************************
# Get first character at index '0': W
# get entire string starting from index 2: lcome to PythoN
# get 2 characters from 0 index: We
# get first 9 characters: Welcome t
# get string from index 2-6: lcome t
# get first 4 characters: Welc
# Last character at index -1: N

    #Raw String examples:
r1= r'Hello\\s'
print r1  #o/p: Hello\\s
print 'Hello\\s'    #o/p: Hello\s
print "Hello\s"     #o/p: Hello\s
print "Hello\\s"    #o/p: Hello\s
print "Hello\\\s"   #o/p: Hello\\s

#Triple QUote string:
t1= '''Welcome to Python tutorial..
Python is very simple and easy to learn (\t) programming language. \nPython is used in e-hacking .'''
print t1
## output:**************************
# Welcome to Python tutorial..
# Python is very simple and easy to learn (    ) programming language.
# Python is used in e-hacking .

print "+++++++++++String function eg:+++++++++++++"
s1= "WELcome to PYTHON"
print s1.capitalize() # Welcome to python
print s1.title()    #Welcome To Python
print s1.center(30)#      WELcome to PYTHON    
# count(str, beg= 0,end=len(string))
# Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given
print "count of substring 't' in s1: "+ str(s1.count("t"))
print "count of substring 'o' in s1: "+ str(s1.count("o", 0, len(s1)))
print 'Length of the string: ' + str(len(s1)) + '''
and we can also find the length if the string using s1.__len()__: ''' + str(s1.__len__())

print s1.endswith("ON")  #True
print "endswith: "+ str(s1.endswith("ON")) #True
print "endswith: "+ str(s1.endswith("Test")) #False
print "startswith: "+ str(s1.startswith("WEL")) #True
print "startswith: "+ str(s1.startswith("Test")) #False
# Here startswith and endswith returns True or False. Hence convert them b4 appending to a string.

##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# find(str, beg=0 end=len(string))
s1="Venu GOPALA krisHNA"
print s1.find("ALA", 0, len(s1)) #8
print s1.find("GOP")        #5
print "s1.find(\"V\"):-- "+ str(s1.find("V"))   #s1.find("V"):-- 0
if s1.find("Venu")>=0:      #True
    print s1.find("Venu")       #0
print s1.find('kr')     #12
print s1.find('kr', 13, len(s1))    # -1

##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#Length of the string:
print 'length of the string: '+ str(len(s1))
print 'length of string2: '+ str(len('v'))
# we can also find the length of the string using __len__() function.
print "length of the string: "+ str(("Hello").__len__())
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# index(str, beg=0, end=len(string))
# Same as find(), but raises an exception if str not found
s1="Venu GOPALA krisHNA"
print "index of GOPALA: "+ str(s1.index("GOPAL"))  # index of GOPALA: 5
#print "index of a string doesn't exist: "+ str(s1.index("XYZ"))
#Output: ValueError: substring not found ********** ERROR **********
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# isalnum() : Returns true if string has at least 1 character and all characters
#  are alphanumeric and false otherwise
S1= "Testing123"
S2= "Python"
S3= "123123123123"
S4= "#$%"
S5= "Venu GOPAL"
print S1.isalnum() #True
print S2.isalnum() #True
print S3.isalnum() #True
print S4.isalnum() #False  due to special characters.
print S5.isalnum() #False due to Space character
print "".isalnum()  #False
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
print "isalpha examples: "
# isalpha() :Returns true if string has at least 1 character and all characters are alphabetic and false otherwise
print S1.isalpha() #False
print S2.isalpha() #True
print S3.isalpha() #False
print S4.isalpha() #False  due to special characters.
print S5.isalpha() #False due to Space character
print "".isalpha()  #False
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# isdigit() : Returns true if string contains only digits and false otherwise
print "isdigit examples: "
print S1.isdigit() #False
print S2.isdigit() #False
print S3.isdigit() #True
print S4.isdigit() #False  due to special characters.
print S5.isdigit() #False due to Space character
print "".isdigit()  #False
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
print "Other String examples: "
print "testing ".isupper()      #False
print "testing 123".islower()   #True
print "TEST".isupper()      #False
print "hello PYthon".upper()    #HELLO PYTHON
print "hello PYTHON".lower()    #hello python
print "Bank of america".title()    #Bank Of America
print "HELLO PYthon".capitalize()   #Hello python
print "HELLO python".swapcase()     #hello PYTHON
##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# print "123421".isnumeric()
#+++ERROR: AttributeError: 'str' object has no attribute 'isnumeric'
# isnumeric can be used only with unicode string contains only numeric characters
print u"123421".isnumeric() #True
print u"abc".isnumeric()    #False
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
print "".isspace() #False
print " ".isspace() #True
print "\t".isspace() #True
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Strip strings examples:
S1= "   Leading  White Space"
S2="Trailing white Space     "
S3= "    Space at beginning and end of the string    "
print "Length of S1 before lstrip(): "+ str(len(S1))
print "Size of S1 after left Strip: "+ str(len(S1.lstrip()))

# Length of S1 before lstrip(): 23
# Size of S1 after left Strip: 20

print "Length of S2 before lstrip(): "+ str(len(S2))
print "Size of S2 after left Strip: "+ str(len(S2.rstrip()))
# Length of S2 before lstrip(): 25
# Size of S2 after left Strip: 20

print "Length of S3 before lstrip(): "+ str(len(S3))
print "Size of S3 after left Strip: "+ str(len(S3.strip()))
# Length of S3 before lstrip(): 48
# Size of S3 after left Strip: 40

# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
##Replace, Split, Join examples:
# replace(old, new [, max]): Replaces all occurrences of old in string with new or at most max occurrences if max given

S1="Bank of America"
print S1.replace("America", "India")    #Bank of India
# if Old sub string is found, then it replaces with new sub string.
# else, the main string remains the same..
print S1.replace("Maha", "India")   #Bank of America

# split(str="", num=string.count(str))
# Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at
# most num substrings if given

sp1=S1.split(" ")
print sp1   #SP1 is a list
print S1.split("a")  #split by character 'a'

# join(seq) :Merges (concatenates) the string representations of elements in sequence seq into a string, with
# separator string
str = "-";
seq = ("This", "IS", "a Sequence"); # This is sequence of strings.
# sequence -- This is a sequence of the elements to be joined.
print str.join( seq );
print "@".join( seq );

strJoinBy="/"
print strJoinBy.join(sp1)
# Here we can join any list/tuple
print "Length of the string: ", len(S1);  
# Here we don't have to convert to str if we use comma ',''

Loops in python

import time
i=1


while i<10:
    print i
    i=i+1  
   

i=1
while True:
    print "This prints once a minute."
#     time.sleep(5)  # Delay for 1 minute (60 seconds)
    if (i==20):
        break
    i=i+1
    print "incrementing i value by 1: "+ str(i)
       
# num = raw_input("Enter a number :")
# print type(num)      
print "Execute until while loop condition becomes false"
i=1
while i<5:  
    print i  
    i=i+1
else:
    print "FIrst Eg: Else block executed...."
   
print "Second loop: While loop terminated. Condition remains True so else block of While won't be executed.."
i=1
while i<5:
    if(i==3): break
    print i  
    i=i+1
else:
    print "Else block.."
   
Str1= "Venu"

for each_letter in Str1:
    print each_letter


l1= ['v', 1, "30", [1,2,3,4], (9,8,7,6)]
for each in l1:
    print type(each)
   
   
t1=(1,2,3,4,'4')
for every in t1:
    print every
   
print "Length of the tuple: "+  str(len(t1))

t1=(1,2,3,4,'4')
for index in range(len(t1)):
    print t1[index]
   
#Range using for loop and else block..
for i in range(10, 15):
    print i  
else: print "Print else block of for loop"

Dictionary eg in python


dict1= {"name":"venu", "company":"cig...", "proj": "BOA"}

print dict1.has_key("proj")
print dict1.__len__()
print dict1.keys()
print dict1.values()
print dict1
print dict1["name"]
print str(dict1)
print "dictionary size: ", len(dict1)
i=10
j=11

def sum1(a, b):
    return a+b

def mul1(a,b):
    return a*b

def substract(a,b):
    return a-b

def div(a,b):
    return a/b

dict2= {1: sum1(i, j),
        2: mul1(i, j),
        3: substract(i, j),
        4: div(i, j)
        }

print dict2[1]
print dict2[2]
print dict2[3]
print dict2[4]


l1= [10,20, 30, 40]
print 10 in l1

print id(l1)
print "size: "+ str(l1.__len__())
l2= l1
l1.append(50)

print l1.__len__()

print l2.__len__()
print id(l2)


x= 10
if x:
    print x
else:
    print "T"


print "testing",
print l1,
print "hello"

Files in Python eg

import os
import tempfile
strPath= "C:\New folder\Testing.txt"
x1 = open(strPath, "r+")
print x1.readlines()    # Read All the lines...
print "Where is the file pointer: ", x1.tell()
x1.seek(5)  # Place the control at 5th character..
print "Control is placed at first character: ", x1.read(1)
print "Where is the file pointer: ", x1.tell()

x1.seek(0)
print "printing lines"
l1= []  #Declare an empty List
for line in x1:
    print len(str(line).strip()) , ": and line text: ", line

print"+++++++++++Read line by line++++++++++++++++++"
x1.seek(0)
while True:
    li= x1.readline()
    if not li: break
    print li
print"+++++++++++++++++++++++++++++"
x1.close()

print os.getcwd()

try:
    cf= open("C:\New folder\Testing1.txt", "w+")
    cf.write("THis is my text")
    filePos= cf.tell()
    print "File pointer positioned at: ", filePos
    cf.seek(0)
   
    print cf.readlines()
    cf.close()
except Exception, e:
    print e
else: print "File created.."


try:
    af= open("C:\New folder\Testing1.txt", "a+")
#     af.append("Second line data")
    af.writelines("\nHello")  
    af.close()
except Exception, e:
    print e
finally:
    pass

dat1= "Second line data"

f1 = open("C:\New folder\Testing1.txt","a") ## file open in appending mode i.e 'a'  
f1.writelines("\n" +dat1)

f1.close()


print tempfile.mkstemp(".txt", "test", "" , True )
print tempfile.gettempdir()
print tempfile.tempdir