你們好,從本文開始將逐漸更新Python教程指南系列,爲何叫指南呢?由於本系列是參考《Python3程序設計指南》,也是做者的學習筆記,但願與讀者共同窗習。python
.py文件中的每一個估計都是順序執行的,從第一行開始,逐行執行的。
int整數(正整數或負整數)express
str字符串(Unicode字符序列)數組
temp = 123 print(temp, type(temp)) temp = 'hello' print(temp, type(temp)) output: 123 <class 'int'> hello <class 'str'>
a = [1, 'abc'] b = [1, 'abc'] print(a is b) a = (1, 'abc') b = (1, 'abc') print(a is b) a = b print(a is b) output: False False True
a = [1, 'abc'] b = [1, 'abc'] print(a is b) a = (1, 'abc') b = (1, 'abc') print(a is b) a = b print(a is b) output: True True True
a = 9 print(0 <= a <= 10) output: True
in來測試成員關係,用not in來測試非成員關係。app
# in運算符 a = (3, 45, 'hello', {'name': 'lisi'}) print(45 in a) string = 'zhangsan|wanger' print('|' in string) output: True True
在Python中,一塊代碼,也就是說一條或者多條語句組成的序列,稱爲suit。dom
語法:函數
if boolean_expression1: suite1 elif boolean_expression2: suite2 else: suite3
while語句用於0次或屢次執行某個suite,循環執行的次數取決於while循環中布爾表達式的狀態,其語法爲:學習
while boolean_expression: suite
for循環語句重用了關鍵字in,其語法爲:測試
for variable in iterable: suite
Python的不少函數與方法都會產生異常,並將其做爲發生錯誤或重要事件的標誌。其語法爲:ui
try: try_suite except exception1 as variable1: exception_suite1 ... except exceptionN as variableN: excetpion_suiteN
其中as variable部分是可選的。spa
加強賦值操做符
字符串列表+=和append的區別
建立函數語法:
def functionName(arguments): suite
爲了熟悉以上關鍵要素,咱們用一個實例來練習一下:
建立一個生成隨機整數組成的網格程序,用戶能夠規定須要多少行、多少列,以及整數所在的區域。
import random
該函數須要3個參數:msg爲提示信息,minimum爲最小值,default爲默認值。該函數的返回值有兩種狀況:default(用戶沒有輸入直接按Enter鍵),或者一個有效的整數。
def get_int(msg, minimum, default): while True: try: line = input(msg) # 若是輸入值爲空而且default不爲None if not line and default is not None: return defalut # 將輸入轉爲整形 i = int(line) # 若是輸入值小於最小值,提示用戶 if i < minimum: print("must be >=", minimum) else: return i # 異常處理 except ValueError as e: print(e)
# 用戶輸入行數 rows = get_int('rows:', 1, None) # 用戶輸入列數 columns = get_int('columns', 1, None) # 用戶輸入最小值 minimum = get_int('minimum(or Enter for 0):', -10000, 0) default = 1000 # 若是最小值大於default,default設置爲最小值的2倍 if default < minimum: default = 2 * minimum # 用戶輸入最大值 maximum = get_int('maximum (or Enter for' + str(default) + ')', minimum, default)
row = 0 while row < rows: line = '' column = 0 while column < columns: # 生成一個大於minimum,小於maximum的隨機整數 i = random.randint(minimum, maximum) s = str(i) # 讓每一個數佔10個字符,爲了輸出整齊 while len(s) < 10: s = ' ' + s line += s column += 1 print(line) row += 1
如下爲輸出信息:
rows:5 columns7 minimum(or Enter for 0):-1000 maximum (or Enter for1000)1000 -871 -205 426 820 986 369 238 -389 485 388 -907 243 346 -912 -885 528 50 -572 744 519 -128 785 -747 -565 -390 522 -357 933 -144 947 -949 -409 105 954 708
注:本文知識介紹Python的8個關鍵要素,可是並無徹底介紹,好比數據類型不僅包括整形和字符串,後面的文章中還會詳細介紹。
歡迎關注(C與Python實戰)[ https://pythoncpp-1254282033....]