Python命令 (if __name__=="__main__":)

1. 语法

1.以#号开头的语句是注释

2.请务必注意,Python程序是大小写敏感的,如果写错了大小写,程序会报错。

3.按照约定俗成的管理,应该始终坚持使用4个空格的缩进。

4.当语句以冒号:结尾时,缩进的语句视为代码块。

1.缩进方式,一般是4个空格,兼容tab键

if a>=0;

    print(a)

else:

    print(a)

2.注释#

3.Python 对大小写敏感

2.基本数据类型

1.空值 None

2./n换行,/t tab键,// 表示/

3.

整数 -1,0,1  0xff00;
浮点数  1.23, -9.01, 1.23e9[1.23x109];
字符串 ‘hello’,“python”;
布尔值 True,False[布尔值可以用and、or和not运算];

3.List 列表 (有序集合)

1.list里面的元素的数据类型也可以不同,list元素也可以是另一个list(s[2][1]) classmates = ['Michael', 'Bob', ‘Tracy’] L = ['Apple', 123, True]

2.classmates.append(‘a’)

classmates.insert(1,’jack’)

classmates.pop()删除末尾

classmates.pop(i),删除指定元素

classmates[1] = ‘sarah’

tuple 有序列表叫元祖;.与list 相似,但是tuple初始化后就不能修改。

遍历List:

def iterList():
    list = ['name','address','name2','addres2','name3','adress3']
    for i,v in  enumerate(list):
        print i,v
   
    #dict = {"a":1,"b":"adf","c":"shide","d":"afda"}
   
 
 

3.1. tuple

元组

tup = ('wo','yao')
    for item in tup:
        print(item)

 

4.dict  (like java’s  hashmap)

d = {‘michal’:95,’bob’:75}

d[‘jack’]=90

获取value方式:
1、d[‘Michael’]如果key不存在,map读取value就会报错;
2、d.get(‘Thomas') 或者 d.get(‘Thomas’,0) 不存在时返回None或者预设值.
如果删除一个key,用pop(key)方法,对应的value也会从dict中删除 d.pop(‘Bob')

遍历dict :

def iterDict():
    dict={'id':123,"name":"afd","sex":"boy"}
    for item in dict:
        print(item)
    #for item in dict.values():
        #print(item)

    for i in enumerate(dict):
        print i
        

 

5.Set ( s = set([1, 2, 3])  )

s = set([1, 2, 3]) set中,没有重复的key 重复元素在set中自动被过滤  s = set([1, 1, 2, 2, 3, 3])
add(key)方法可以添加元素到set中
remove(key)方法可以删除元素:
set和dict的唯一区别仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。
*不可变对象

遍历Set:

def iterSet():
    s = set([1,2,3])
    for item in s:
        print(item)
        
    for i in enumerate(s):
        print (i)

 

6.判断语句

age = 3
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print(‘kid')

 

7.循环语句

def whileTest():
    list = ['name','address']
    for item in list:
        print(item)
        
    tup = ('wo','yao')
    for item in tup:
        print(item)
        
    click = 10
    while click > 0 :
        print (click)
        click -=1
        if click == 8 :
            #return
            continue
        if click < 5 :
            break
    
    

8.函数

#函数声明
def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x
#默认值
def move(x,y,step,angle = 30):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx,ny
#空函数
def nop():
    pass

#返回值
def showlist(list):
    return 1,1,2,3

9.切片

def iter():
    list = ['name','address','name2','addres2','name3','adress3']
    print(list[1:4])
    print (list[-3:-1])
    print(list[1:4:2])
    print(list[::2])
    print(list[::])
    print(list)

10. 列表生成器:

#列表生成器
def listGenerate():
    list = [x for x in range (1,3) ]
    print (list)
    print (type(range(1,11)))
    
    lists = [x*y for x in range(1,3) for y in range(1,3)] #笛卡尔积
    print(lists)
    
    listss = [x*y for x in range(1,11) for y in range(1,11) if x>y] #笛卡尔积
    print (listss)
    gen = (x*y for x in range(1,11) for y in range(1,11) if x>y)
    print (type(gen))
    print(gen.next()) #生成器用来遍历较小的集合

11.生成器:

#生成器
def gen():
    listss = [x*y for x in range(1,3) for y in range(1,3) if x>y] #笛卡尔积
    
    gen = (x*y for x in range(1,3) for y in range(1,3) )
   
    print(gen.next()) #生成器用来遍历较小的集合
    for g in gen:
        print(g)
        
    list = ['name','address','name2','addres2','name3','adress3']
    gen = (x+'1' for x in list if x == "name") 
    for g in gen :
        print (g)
        
    uv = {'id':12,'uv':3000,'id':13,'uv':30001,'id':14,'uv':30002}
    pv = {'id':12,'uv':3000,'id':13,'uv':30001,'id':14,'uv':30002}
    print(type(uv))
    

12.异常处理:

#异常处理
def exceptionTest():
    try:
         i = 10
         j = i/0
         print 'end try'
    except Exception,e:
        print e
        print 'error'
        
    finally:
        print 'finally'

13.读取文件

14.读取properties

ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。
ConfigParser 初始工作
cf = ConfigParser.ConfigParser()
cf.read("配置文件名")
获取所有sections
s = cf.sections()
获取指定section 的options。
o = cf.options("db")
获取指定section 的配置信息
v = cf.items("db")
按照类型读取指定section 的option 信息
db_host = cf.get("db", "db_host")
db_port = cf.getint("db", "db_port")
设置某个option 的值
cf.set("db", "db_pass", "zhaowei")
cf.write(open("test.conf", "w"))
添加一个section
cf.add_section(‘liuqing')
cf.write(open("test.conf", "w"))
移除section 或者option
cf.remove_option('liuqing','int')
cf.remove_section('liuqing')
cf.write(open("test.conf", "w"))

 

例子:

#pro
import ConfigParser

cp=ConfigParser.ConfigParser()
cp.read('demo.txt')

'''
print(cp.sections())

print(cp.options('db'))
print(cp.items('db'))

print(type(cp.get('prp','prp.hu')))
print(cp.getint('db','db.name'))
'''

#cp.add_section('dbnew')
#cp.set('dbnew','dbnew.ip','192.168.1.1')


#cp.remove_option('dbnew','dbnew.ip')
cp.remove_section('dbnew')

cp.write(open('demo.txt','w'))
print(cp.sections())

 

demo.txt

[ddshow]
ip = 10.100.1.1
db.name = zhangsan
db.pwd = lisi

[ddshow_stat]
ip = 10.100.1.2
db.name = zhangsan2
db.pwd = lisi2

 


15.发送邮件

#mail

import smtplib
from email.mime.text import MIMEText

sender="wuzhanwei@youku.com"
receiver="wzhwei@126.com"
smptserver="mail.youku.com"

username="wuzhanwei"
password="WSWZW!!)2"

smtp=smtplib.SMTP()
smtp.connect(smptserver)
smtp.login(username,password)

##
msg=MIMEText('<html>hello</html>','html','utf-8')
msg['Subject']='sub'
##

smtp.sendmail(sender,receiver,msg.as_string())

smtp.quit()

16.访问数据库

17.Python编写mapreduce

mapper:

import sys

for line in sys.stdin:
    line=line.strip()
    words=line.split()
    for word in words:
        print "%s\t%s" %(word,1)

 

 

reducer:

import sys
current_word=None
current_count=0
word=None
for line in sys.stdin:
    line=line.strip()
    word,count=line.split('\t',1)
    try:
        count=int(count)
    except Exception :
        continue
    if current_word==word:
        current_count+=count
    else:
        if current_word:
            print "%s\t%s" %(current_word,current_count)
        current_count=count
        current_word=word
if word==current_word:
    print "%s\t%s" %(current_word,current_count)

 

mr:

import sys
for line in sys.stdin:
    line =line.strip()
    words=line.split()
    for word in words:
        print '%s\t%s' %(word,1)

 

 

 

 

 

 

 

 

 

 

 

 

 

111.直接运行py 文件

#!/usr/bin/env python
name = raw_input()
print('hello,', name)
然后,通过命令给hello.py以执行权限:sudo chmod a+x hello.py
就可以直接运行hello.py了

posted @ 2015-09-25 21:13  农民阿姨  阅读(1283)  评论(0编辑  收藏  举报