溫故而知新-python語法複習
1.程式的輸出
import sys;sys.stdout.write("hello world\n"); out:hello world |
print("%s is number %d" % ("ten",10)); out:ten is number 10 |
注:不同於print(),write()不會自動在字串後面新增換行符
2.程式的輸入
import sys;user=input("enter loginname:");print("your login is",user);
3.字串的切片和索引操作:
pystr='spyder_python_3.5';print(pystr[0:6]);print(pystr[6]);print(pystr[-3:-1],pystr[-1]); |
pystr='spyder_python_3.5';print(pystr[0:6]);print(pystr[6]);print(pystr[-3:]); |
Out:spyder
_
3.5
注:切片不包含結束座標。因此常用:[-3:]
3. 列表和元祖
列表,運算子[],元素可以增刪改。
元祖,運算子(),只讀的列表。
共同點:切片操作,運算子[],[:]
aList=[1,"a",2,"b"]; aTuple=("rebots",77,93,"try"); |
aList[2:] Out[17]: [2, 'b'] |
aTuple[0:3] Out[18]: ('rebots', 77, 93) |
4.字典
Python的對映資料型別,鍵-值(key-value)對構成;一般來說,數字或者字串作為鍵key會最為常用;運算子為{}。
#建立字典: aDict={'host':'beijing'}; aDict['tel']='18888888888'; aDict['name']='Clark'; aDict[1]='etl'; aDict[2]='oracle'; aDict[3]='sql tuning'; |
aDict Out[25]: {1: 'etl', 2: 'oracle', 3: 'sql tuning', 'host': 'beijing', 'tel': '18888888888', 'name': 'Clark'} |
#字典的查詢 aDict.keys() Out[26]: dict_keys([1, 2, 3, 'host', 'tel', 'name']) for key in aDict: print(str(key)+"\t "+aDict[key]) |
5.if 語句
def stastics(y):
import sys;
x=int(input("enter a number less then 30:"))+y;
if x<=10:
print("class_1");
elif x<=20:
print("class_2");
elif x<=30:
print("class_3");
else:
print("you enter a number more then 30.");
6.while語句
def test_while(counter):
while counter<10:
print("loop #%d" % (counter));
counter+=1;
test_while(8)
loop #8
loop #9
7.for迴圈
for item in aDict.keys():
print(item,"\t",aDict[item])
for item in [1,2,'a','b']:
print(item);
8.range()內建函式
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
range()函式建立range物件
range(i, j) produces i, i+1, i+2, ..., j-1.
range(4).__contains__(2)
Out[33]: True
range(4).__contains__(4)
Out[34]: False
9. 列表解析(列表和range物件的關係)
[x ** 2 for x in range(4)]
Out[35]: [0, 1, 4, 9]
[x for x in range(4)]
Out[36]: [0, 1, 2, 3]
10.檔案和內建函式open(),file()
持久儲存。
Open:
open(file, mode='r', buffering=-1,encoding=None, errors=None, newline=None, closefd=True, opener=None)
'r' open for reading (default)
'w' open for writing,truncating the file first
'x' create a new file andopen it for writing
'a' open for writing,appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (readingand writing)
open(r'E:\庫-技術研究庫\branch-stage01\程式設計-python\方向-pythoncore\專題-【Python核心程式設計(第二版)】Wesley J. Chun\1.txt', mode='x', encoding=None)
Out[42]: <_io.TextIOWrapper name='E:\\庫-技術研究庫\\branch-stage01\\程式設計-python\\方向-pythoncore\\專題-【Python核心程式設計(第二版)】Wesley J. Chun\\1.txt' mode='x' encoding='cp936'>
file=open(r'E:\庫-技術研究庫\branch-stage01\程式設計-python\方向-pythoncore\專題-【Python核心程式設計(第二版)】Wesley J. Chun\1.txt', mode='w', encoding=None)
file.writelines([str(item)+"\t"+aDict[item]+"\n"for item in aDict.keys()])
file.close()
11. 錯誤和異常
try:
file=open(r'E:\庫-技術研究庫\branch-stage01\程式設計-python\方向-python core\專題-【Python核心程式設計(第二版)】Wesley J. Chun\2.txt', mode='x', encoding=None);
except IOError:
print("file openerror:",IOError);
else:
print("file open error:other");
file open error: <class'OSError'>
try:
file=open(r'E:\庫-技術研究庫\branch-stage01\程式設計-python\方向-python core\專題-【Python核心程式設計(第二版)】Wesley J. Chun\2.txt', mode='x', encoding=None);
except IOError as e:
print("file open error:",e);
else:
print("file open error:other");
file open error: [Errno 17] File exists:'E:\\庫-技術研究庫\\branch-stage01\\程式設計-python\\方向-python core\\專題-【Python核心程式設計(第二版)】Wesley J. Chun\\2.txt'
12. 函式
12.1 標量運算和列表運算
def addMe2(x):
return(x+x)
addMe2(2.5)
Out[81]: 5.0
addMe2('python')
Out[82]: 'pythonpython'
addMe2(['1','a',2,'b'])
Out[83]: ['1', 'a', 2, 'b', '1', 'a', 2,'b']
12.2 預設引數
def foo(debug=True):
if debug:
print("in debug mode");
else:
print("out debug mode");
foo()
in debug mode
foo(False)
out debug mode
13.類
類是面向物件程式設計的核心,它扮演資料及邏輯容器的角色。
********************************************************************
** 歡迎轉發,原文:http://blog.csdn.net/clark_xu [徐長亮的專欄]
** 感興趣的程式碼在:https://github.com/clark99
** 感謝支援公眾號:clark_blog
********************************************************************