★【Python编程】(1) 总记 语法例程

【转载请注明出处:http://blog.csdn.net/leytton/article/details/35988121

python注释

#单行注释
'''
多行注释
多行注释
多行注释
''' 
头部加上
#-*-coding:utf-8-*- #解决中文注释问题


语法

00_input编码.py

import sys

type0=sys.getfilesystemencoding()
print(type0)

s1=input("请输入:");
print(s1)

s2=s1.encode('gbk').decode('utf_8')
print(s1.encode('gbk').decode('utf_8'))
print(s2)

01_while.py

sum,i=0,1
while i<101:
    print(i)
    sum+=i
    i=i+1
print(sum)
input()

02_while_if_continue_break.py

i=0
while True:
    i=i+1
    if i%2!=0:
        continue;
    elif i==4:
        print('i=4')
    elif i==10:
        break
    else:
        print(i)

03_function_01_global_sleep.py

#-*-coding:utf-8-*- 
import time
def Count(n):
    global sum
    i=1
    while i<=n:
        print(i)
        time.sleep(2)   #休眠两秒
        sum+=i
        i=i+1
        
n=int(input("请输入一个整数:"))
sum=0
Count(n)
print("1+2+...+",n,"=",sum)

03_function_02_默认参数.py

def say(message, times = 1):
    print (message * times)

say('Hello')
say('World', 5) 


# 输出
# $ python func_default.py
# Hello
# WorldWorldWorldWorldWorld 

03_function_03_关键参数.py

def func(a, b=5, c=10):
    print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100) 

#输出
#$ python func_key.py
#a is 3 and b is 7 and c is 10
#a is 25 and b is 5 and c is 24
#a is 100 and b is 5 and c is 50

05_记忆运算结果.py

#最近一次表达式输出保存在 "_"变量中

06_DocString.py
def printMax(x, y):
    '''Prints the maximum of two numbers.

    The two values must be integers.'''
    #__Doc__显示说明
    x = int(x) # convert to integers, if possible
    y = int(y)
    
    if x > y:
        print (x, 'is maximum')
    else:
        print (y, 'is maximum')

printMax(3, 5)
print (printMax.__doc__)

07_复数.py

# 虚部由一个后缀"j"或者"J"来表示。带有非零实部的复数记为"real+imagj)",
# 或者也可以通过"complex(real, img)"函数创建
print(1j*1J)
print(1j * complex(0,1))

a=1.5+0.5j
print(a.real)
print(a.imag)

08_sys模块.py

import sys
print ('The command line arguments are:')
for i in sys.argv:
    print (i)
print ('\n系统路径:')
for i in sys.path:
    print (i)

09_模块名_模块引用01.py

import usingname01
usingname01.say()
print("version=",usingname01.version)

09_模块名_模块引用02.py

from usingname01 import say, version
# from usingname01 import *
say()
print("version=",version)

10_dir_del.py

import sys
a,b=1,2

print(dir(sys))
print(dir())
print(__file__)
print("a=",a)

del(a)
print(dir())
#print(a)

11_list_01.py

s=['dd','bb']
print("The length of 's' is ",len(s))
for item in s:
    print(item,)
print(s)
s.append('aa') #增加
s.sort()  #排序
print(s)

a=s  #列表的赋值语句不创建拷贝,等于是指针赋值.
del a[1] #删除
print(s)
s[1]='cc' #修改
print(s)

11_list_02.py

listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print (listtwo)

# 输出
# [6, 8]

12_元组_01.py

zoo = ('wolf', 'elephant', 'penguin')
print ('Number of animals in the zoo is', len(zoo))

new_zoo = ('monkey', 'dolphin', zoo)
print ('Number of animals in the new zoo is', len(new_zoo))
print ('All animals in new zoo are', new_zoo)
print ('Animals brought from old zoo are', new_zoo[2])
print ('Last animal brought from old zoo is', new_zoo[2][2])

# 输出
# $ python using_tuple.py
# Number of animals in the zoo is 3
# Number of animals in the new zoo is 3
# All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
# Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
# Last animal brought from old zoo is penguin 

12_元组_02_print.py

age = 22  
name = 'Swaroop'  
print('Why is %s playing with that python?' % name)     # 像不像C++ 的printf啊  
print('%s is %d years old' % (name, age))    # 元组的显示

# 输出
# Why is Swaroop playing with that python?
# Swaroop is 22 years old

13_字典_01.py

ab = {'Swaroop' : 'swaroopch@byteofpython.info',  
'Larry' : 'larry@wall.org',  
'Matsumoto' : 'matz@ruby-lang.org',  
'Spammer'   : 'spammer@hotmail.com'}     # 字典的定义  

print("Swaroop's address is %s" % ab['Swaroop'])     # 可以像数组一样使用, 索引是key 
 
# Adding a key/value pair  
ab['Guido'] = 'guido@python.org'     # 赋值  

# Deleting a key/value pair  
del ab['Spammer']    # 删除  
print('\nThere are %d contacts in the address-book' % len(ab))  

for name, address in ab.items():     # 注意这个是怎么循环的  
    print('Contact %s at %s' %(name,address))
if 'Guido' in ab: # OR ab.has_key('Guido')   # 查询  
    print("\nGuido's address is %s" % ab['Guido'])  
     
#输出  
# Swaroop's address is swaroopch@byteofpython.info
# There are 4 contacts in the address-book
# Contact Larry at larry@wall.org
# Contact Guido at guido@python.org
# Contact Matsumoto at matz@ruby-lang.org
# Contact Swaroop at swaroopch@byteofpython.info
# Guido's address is guido@python.org

13_字典_02_键的排序.py

ab = {'Swaroop' : 'swaroopch@byteofpython.info',  
'Larry' : 'larry@wall.org',  
'Matsumoto' : 'matz@ruby-lang.org',  
'Spammer'   : 'spammer@hotmail.com'}     # 字典的定义  

keys=list(ab.keys())
keys.sort()

for key in keys:
     print(key,'===>',ab[key])

14_序列.py

shoplist = ['apple', 'mango', 'carrot', 'banana']  
# Indexing or 'Subscription' operation  
print('Item 0 is', shoplist[0])  
print('Item 1 is', shoplist[1])  
print('Item 2 is', shoplist[2])  
print('Item 3 is', shoplist[3])  
print('Item -1 is', shoplist[-1])  
print('Item -2 is', shoplist[-2])  
# Slicing on a list  
print('Item 1 to 3 is', shoplist[1:3])  
print('Item 2 to end is', shoplist[2:])  
print('Item 1 to -1 is', shoplist[1:-1])  
print('Item start to end is', shoplist[:])  
# Slicing on a string  
name = 'swaroop'  
print('characters 1 to 3 is', name[1:3])  
print('characters 2 to end is', name[2:])  
print('characters 1 to -1 is', name[1:-1])  
print('characters start to end is', name[:])  
# 输出  
# $ python seq.py  
# Item 0 is apple  
# Item 1 is mango  
# Item 2 is carrot  
# Item 3 is banana  
# Item -1 is banana  
# Item -2 is carrot  
# Item 1 to 3 is ['mango', 'carrot']  
# Item 2 to end is ['carrot', 'banana']  
# Item 1 to -1 is ['mango', 'carrot']  
# Item start to end is ['apple', 'mango', 'carrot', 'banana']  
# characters 1 to 3 is wa  
# characters 2 to end is aroop  
# characters 1 to -1 is waroo  
# characters start to end is swaroop 

15_字符串函数.py

#coding=utf-8
name = 'Swaroop' # This is a string object   
if name.startswith('Swa'):  
    print('Yes, the string starts with "Swa"')  
if 'a' in name:  
    print('Yes, it contains the string "a"')  
if name.find('war') != -1:  
    print('Yes, it contains the string "war"')  
delimiter = '_*_'  
mylist = ['Brazil', 'Russia', 'India', 'China']  
print(delimiter.join(mylist))  
# 输出  
# Yes, the string starts with "Swa"  
# Yes, it contains the string "a"  
# Yes, it contains the string "war"  
# Brazil_*_Russia_*_India_*_China

16_压缩文件脚本X.py(False)

17_类_01_空类.py

class Person:
    pass

p1=Person()
p1.name='Leytton'
p1.age=20

print(p1.name)
print(p1.age)

17_类_02_构造_析构_一般函数.py

# Python中所有的类成员(包括数据成员)都是 公共的 ,所有的方法都是 有效的 。
# 只有一个例外:如果你使用的数据成员名称以 双下划线前缀 比如__privatevar,Python的名称管理体系会有效地把它作为私有变量。

class Person:
    def __init__(self,name):   # 类构造函数  
        self.name=name    # 初始化工作 
        # 注意name不需要在类中声明, 直接赋值就代表声明了
        
    def sayHello(self):    # 类方法定义时, 第一个参数都是self 
        print("Hello,my name is %s" %self.name)
        
    
    def __del__(self):   # 类的析构函数  
        print('%s says bye.' % self.name)


p1=Person("Leytton1")  # 使用时不需要填入self
p1.sayHello()
p1.age=20
print(p1.age)

p2=Person("Leytton2")  # 使用时不需要填入self
p2.sayHello()

17_类_03_继承.py

#!/usr/bin/python  
# Filename: inherit.py  
class SchoolMember:  
    '''Represents any school member.'''  
    def __init__(self, name, age):   # 构造函数  
        self.name = name  
        self.age = age  
        print('(Initialized SchoolMember: %s)' % self.name)  
    def tell(self):  
        '''Tell my details.'''  
        print('Name:"%s" Age:"%s"' % (self.name, self.age))  
class Teacher(SchoolMember):     # 继承  
    '''Represents a teacher.'''  
    def __init__(self, name, age, salary):  
        SchoolMember.__init__(self, name, age)  # 调用父类的构造函数, 这里调用时有self的  
        self.salary = salary  
        print('(Initialized Teacher: %s)' % self.name)  
    def tell(self):  # 重载了父类的tell方法  
        SchoolMember.tell(self)  
        print('Salary: "%d"' % self.salary)  
class Student(SchoolMember):  
    '''Represents a student.'''  
    def __init__(self, name, age, marks):  
        SchoolMember.__init__(self, name, age)  # 调用父类的构造函数, 这里调用时有self的  
        self.marks = marks  
        print('(Initialized Student: %s)' % self.name)  
    def tell(self):  # 重载了父类的tell方法  
        SchoolMember.tell(self)  
        print('Marks: "%d"' % self.marks)  
t = Teacher('Mrs. Shrividya', 40, 30000)  
s = Student('Swaroop', 22, 75)  
print() # prints a blank line  
members = [t, s]  
for member in members:   # 循环调用tell  
    member.tell() # works for both Teachers and Students   
# 输出  
# $ python inherit.py  
# (Initialized SchoolMember: Mrs. Shrividya)  
# (Initialized Teacher: Mrs. Shrividya)  
# (Initialized SchoolMember: Swaroop)  
# (Initialized Student: Swaroop)  
# Name:"Mrs. Shrividya" Age:"40" Salary: "30000"  
# Name:"Swaroop" Age:"22" Marks: "75"

18_文件读写_IO_exits.py

import os
import sys
str='''\
My name is Leytton,
I'm studying Python~
'''
fout=open('18_fileIO.txt','w')  # open for 'w'riting 打开文件写方式
fout.write(str)     # write text to file写入文本到文件
fout.close()       # close the file关闭文件

# if no mode is specified, 'r'ead mode is assumed by default
if os.path.exists('18_fileIO.txt')==False:
    print('文件不存在')
    sys.exit()
    
fin=open('18_fileIO.txt')  #fin=open('18_fileIO.txt','r')#再次打开文件  
while True:
    #str=fin.read()   读取所有内容至字符串
    #lines=fin.readlines()   读取所有内容至数组
    line=fin.readline()    # 循环读取文件, 知道读取到EOF文件尾
    if len(line)==0:     # Zero length indicates EOF
        break
    else :
        print(str)   #print(str,end='')
fin.close

19_对象持久化_01_pickle.py

#命名空间使用as来重命名
import pickle as p

class Person:
    pass

p1=Person()
p1.name='Leytton'
p1.age=20

lists=['aa','bb','cc','dd',p1]
f=open('19_cPickle.txt','wb')
p.dump(lists,f)   # Write to the file 写入Python对象到文件
f.close()

del lists   # remove the lists
#print(lists)

f=open('19_cPickle.txt','rb')   # Read back from the storage 重新读取
lists=p.load(f)
print(lists)

19_对象持久化_02_JsonX.py(False)

import json as p

class Person:
    pass

p1=Person()
p1.name='Leytton'
p1.age=20

lists={'hhh':p1}
print(lists)

f=open('19_Json.json','w')
p.dump(lists,f)   # Write to the file 写入Python对象到文件
f.close()

del lists   # remove the lists
#print(lists)

f=open('19_Json.json','r')   # Read back from the storage 重新读取
lists=p.load(f)
print(lists)

20_异常处理X.py

21_sys_argv.py

#!/usr/bin/python  
# Filename: cat.py  
import sys  
def readfile(filename):  
    '''Print a file to the standard output.'''  
    f = open(filename)  
    while True:  
        line = f.readline()  
        if len(line) == 0:  
            break  
        print(line) # notice comma  
    f.close()  
# Script starts from here  
if len(sys.argv) < 2:  
    print('No action specified.')  
    sys.exit()  
if sys.argv[1].startswith('--'):  
    option = sys.argv[1][2:]  
    # fetch sys.argv[1] but without the first two characters  
    if option == 'version':  
        print('Version 1.2')  
    elif option == 'help':  
        print('''\  
This program prints files to the standard output.  
Any number of files can be specified.  
Options include:  
  --version : Prints the version number  
  --help    : Display this help''')
    else:  
        print('Unknown option.')  
    sys.exit()  
else:  
    for filename in sys.argv[1:]:  
        readfile(filename)

22_sys_os.py

# os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。
# 
# os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。
# 
# os.getenv()和os.putenv()函数分别用来读取和设置环境变量。
# 
# os.listdir()返回指定目录下的所有文件和目录名。
# 
# os.remove()函数用来删除一个文件。
# 
# os.system()函数用来运行shell命令。
# 
# os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
# 
# os.path.split()函数返回一个路径的目录名和文件名。
# >>> os.path.split('/home/swaroop/byte/code/poem.txt')
# ('/home/swaroop/byte/code', 'poem.txt') 
# 
# os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.existe()函数用来检验给出的路径是否真地存在。
import os
#help(os)
print ('当前路径:',os.getcwd())

print ('\n当前路径目录和文件:')
files=os.listdir()  #默认为当前路径
for item in files:
    print (item)

23_exec_eval.py

exec('print ("Hello World")')

exec(open('22_sys_os.py','rb').read())

print(eval('2*3'))

24_数据库_01_MySQL.py

import mysql.connector as MySQLdb

conn=MySQLdb.Connect(user='root',password='lqw',database='leyttonblog')

cur=conn.cursor()
cur.execute('''select * from user''')
results=cur.fetchall()
print(results)
for r in results:
    print(r[1],r[2])



24_数据库_01_SQLite.py

import sqlite3

conn=sqlite3.Connection('24_SQLite.db')
cur=conn.cursor()
cur.execute('''select * from person''')
print(cur.fetchall())

25_网络编程_01_Socket服务端.py

import socket


s=socket.socket()
host=socket.gethostname()
#print(host)
port=8082
s.bind((host,port))

s.listen(5)
print("等待请求...")
while True:
    c, addr=s.accept()
#     print(c)
    print(addr)
    print("获得来自",addr[0],"的请求")
    
    s1=input("请发送消息:");
    print(s1)
    s1=s1.encode('gbk').decode('utf_8')
    s2="服务端说:"
    
    c.send((s2+s1).encode('utf_8'))
    print("向客户端发送了消息...\n")
    c.close()


25_网络编程_02_Socket客户端.py

import socket

s=socket.socket()
host=socket.gethostname()
#print(host)
port=8082
s.connect((host,port))

print("开始请求...")
msg=s.recv(1024) 
print("获得服务端消息...")
#print(str(msg)[2:-1])
print(msg.decode('utf_8'))

25_网络编程_03_urllib.py

import re
from urllib.request import urlopen

webapp=urlopen('http://www.qq.com/ZendStudio/test/')

text=webapp.read()

print(text)

m=re.search('<a.*href=\"(.*)".*>(.*)</a>', text.decode('utf_8'),re.IGNORECASE)   #re.DOTALL
print(m.group(0))

m=re.findall('<a.*href=\"(.*)".*>(.*)</a>', text.decode('utf_8')) 
print(m)

26_界面编程_01.py

import tkinter
top = tkinter.Tk()
top.title('HelloGUI')
top.iconbitmap("26_界面编程_01_logo.ico")
top.geometry('600x400')
btn = tkinter.Button(top, text='mAmimoluo!')
btn.pack()
label = tkinter.Label(top,text='Hello World')
label.pack()
quit=tkinter.Button(top,text='QUIT',command=top.quit,activeforeground='white',activebackground='red')
quit.pack(side='bottom')
tkinter.mainloop()


posted @ 2014-06-30 11:49  Leytton  阅读(247)  评论(0编辑  收藏  举报