語句塊縮進
python概述
python 簡介
python起源
python的特點
環境
安裝
python運行環境
導入tab模塊
vim編輯器使用
python起步
python語法結構
語句塊縮進
程序輸出
程序輸入
註釋
文檔字符串
python變量
變量定義
變量賦值
運算符
python 代碼塊通過縮進對齊表達代碼邏輯而不是使用大括號
縮進表達一個語句屬於哪個代碼塊
縮進風格:
- 1 或 2:可能不夠,很難確定代碼語句屬於哪個塊
- 8 至 10:可能太多,如果代碼內嵌的層次太多,就會使得代碼很難閱讀
- 4個空格:非常流行,範。羅薩姆支持的風格
注意區別:
>>> print 'hello world!'
hello world!
>>> print 'hello','world'
hello world
>>> print 'hello''world'
helloworld
>>> print 'hello'+'world'
helloworld
>>> print 'hello'+' world'
hello world
程序輸入
使用raw_input()函數讀取用戶輸入數據
>>> user = raw_input("Enter your name: ")
Enter your name: bob
>>> print "Your name is:", user
Your name is: bob
>>> i = raw_input("input a number: ")
input a number: 10
>>> i + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> i + '1'
'101'
>>> int(i) + 1
11
>>> import tab
>>> type(i)
<type 'str'>
程序輸入輸出小練習:
1.創建~/bin/login.py文件
2.提示用戶輸入用戶名
3.獲得到相關用戶名後,將其保存在變量中
4.在屏幕上輸出Welcome用戶名
#!/usr/bin/env python user_name = raw_input("Enter the user name: " ) print "Welcome",user_name 註釋: 和大部分腳本及Unix-shell語言一樣,python也是用#符號標示註釋 從#開始,直到一行結束的內容都是註釋 良好的註釋習慣可以: - 方便其他人瞭解程序功能 - 方便自己在日後讀懂代碼 >>> import string >>> help(string) # 獲取幫助/使用方法 文檔字符串 可以當作一種特殊的註釋 在模塊、類或者函數的起始添加一個字符串,起到在線文檔的功能 簡單的說明可以使用單引號或雙引號 較長的文字說明可以使用三引號 自制模塊/幫助文檔 # vim /home/qihang/PycharmProjects/day01/star.py #!/usr/bin/env python # -- coding: utf-8 -- """示例程序 僅僅是一個測試 只有一個函數 """ def pstar(): "用於打印20個型號“" print '*' * 20 # cd /home/qihang/PycharmProjects/day01/ # python >>> import star >>> help(star) Help on module star: NAME star - 示例程序 FILE /home/qihang/PycharmProjects/day01/star.py DESCRIPTION 僅僅是一個測試 只有一個函數 FUNCTIONS pstar() 用於打印20個型號“ 注意 兩種格式的差距 >>> a = '''hello ... xiaoming''' >>> a 'hello\nxiaoming' >>> print a hello xiaoming >>> b = 'hello\nworld!' >>> b 'hello\n world!' >>> print b hello world! 變量定義 - 第一個字符只能是大小寫字母或下劃線 - 後續字符只能是大小寫字母或數字或下劃線 - 區分大小寫 python是動態類型語言,即不需要預先聲明變量的類型 : 1、有意義(pythonstring) 2、簡短(pystr) 3、多個單詞之間用下劃線(py_str) 4、變量用名詞(phone),函數使用謂詞(動詞+名詞) update_phone 5、類名:每個單詞首字母大寫(MyClass) 變量的類型和值在賦值那一刻被初始化 變量的賦值通過等號來執行 >>> counter = 0 >>> name = 'bob' python也支持增量賦值 >>> n+= 1 #等價於n = n + 1(n之前必須賦值) >>> n*= 1 #等價於n = n * 1 >>> i++ File "<stdin>", line 1 i++ ^ SyntaxError: invalid syntax python中沒有 a-- python 中的 --a 表示負號,++a 表示正號,不會是a的值發生變化。 >>> a 15 >>> --a 15 >>> ++a 15 >>> a-- File "<stdin>", line 1 a-- ^ SyntaxError: invalid syntax >>> a++ File "<stdin>", line 1 a++ ^ SyntaxError: invalid syntax 標準算數運算符 + - × /() //(地板除) %(求模) **(冪運算) /(除法的注意事項) >>> 5 / 3 1 >>> 5./ 3 1.6666666666666667 //(地板除,取靠近商的最小值。) >>> print 5. //3 1.0 >>> print -5. //3 -2.0 比較運算符 < <= > >= == != <> 連比(儘量少用,可讀性差) >>> 3 < 5 < 10 True >>> 10 < 20 > 15 True >>> 10 < 20 and 20 >15 True 邏輯運算符 and not or :不用死記硬背優先級的順序,可以依靠括號來明確定義先算那些,後算那些 數字:基本數字類型 - int: 有符號整數 - long:長整數 >>> a 10 >>> a = 10L >>> a 10L - bool:布爾值 - True:1 - False:0 >>> True + 1 2 >>> False * 10 0 >>> type(True) <type 'bool'> - float:浮點數 - complex:複數 數字的表達方式 python默認以十進制數顯示 數字以0開頭表示爲8進制數 數字以0x開頭表示16進制數 數字以0b或0B開頭表示2進制數 >>> 11 11 >>> 011 9 >>> 0x11 17 >>> 0b11 3 進制之間的轉換,是個問題(2進制轉16進制的技巧:四位二進制換成一位16進制) >>> 0x53 83 >>> 0xA3 163 >>> bin(163) '0b10100011' >>> 0B11101011 235 >>> hex(235) '0xeb' 字符:定義字符串 python 中字符串被定義爲引號之間的字符集合 python支持使用成對的單引號或雙引號 無論單引號,還是雙引號,表示的意義相同 python還支持三引號(三個連續的單引號或者雙引號),可以用來包含特殊字符 python 不區分字符和字符串 字符串切片 使用索引運算符[]和切片運算符[:] 可得到子字符串 第一個字符的索引是0,最後一個字符的所以十-1 >>> pyStr = 'python' >>> pyStr[0] 'p' >>> pyStr[-2] 'o' >>> pyStr[-4] 't' >>> pyStr[2:] 'thon' >>> pyStr[::2](設置步長爲2) 'pto' >>> pyStr[1::2](從下標爲1開始取,步長爲2) 'yhn' >>> pyStr[::-1](從下標爲0開始取,步長爲-1) 'nohtyp' >>> pyStr[:4] 'pyth' >>> 'python'[6] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range >>> 'python'[0] 'p' >>> len(pyStr) 6 字符串連接操作 使用+號可以將多個字符串拼接在一起 使用*號可以將一個字符串重複多次 >>> pyStr = 'python' >>> isCool = 'is Cool' >>> print pyStr + '' + isCool pythonis Cool >>> print pyStr + ' ' + isCool python is Cool >>> pyStr * 2 'pythonpython' 列表:定義列表 可以將列表當成普通的“數組”,它能保存任意數量任意類型的python對象 像字符串一樣,列表也支持下標和切片操作 列表中的項目可以改變(項目可以使數字/字符串/列表/字典) >>> aList=[1,'tom',2,'alice'] >>> aList [1, 'tom', 2, 'alice'] >>> aList[1] = 'bob' >>> aList [1, 'bob', 2, 'alice'] >>> aList[2:] [2, 'alice'] >>> aList = [1,'bob',[10,20]] >>> len(aList) 3 >>> aList[2][0] 10 列表操作 使用in或not in 判斷成員關係(字符串同樣適用) 使用append方法向列表中追加元素 >>> aList [1, 'bob', [10, 20]] >>> 'bob' in aList True >>> 'alice' not in aList True >>> aList.append(3) >>> aList [1, 'bob', [10, 20], 3] >>> aList[5] = 'tom' Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range 元組:元組的定義及操作 可以認爲元組是“靜態”的列表 元組一旦定義,不能改變 >>> aTuple = (1,'tom',2,'alice') >>> 'tom' in aTuple True >>> aTuple[0]=3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment 元組的特殊性(“可變”) >>> atuple = ('1','bob',[10,20]) >>> atuple ('1', 'bob', [10, 20]) >>> atuple[2] = [100,20] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> atuple[2][0] = 100 >>> atuple ('1', 'bob', [, 20]) >>> atuple[2].append(300) >>> atuple ('1', 'bob', [100, 20, 300]) 字典:字典的定義及操作 字典是由鍵-值(key-value)對構成的映射數據類型 通過鍵取值,不支持下標操作 字典是無序集合 >>> userDict = {'name':'bob','age':23} >>> userDict {'age': 23, 'name': 'bob'} >>> userDict['gender'] = 'male'(如果字典中本身有這個key,就將該key的value修改,如果沒有這個key,就新增這個key-alue >>> userDict {'gender': 'male', 'age': 23, 'name': 'bob'} >>> 'bob' in userDict False >>> 'name' in userDict True >>> userDict[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 0 >>> len(userDict) 3 按存儲模型分類 - 標量類型: 數值、字符串 - 容器類型: 列表、元組、字典 按更新模型分類 - 可變類型: 列表、字典 - 不可便類型: 數字、字符串、元組 按訪問模型分類 - 直接訪問: 數字 - 順序訪問: 字符串、列表、元組、 - 映射訪問: 字典 關於變量與內存的引用關係 >>> aList [1, 'bob', [10, 20], 3] >>> bList=aList(將bList這個變量與aList變量指向同一個內存) >>> bList [1, 'bob', [10, 20], 3] >>> aList[0] = 1000 >>> aList [1000, 'bob', [10, 20], 3] >>> bList [1000, 'bob', [10, 20], 3](因爲是指向同一塊內存,所以aList變了,bList也跟着變了) 如果不想指向同一塊內存,可以把aList的內容取出來,重新賦值給新的變量 >>> cList = aList[:] >>> cList [1000, 'bob', [10, 20], 3] >>> cList.append('tom') >>> aList [1000, 'bob', [10, 20], 3] >>> cList [1000, 'bob', [10, 20], 3, 'tom'] 判斷語句 if 語句 if 語句語法結構 標準if 條件語句語法 if expression: if_suite else: else_suite 如果表達式的值非0、非空、none或者爲布爾值True,則代碼組if_suite被執行;否則就去執行else_suite >>> if 3: ... print 'ok' ... ok >>> if 0: ... print 'ok' ... >>> >>> if -1: ... print "ok" ... ok >>> if ' ': ... print 'ok' ... ok >>> if '': ... print 'ok' ... >>> >>> if 3 > 10: ... print 'ok' ... else: ... print 'no' ... no 代碼組是一個python術語,它由一條或多條語句組成,表示一個子代碼塊 注意:同一級子語句,縮進必須相同,如果不同,則報錯 >>> if 3 > 1: ... print 'yes' ... print 'ok' ... yes ok >>> if 3 > 1: ... print 'yes' ... print 'ok' File "<stdin>", line 3 print 'ok' ^ IndentationError: unexpected indent if 語句示例解析 判斷合法用戶 1、創建~/bin/login2.py文件 2、提示用戶輸入用戶名和密碼 3、獲得到相關信息後,將其保存在變量中 4、如果用戶輸的用戶名爲bob,密碼爲123456,則輸出Login successful,否則輸出Login incorrect 自己寫的: #!/usr/bin/env python # -- coding: utf-8 -- user_name = raw_input("Enter the user_name: ") pass_word = raw_input("Enter the password: ") if user_name == "bob": if pass_word == '123456': print "Login successful" else: print "Login incorrect" else: print "Login incorrect" 老師寫的: #!/usr/bin/env python # -- coding: utf-8 -- import getpass user_name = raw_input("Enter the user_name: ") pass_word = getpass.getpass("Enter the password: ") #無回顯 if user_name == "bob" and pass_word == '123456': print "Login successful" else: print "Login incorrect" 擴展if 語句 擴展if 語句結構 擴展if條件語句的語法 if expression1: if_suite elif expression2: elif_suite else: else_suite 只有滿足相關條件,相應的子語句纔會執行 沒有Swith/case這樣的替代品 擴展if 語句示例解析 對於多個分支,只有一個滿足條件的分支被執行 >>> x = 9 >>> if x > 0: ... print "Positive" ... elif x < 0: ... print "Negative" ... else: ... print "Zero" ... Positive 編寫判斷成績的程序 創建 ~/bin/grade.py腳本,根據用戶輸入的成績分檔,要求如下: 1、如果成績大於60分,輸出“及格” 2、如果成績大於70分,輸出“良好” 3、如果成績大於80分,輸出“好” 4、如果成績大於90分,輸出“優秀” 5、否則輸出“你要努力了” 自己寫的: #!/usr/bin/env python # -- coding: utf-8 -- grade = int(raw_input("input the grade(0-100): ")) if grade >= 60 and grade < 70: print "及格" elif grade >= 70 and grade < 80: print "良好" elif grade >= 80 and grade < 90: print "好" elif grade >= 90 and grade <=100: print "優秀" else: print "你需要努力了" 老師給的(可以使用連等): #!/usr/bin/env python # -- coding: utf-8 -- score = int(raw_input("score: ")) if score >=90: print "優秀" elif score >= 80: print "好" elif score >= 70: print "良" elif score >=60: print "及格" else: print "你要捱打了!" 編寫一個程序,和計算機玩石頭、剪刀、布猜拳遊戲 思路: 計算機隨機出石頭剪刀步的方法 >>> import random >>> random.choice('abcdef') 'a' >>> random.choice('abcdef') 'f' >>> random.choice(['bob','tom','lee']) 'bob' >>> random.choice(['bob','tom','lee']) 'tom' >>> random.choice(['bob','tom','lee']) 'lee' 根據計算機出的,來和人出的進行比較 相關知識點:輸出不同顏色的字體 shell/命令行下 # echo [ok] # echo -e "\e[32;43;1m[ok]" #此處沒有0m結束,接下來輸出的顏色都是和這個相同 # echo -e "\e[32;43;1m[ok]\e[0m" 代碼如下: #!/usr/bin/env python # -- coding: utf-8 -- import random ch_list = ["石頭","剪刀","布"] #列出人贏的組合 win_list = [["石頭","剪刀"],["剪刀","布"],["布","石頭"]] prompt = """(0) 石頭 (1) 剪刀 (2) 布 請選擇(0/1/2): """ #計算機的選擇 computer = random.choice(ch_list) #人的選擇方式 ind = int(raw_input(prompt)) player = ch_list[ind] #輸出 人機 選擇 print "Your choice: %s,Computer's choice: %s" % (player,computer) #判斷輸贏 if [player,computer] in win_list: #設置輸出字符顏色“\033[31;1m,其中\033是特定寫法,31,表示字符本身顏色(30+都是字體本身顏色),1m 表示開啓,0m表示關閉” print "\033[31;1mYou Win!\033[0m" elif player == computer: print "\033[32;1m平局\033[0m" else: print "\033[34:1mYou Lose\033[0m"