#Python特性,强类型(即强制要求变量类型),dynamic,capital sensitive,隐士类型(不需要声明)and objective.
#compile with python3
- common libs
# -*- coding: utf-8 -*-
import os
import sys
import urllib
import json
import re
import getopt
import socket
import time
import urllib2
import urllib
import cookielib
import json
import httplib
2. #index with tabs
#inverse indentations mean end of block of codes.
3. #interpretation
#This is a comment with # for single line
'''
Single quotes for multi-line comments
Single quotes for multi-line comments
Single quotes for multi-line comments
'''
"""
Double quotes for multi-line comments
Double quotes for multi-line comments
Double quotes for multi-line comments
"""
4. #set variables with = or -= or +=
>>> myint=2
>>> myint+=3
>>> myint
5
>>> mystring="Today is"
>>> mystring+=" Sunny."
>>> print(mystring)
Today is Sunny.
5. process control
(1) if ……else
if ACTION=="online":
weight=100
elif ACTION=="offline":
weight=0
elif ACTION=="get":
http_method="GET"
else:
usage()
(2) while
while 1:
try:
request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request,timeout=1)
except urllib2.URLError, err:
print("Failed to GET "+url)
else:
str1=response.read().decode('utf-8')
str=json.loads(str1)
code=str["code"]
if code == 0:
break
time.sleep(3)
i=i+1
if i >= max_retry:
print("soa-console API Operate Failed. Check if http://xxx.hostname.com available!")
exit(1)
(3) for
for key,value in options:
if key in ("-h","--help"):
usage()
if key in ("-t","-run"):
RUN=True
if key in ("-n","--name"):
if value:
VALUE=value
if key in ("-a","--action"):
ACTION=value
if key in ("-A","--appname"):
APPLICATION=value
6、数据类型
(1)list
>>> list = [] #空列表
>>> list.append('Google') # 使用append() 添加元素
>>> list.append('Honkong')
>>> print list
['Google', 'Honkong']
>>> print list[0]
Google
>>> del list[0]
>>> print list
['Honkong']
(2)tuple
>>> tup1=() #空元组
>>> tup2=('a','b','c','d')
>>> tup3=('A','B','C','a','b','c')
>>> dir(tuple) #查看元组支持的方法
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>> tup2.count('a') #元素a出现的次数
>>> tup2.index('b') #元素b第一次出现的位置
1
>>> tup_sum=tup2+tup3 #元组合并
>>> print tup_sum
('a', 'b', 'c', 'd', 'A', 'B', 'C', 'a', 'b', 'c')
>>> tup_multi=tup3*2 #保留元组tup3不变情况下,复制2次,生成新元组tup_multi
>>> print tup_multi
('A', 'B', 'C', 'a', 'b', 'c', 'A', 'B', 'C', 'a', 'b', 'c')
#元组切片操作
>>> print tup_multi[:] #取所有元组
('A', 'B', 'C', 'a', 'b', 'c', 'A', 'B', 'C', 'a', 'b', 'c')
>>>
>>> print tup_multi[2:] # 从2至末尾元素
('C', 'a', 'b', 'c', 'A', 'B', 'C', 'a', 'b', 'c')
>>> print tup_multi[2:5] #从2至5的元素
('C', 'a', 'b')
>>> print tup_multi[2:7:2] #语法:T[start [, stop[, step]]] ,取从2开始至7结束,每隔1个位置的元素
('C', 'b', 'A')
列表和元组的区别:
列表使用[],用于在不确定元素个数情况;元组使用(),元素不能修改。
(3)dictionaries(hash tables)
字典由多个<key,value>对组成,key是索引字段(如果重复,后者会覆盖前者)。 例如:
dict = {key1 : value1, key2 : value2 }
>>> dict = {'Name': 'kk','Age':5,'gender':'Male'}
>>> print(dict['Name'])
kk
修改value:
>>> dict['gender']='Female'
>>> print(dict['gender'])
Female
删除<key,value>:
>>> del dict['gender']
>>> print(dict['gender'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'gender'
删除后找不到对应的key,所以报错了。