Python中沒有強制的語句終止字符,代碼塊是經過縮進來指示的。縮進表示一個代碼塊的開始,逆縮進則表示一個代碼塊的結束。通常用4個空格來表示縮進。html
# 本行是註釋 some_var = 3 print(some_var) print(some_var == 4) if some_var > 1: print('Python就是這麼簡單') 3 False Python就是這麼簡單
外部庫可使用 import [libname] 關鍵字來導入,也可使用 from [libname] import [funcname] 來導入所須要的函數。例如:java
import math math.sqrt(25) 5.0 from math import sqrt sqrt(25) 5.0
查看數據類型:python
type(2) int type('two') str type(True) bool
類型轉換:git
float(2) 2.0 int(2.9) 2 str(2.9) '2.9'
10 + 4 14 10 - 4 6 10 * 4 40 10 % 4 # 計算餘數 2 10 / 4 2.5
賦值sql
x = 5
比較:express
x > 3 True x >= 3 True x != 3 True x == 5 True
布爾運算:安全
# and:與 5 > 3 and 6 > 3 True # or:或 5 > 3 or 5 < 3 True # not:非 not False True
# if 語句 if x > 0: print('positive') positive # if/else 語句 if x > 0: print('positive') else: print('zero or negative') positive # if/elif/else 語句 if x > 0: print('positive') elif x == 0: print('zero') else: print('negative') positive
建立列表app
# 兩種建立空列表的方法以下 empty_list = [] empty_list = list() # 建立列表 simpsons = ['homer', 'marge', 'bart']
獲取列表數據:curl
# 列表的第0個元素(列表的下標從0開始,這和C語言等一致) simpsons[0] 'homer' # 列表元素個數 len(simpsons) 3
列表方法:函數
# 在尾部追加,操做符+=完成一樣的功能 simpsons.append('lisa') simpsons ['homer', 'marge', 'bart', 'lisa'] # 在尾部追加多個元素 simpsons.extend(['itchy', 'scratchy']) simpsons
['homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy'] # 在索引位置處將數據項插入列表 simpsons.insert(0, 'maggie') simpsons
['maggie', 'homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy'] # 列表從左往右搜索第一個出現的元素,並移除 simpsons.remove('bart') simpsons
['maggie', 'homer', 'marge', 'lisa', 'itchy', 'scratchy'] # 替代列表第一個元素 simpsons[0] = 'krusty' simpsons
['krusty', 'homer', 'marge', 'lisa', 'itchy', 'scratchy'] # 統計元素出現次數 simpsons.count('lisa') 1 # returns index of first instance simpsons.index('itchy') 4
列表切片:
weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri'] # 第一個元素,索引值爲0 weekdays[0] 'mon' # 前三個元素,索引值爲0、一、2,,其中0能夠省略 print(weekdays[0:3] == weekdays[:3]) weekdays[0:3] True ['mon', 'tues', 'wed'] # 從索引值爲3的元素的位置到最後位置的元素 weekdays[3:] ['thurs', 'fri'] # 最後一個元素 weekdays[-1] 'fri' # 每隔兩個元素進行存取 weekdays[::2] ['mon', 'wed', 'fri'] # 反轉列表,等價於list(reversed(weekdays)) weekdays[::-1] ['fri', 'thurs', 'wed', 'tues', 'mon'] # 對列表進行排序 (原地修改列表但不返回列表) simpsons.sort() simpsons ['homer', 'itchy', 'krusty', 'lisa', 'marge', 'scratchy'] # 反向排序 simpsons.sort(reverse=True) simpsons ['scratchy', 'marge', 'lisa', 'krusty', 'itchy', 'homer'] # 根據傳入的規則排序,以長度爲例 simpsons.sort(key=len) simpsons ['lisa', 'marge', 'itchy', 'homer', 'krusty', 'scratchy'] # 返回已排序列表(並不修改原列表),能夠傳入排序規則: simpsons = [ 'krusty', 'itchy', 'scratchy', 'lisa'] sorted(simpsons, key=len) ['lisa', 'itchy', 'krusty', 'scratchy'] # 對象引用 num = [10,20,30,40,50] same_num = num # 會同時修改兩個對象 same_num[0] = 0 print(num) print(same_num) [0, 20, 30, 40, 50] [0, 20, 30, 40, 50] # 檢查是不是同一個對象 num is same_num True # 判斷兩個對象是否相等 num == same_num True
# 直接建立一個元組 digits = (0, 1, 'two') # 將列表轉化爲元組 digits = tuple([0, 1, 'two']) # 元組第三個位置的元素 digits[2] 'two' # 元組長度 len(digits) 3 # 統計元組中元素出現的次數 digits.count('two') 1 # 返回該元素第一次出現的索引值 digits.index(1) 1 # 元組不可修改,下面語句會報錯 # digits[2] = 2
# 建立字符串 s = 'I like you' # 字符串切片 s[0] 'I' # 長度 len(s) 10
字符串切片相似於列表切片:
s[:6] 'I like' s[7:] 'you' s[-1] 'u'
字符串方法 (並不修改原字符串):
s.lower() 'i like you' s.upper() 'I LIKE YOU' s.startswith('I') True s.endswith('you') True # 返回在字符串中的最左位置,若是沒有找到,就返回-1 s.find('like') 2 # 字符串替換 s.replace('like', 'love') 'I love you'
字符串分割:
# 返回一個被空白字符分割的字符串列表 s.split(' ') ['I', 'like', 'you'] # 返回一個被特定字符分割的字符串列表 s2 = 'a, an, the' s2.split(',') ['a', ' an', ' the'] # 字符串拼接 stooges = ['larry', 'curly', 'moe'] ' '.join(stooges) 'larry curly moe' # + 也可做字符串拼接 s3 = 'The meaning of life is' s4 = '42' s3 + ' ' + s4 'The meaning of life is 42' # 移除開始和結尾的空白字符 s5 = ' ham and cheese ' s5.strip() 'ham and cheese'
格式化字符串:
# 方法1 'raining %s and %s' % ('cats', 'dogs') 'raining cats and dogs' # 方法2 'raining {} and {}'.format('cats', 'dogs') 'raining cats and dogs'
字典的鍵與值:
# 建立一個空字典(兩種方法) empty_dict = {} empty_dict = dict() # 建立字典(兩種方法) family = {'dad':'homer', 'mom':'marge', 'size':6} family = dict(dad='homer', mom='marge', size=6) family {'dad': 'homer', 'mom': 'marge', 'size': 6} # 傳入鍵名,獲取字典鍵值 family['dad'] 'homer' # 返回字典的鍵-值對數目 len(family) 3 # 檢查字典中是否含有某個鍵名 'mom' in family True # 返回鍵名 family.keys() dict_keys(['size', 'dad', 'mom']) # 返回鍵值 family.values() dict_values([6, 'homer', 'marge']) # 返回鍵值對 family.items() dict_items([('size', 6), ('dad', 'homer'), ('mom', 'marge')])
修改字典:
# 增長一個鍵-值 family['cat'] = 'snowball' family {'cat': 'snowball', 'dad': 'homer', 'mom': 'marge', 'size': 6} # 編輯一個已存在的鍵-值 family['cat'] = 'snowball ii' family {'cat': 'snowball ii', 'dad': 'homer', 'mom': 'marge', 'size': 6} # 刪除一個鍵-值 del family['cat'] family {'dad': 'homer', 'mom': 'marge', 'size': 6} # 字典值能夠是列表 family['kids'] = ['bart', 'lisa'] family {'dad': 'homer', 'kids': ['bart', 'lisa'], 'mom': 'marge', 'size': 6} # 增長多個鍵-值 family.update({'baby':'maggie', 'grandpa':'abe'}) family {'baby': 'maggie', 'dad': 'homer', 'grandpa': 'abe', 'kids': ['bart', 'lisa'], 'mom': 'marge', 'size': 6}
獲取鍵值的一個更安全的方法(get):
# 獲取字典值,等價於family['mom'] family.get('mom') 'marge' # 若是字典中不存在,返回一個默認值 family.get('grandma', 'not found') 'not found'
建立集合:
# 建立空集合 empty_set = set() # 建立集合 languages = {'python', 'r', 'java'} # 將列表轉化爲集合 snakes = set(['cobra', 'viper', 'python'])
集合運算:
# 交集 languages & snakes {'python'} # 並集 languages | snakes {'cobra', 'java', 'python', 'r', 'viper'} # 差集 languages - snakes {'java', 'r'}
修改集合 (並不返回集合):
# a增長元素 languages.add('sql') languages {'java', 'python', 'r', 'sql'} # 增長一個已存在的元素 languages.add('r') languages {'java', 'python', 'r', 'sql'} # 移除元素 languages.remove('java') languages {'python', 'r', 'sql'} # 移除全部元素 languages.clear() languages set()
從列表中獲取惟一元素的排序列表:
sorted(set([9, 0, 2, 1, 0])) [0, 1, 2, 9]
定義沒有參數、沒有返回值的函數:
def print_text(): print('this is text') # 調用函數 print_text() this is text
定義含有一個參數、含有一個返回值的函數:
# 定義函數 def square_this(x): return x**2 # 調用函數 result = square_this(3) print(result) 9
定義含有兩個位置參數(非默認值)、一個關鍵字參數(默認值)的函數:
def calc(a, b, op='add'): if op == 'add': return a + b elif op == 'sub': return a - b else: print('valid operations are add and sub') # 調用函數 calc(10, 4, op='add') 14 # 經過參數位置來傳入參數值 calc(10, 4, 'add') 14 # ‘op’關鍵字參數爲默認值 calc(10, 4) 14 calc(10, 4, 'sub') 6 calc(10, 4, 'div') valid operations are add and sub
若是您還沒有編寫函數體,請使用pass做爲佔位符:
def stub(): pass
函數含有兩個返回值:
def min_max(nums): return min(nums), max(nums) # 多個返回值能夠綁定到類型爲元組的變量上 nums = [1, 2, 3] min_max_num = min_max(nums) min_max_num (1, 3) # 多個返回值綁定到多個變量上()經過元組解包的方式 min_num, max_num = min_max(nums) print(min_num) print(max_num) 1 3
定義函數:
# 最多見的定義函數的方法——def def squared(x): return x**2 # 使用lambda定義函數的方法,等價於def函數定義 squared = lambda x: x**2
依據字符串最後一個元素的順序,將字符串列表進行排序:
# 使用def函數定義的方法 simpsons = ['homer', 'marge', 'bart'] def last_letter(word): return word[-1] sorted(simpsons, key=last_letter) ['marge', 'homer', 'bart'] # 使用lambda函數定義的方法 sorted(simpsons, key=lambda word: word[-1]) ['marge', 'homer', 'bart']
for 循環:
# for循環 fruits = ['apple', 'orange'] for fruit in fruits: print(fruit.upper()) APPLE ORANGE # 對字典的循環,依次打印字典的鍵名和鍵值 family = {'dad':'homer', 'mom':'marge', 'size':6} for key, value in family.items(): print(key, value) size 6 dad homer mom marge # 對列表的循環,依次打印列表元素的索引值和元素 for index, fruit in enumerate(fruits): print(index, fruit) 0 apple 1 orange
while
循環:
count = 0 while count < 5: print('This will print 5 times') count += 1 # 等價於 'count = count + 1' This will print 5 times This will print 5 times This will print 5 times This will print 5 times This will print 5 times
列表生成式:
# 經過for循環得到一個列表,該列表的每一個元素是原始列表對應元素的三次方 nums = [1, 2, 3, 4, 5] cubes = [] for num in nums: cubes.append(num**3) cubes [1, 8, 27, 64, 125] # 使用列表生成式 cubes = [num**3 for num in nums] cubes [1, 8, 27, 64, 125] # 若是隻想得到偶數值的列表 # 語法: [expression for variable in iterable if condition] cubes_of_even = [num**3 for num in nums if num % 2 == 0] cubes_of_even [8, 64]
集合生成式:
fruits = ['apple', 'banana', 'cherry'] unique_lengths = {len(fruit) for fruit in fruits} unique_lengths {5, 6}
字典生成式:
fruit_lengths = {fruit:len(fruit) for fruit in fruits} fruit_lengths {'apple': 5, 'banana': 6, 'cherry': 6} fruit_indices = {fruit:index for index, fruit in enumerate(fruits)} fruit_indices {'apple': 0, 'banana': 1, 'cherry': 2}
1. 應該學Python 2 仍是 Python 3?
若是你還在問這個問題,選擇Python 3。Python 3已經被普遍支持和使用,Python 2的程序能夠經過 2to3 轉換爲Python 3。對初學者來講,Python 2和3區別不大。BigQuant的策略開發語言是Python 3。