前言
在开始使用Python编程的时候,需要记住一些最基本的元素,
本文主要记录了我在日常开发中用得最多的一些知识点,用于快速查询使用。
注释
示例1:# this is comments
源文件编码方式声明
# -*- coding: utf_8 -*-
在源文件中需要使用中文(包括中文注释)时,此声明是必不可少的
连字符
if 1900 < year < 2100 and 1 <= month <= 12 \
and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
return 1
当一行语句太长,为了方便打印可阅读,我们可以写成几行,行与行之间使用连字符号“\”连接。
连字符号可以理解为一个转义字符,他所转义的对象是'换行符'。
在括号中的内容可以写成多行而不使用连字符:
month_names = ['Januari', 'Februari', 'Maart', # These are the
'April', 'Mei', 'Juni', # Dutch names
'Juli', 'Augustus', 'September', # for the months
'Oktober', 'November', 'December'] # of the year
for语句
示例1:for i in range(1, 6):
print i
示例2:
list = [1, 2, 3, 4, 5]
for i in list:
print i
两个示例均会输出1~5.
注:for语句可以结合else使用:
for i in range(1,6):
print i
else:
print 'last num:', i
else中的只有在条件变成false,并且不是被break出来的情况才会被执行。
while语句
示例:i = 1
while i < 6 :
print i
i = i+1
此示例输出1~5
函数定义
示例1:def printhello():
print 'Hello'
printhello()
示例2:
def printany(x):
print str(x)
printany('hello')
两个示例均输出hello
异常处理
语法:try:
语句
except 异常名,数据:
语句
else:
语句
示例1:
try:
1/0
except:
print 'Exception'
else:
print 'Not Exception'
此例输出 Exception
执行Shell命令
示例1:os.system('echo hello')
此例输出hello
空操作
pass
此语句表示执行空操作
打开并逐行读取文件
示例:fd = open('test.txt', 'r')
for line in fd:
print line
fd.close()
此例会将test.txt文件打开,然后输出每一行,最后关闭。
打开并写入文件
示例:str = 'this line will be write to file'
filename = 'testwf.txt'
fd = open(filename, 'w')
fd.write(str)
fd.close()
此例会打开一个名为testwf.txt的文件(不存在则新建),然后写入一个字串,最后关闭。
对文件做二进制操作
示例1:from array import array
buff = array('B', [0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x20, 0x21])
f = open('test.bin', 'wb')
buff.tofile(f)
f.close()
示例2:
from array import array
buff = array('B', [0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x20, 0x21])
f = open('test.bin', 'wb')
f.write(buff)
f.close()
此例会将array里面的内容写入到文件test.bin中
命令行参数传递
示例:import sys
print 'arg num:', len(sys.argv)
i = 0
for arg in sys.argv:
print 'arg', i, ':', arg
i = i+1
将上文保存为test.py,执行命令:python test.py 1 2 3 可以看到如下输出:
arg num: 4
arg 0 : test.py
arg 1 : 1
arg 2 : 2
arg 3 : 3
获取用户输入
示例:name = raw_input('Input you name:')
print 'Hello, ', name
此示例执行后会要求你输入姓名,然后输出“Hello, xxx”字样
延时
示例:import time
print 'Hello'
time.sleep(5)
print 'world'
以上示例在显示了Hello之后等待5秒然后才会显示world