#使用版本:Python 2.7.2
多行註釋 ''' 或者 """ (三個單引號或者雙引號)
當行多斷代碼隔離 ;
下段代碼的開始 :
代碼的連接 print "too long"\
" words"\
相當於 print too long words
1. 類型轉換
int(string)
float(String)
chr(ASCII值到字符)
ord(ASCII字符轉換成值)
oct(String) 八進制
hex 16進制
long 長整型
String.atoi(num) #字符串->int
2.基本輸入
name = raw_input('please input your name')
3.使用中文
第一行: #-*-coding:utf-8-*-
String.decode('utf-8')
String.encode('gbk')
4.數學計算
import math
math.sin(60)
math.pi
math.sqrt(9) #3
math.log10(100) #2
math.pow(2,8) #256
5.運算符
+ - * / 加減乘除
** 乘方
| ^ & 按位或 ,異或, 與
<< >> 左移運算,右移運算
6.轉義符
\n 換行
\t 製表
\r 回車
\\ \' \" # \ ,' , "
7.字符串
string.capitalize()
string.count() #獲得某一子字符串的數目
isidgit ,isalpha ,islower,istitle(),join,lower ,split ,len(string)
String[0] #字符串第一個字符
String[-1] #字符串最後一個字符
String[-2] #字符串倒數第二個字符
String[0:-2] #從第一個字符,到倒數第二個字符,但是不包含倒數第二個字符
8.格式化輸出
%c %d %o %s
%x %X(十六進制整數,其中字母大寫)
str = 'so %s day'
print str % 'beautiful'
9.原始字符串(Raw String)
以R或r 開頭的字符串,沒有轉義字符
import os
path =r'c:\test' #這裏\t就不是製表符的意思了
dirs =os.listdir(path)
print dirs
10.列表 list
list=[]
list.append(1)
list.count(2) #2在list裏出現的次數
list.extend([2,3,4,5])
list.inedx(5)
list.insert(2,6)
list.pop(2) #彈出index是2的數
list.remove(5)#移除5個數字
list.reverse()
list.sort()
list[1:4] #返回下標1到3的數字(不包含4)
list[1:-1] #返回第二個到最後一個的數,但不包含最後一個
11.字典 Dictionary
鍵值對 key:value
dic={'apple':2 ,'orange':1}
dic.clear()
dic.copy()
dic.get(key)
dic.has_key(key)
dic.items()
dic.keys()
dic.values()
dic.pop(k) #刪除k
dic.update()
12.文件File
open(filename,mode,bufsize) #mode: r(讀方式),w(寫方式) ,b(二進制)
file.read() #讀入文件到字符串
file.readline() #讀取一行
file.readlines()#讀取所有行
file.write() #字符串寫到文件
file.writelines()#列表寫到文件
#open file as write mode
file = open('c:/Python27/test/hello.py','w')
file.write('print "write python"\n')
#generate list and write into file
list=[]
for i in range(10)
s=str(i)+'\n'
list.append(s)
file.writelines(list)
file.close()
#print out the file content
file = open('c:/Python27/test/hello.py','r')
s = file.read()
print s
12.if 語句
if :
else if:
else :
13.for 語句
for <str> in <list>:
if<condition> :
break
if<condition> :
continue
else:
14.range
range(start,stop,step) #start,step可選參數
for i in range(1,5+1,1) # 打印 1-5 ,步長爲1
print i
15.while
while<condition>:
do loop