Python Learning

Website: www.python.org

Structure
Input: variable
Process: basic calculation, logical calculation
Output: print, write to file, load into database

Number and Math
18/7-->2
18.0/7.0-->2.5714285714285716
9%4-->1
8**3-->512

Function
print(<variable>) / print <variable>: (integer, string, float)
Example: 
print(a)
print x, y, z
print(x,y,z)
print(1)
print(1.345)
print("abc")

Print format 
print(format(<value>,'m.nf'))
m: print length
n: how many bits after point (>0)
Example
print(format(12.123456,'6,2f'))
  12.12

Input
str1=input(<message>): str1=input("please input value:")

Len
len(<variable>): len(a)

Pow
pow(2,3)-->8 <=> 2*2*2 <=> 2**3

abs
abs(-18)-->18

Module
import <module name>
Example: import math

math.floor(18.7)-->18
math.sqrt(4)-->2

also can give the module.function with lable
abc=math.floor
abc(18.7)-->18

Program
x = input("Input Name:")
print ("hey " + x)
input("Press<Enter>")

String
"hey" = 'hey' = "he's a jerk" = 'he\'s a jerk'

join string
a= "bucky "
b="roberts"
a + b --> bucky roberts

"hey now" --> 'hey now'
print "hey now" --> hey now

convert num to string
num = 18
print("abc" + str(num)) -->abc18

Sequence
family = ['mom','dad','bro','sis','dog']
                0         1    2      3     4
               -5       -4   -3    -2    -1
family[3] --> 'sis'
family[-2] -->'sis'
'bucky'[3] --> 'k'

Slicing
example = [1,2,3,4,5,6,7,8,9]
                  0 1 2 3 4 5 6 7
                  -8 -7 -6 -5 -4 -3 -2 -1 
example [4:8] --> [4,5.6,7]
example [-5:] --> [5,6,7,8,9] 
example [:] --> [1,2,3,4,5,6,7,8,9]
example [1:8:2] --> [1,3,5,7]
example [10:0:-2] -->[9, 7, 5, 3, 1]

[7,4,5]+[1,2,3]-->[7,4,5,1,2,3]
'bucky'+'roberts' --> 'buckyroberts'
'bucky'*10 -->'buckybuckybuckybuckybuckybuckybuckybuckybuckybuckybucky'
21*10--> 210
[21]*10 --> [21,21,21,21,21,21,21,21,21,21]
'21'*10 -->'21212121212121212121'

name='roastbeef'
'z' in name --> False
'r' in name --> True

family = ['mom','dad','bro','sis','dog'] 
'mom' in family --> True
'cat' in family --> False

family = ['mom','dad','bro','sis','dog']  
len(family) --> 5
max(family) --> 'sis'

list('bucky') --> ['b','u','c','k','y']
a=list('bucky')
a[3] ='a'
a --> ['b','u','c','a','y']
del a[3]
a --> ['b','u','c','y']
a[1:]=list('abcd')
a --> ['b','a','b','c','d']
a[1:1]=['z']
a --> ['b','z','b','c','d']
a[1:3]=[]
a --> ['b','b','c','d']

Methods
list.append(''): add item at the end of list
Example: a.append('abc')
list.count(''): count the number of specific items 
Example: a.count('abc')   
list.extend(): add several items at the end of the list
Example a.extend(b)
list.index(''): find out the position of item
Example a.index('abc')
list.insert('',''): insert item into one position
Example a.insert(2, 'abc')
list reverse(): reverse the list

Dictionary
{key:value}
Example:
book={'Dad':'Bob','Mom':'Lisa','Bro':'Joe'}
book['Dad'] -->'Bob'

Clean the dictionary: book.clear()
Copy the dictionary: book.copy()

If Statement
if <condition>:
    <script>
elif <condition>:
    <script>
else:
    <script>

Example
tuna="fish"
if tuna=="fish":
    print ("this is a fish alright")
elif tuna=="abc":
    print ("this is not a fish alright")
else
    print ("this is not at all a fish alright")

Different between == and is
only one = two = ['abc']
one is two --> true

otherwise 
one = ['a']
two = ['b']
one is two --> false
one == two --> true
  
Loop Statement
while <condition>:
    <script>
Example

b=1
while b < 10:
    print (b)
    b=b+1

for <condition>:
    <script>
Example
gl=['bread','milk','meat','beef']
for food in gl:
    print (food)

ages={'dad':42, 'mom': 48, 'lisa':7}
for item in ages:
    print (item, ages[item])

break
Example
while 1:
    name = input('enter name: ')
    if name=='quit': break

Custom define function
def whatup(x):
    return 'whats up ' +x
print (whatup('abc')) --> whats up abc

function with default value
function
def name(first='tom', last='smith')
    print '%s, %s' % (first, last)
call function
name() --> tom, smith
name('bucky') --> bucky, smith
name('bucky','roberts') --> bucky, roberts
name(last='roberts') --> tom, roberts

function with multiple parameters
function
def list(*food):
    print(food)
call function
list('apple','peach','beef','meat') --> ('apple','peach','beef','meat') 

function
def profile(name, *ages):
    print(name)
    print(ages)
call function
profile('bucky',42,43,44,54) --> 
bucky 
(42,43,44,54)

function with dictionary
function
def cart(**items):
    print(items)
call function
cart(apple=4,peach=5,beef=80) --> {'apple': 4, 'beef': 80, 'peach': 5}

funciont with multiple parameters and dictionary
function
def profile(first,last,*ages,**items):
    print(first,last)
    print(ages)
    print(items)
call function
profile('bucky','roberts', 23,45,16,14,bacon=4, saus=64) --> 

bucky roberts
(23, 45, 16, 14)
{'bacon': 4, 'saus': 64}

Using Tuples or dictionary to trigger function
function
def example(a,b,c):
    return a+b*c
call function
tuna=(4,5,6)
example(*tuna) --> 34

function
def example(**this):
    print(this)
call function
bacon={'mom':32, 'dad':54}
example(**bacon) -->{'dad': 54, 'mom': 32}

Object Oriented Program
Define Class
class exampleClass:
    eyes="blue"
    age=22
    def thisMethod(self):
        return 'hey htis method worked'

Create object
exampleobject=exampleClass()

Using object
exampleobject.eyes -->'blue'
exampleobject.age --> 22
exampleobject.thisMethod --> 'hey this method worked'

Working with files (write will overwrite the previous context)
Write context into file
1. create file object: fob=open('d:/work/test/a.txt','w')
2. write context into file: fob.write('hey new brown cow')
3. close the file: fob.close()

Read context from file
1. create file object: fob=open('d:/work/test/a.txt','r')
2. read specific number of bit context from file: fob.read(3) --> 'hey'
3. read the rest context from file: fob.read() --> ' new brown cow'
4. close the file: fob.close()

Read line by line
1. create file object: fob=open('d:/work/test/a.txt','r')
2, read file line by line: print(fob.readlines()) -->['hey \n', 'new \n', 'brown \n', 'cowabc']
3. close the file: fob.close()

Write line by line
1. create file object: fob=open('d:/work/test/a.txt','w')
2, write file line by line: fob.write('this is the first line\nthis is the second line\nthis is the third line\nthis is the last line')
3. close the file: fob.close()

Modify the specific line
1. create file object: fob=open('d:/work/test/a.txt','r')
2. convert the file context into list: listme=fob.readlines()
3. close the file: fob.close()
4. change the context of the list: listme[2]="abcde"
5. create file object: fob=open('d:/work/test/a.txt','w')
6. put the list context into file: fob.writelines(listme)
7. close the file: fob.close()

Custom Define module (save several functions into a file)
1. create one file "test.py" with following context
def testmod():
    print('hello world!!!')
2. load module: import test
3. use the function: test.testmod() --> 'hello world!!!'

Reload custom define module
1. load the imp module: import imp
2. reload the custom define module: imp.reload(test)

System library
1. list the context in the module: dir(math)
2. detail describe the context in the module: help(math)
3. brief describe the module: math.__doc__

Comments

Popular posts from this blog

Nginx Proxy & Load Balance & LNMP

Snort+barnyard2+Snorby CentOS 6.5_64 Installation

ORACLE Error