message = "hello world python" print(message)
name = 'ada lovelace' print(name.title()) 輸出獲得: Ada Lovelace
title()以首字母大寫的方式顯示每一個單詞,即每一個單詞的首字母都改成大寫python
print(name.upper()) print(name.lower()) 獲得: ADA LOVELACE ada lovelace
用「+」 來拼接字符串git
「\t,\n」來空格與換行app
msg = ' python ' print(msg.rstrip()) print(msg.lstrip()) print(msg.strip()) 獲得 python python python
單引號與單引號一對,
雙引號與雙引號是一對,
通常要成對出現,且。ide
age = 23 msg = "Happy "+str(age)+" rd Birthday" # 必須使用str()不然python識別不了 print(msg)
bicycles = ['trek','cannondale','redline','specialized'] print(bicycles)
print(bicycles[0]) 獲得 trek
names =['zhangsan','lisi','wangwu','zhaoliu'] print(names) names[0] = 'zhangsanfeng' print(names) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu']
在列表末尾添加元素函數
names.append('qianda') print(names) 獲得: ['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu', 'qianda'] cars = [] cars.append('honda') cars.append('honda2') cars.append('honda3') print(cars) 獲得 ['honda', 'honda2', 'honda3']
在列表中插入元素 測試
cars.insert(0,'honda0') print(cars) 獲得: ['honda0', 'honda', 'honda2', 'honda3']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] del nicks[0] print(nicks) 獲得: ['lisi', 'wangwu', 'zhaoliu']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) poped_nicks = nicks.pop(); print(nicks) print(poped_nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhangsan', 'lisi', 'wangwu'] zhaoliu
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) poped_nicks = nicks.pop(0) print('The first name is '+poped_nicks.title()+'.') 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] The first name is Zhangsan.
若是不肯定使用del語句仍是pop()方法,有一個簡單的標準:若是你要從列表中刪除的一個元素,且再也不以任何方式使用它,就使用del語句;若是你要在刪除元素後還能繼續使用它,就使用方法pop()ui
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) nicks.remove('lisi') print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhangsan', 'wangwu', 'zhaoliu']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) nicks.sort(); print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['lisi', 'wangwu', 'zhangsan', 'zhaoliu'] 還能夠按字母順序相反的順序排列列表元素,只須要向sort()方法傳遞參數reverse = True nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) nicks.sort(reverse = True); print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhaoliu', 'zhangsan', 'wangwu', 'lisi']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) print(sorted(nicks)) print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['lisi', 'wangwu', 'zhangsan', 'zhaoliu'] ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] 還能夠相反順序臨時排序 nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) print(sorted(nicks,reverse = True)) print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhaoliu', 'zhangsan', 'wangwu', 'lisi'] ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) nicks.reverse() print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhaoliu', 'wangwu', 'lisi', 'zhangsan'] 方法reverse()永久性地修改列表元素的排列順序,但可隨時恢復原來的排列順序,只須要再次調用reverse()
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(len(nicks)) 獲得:4
####4.使用列表時避免索引錯誤
注意元素的個數,另外訪問最後一個元素時,均可使用索引-1,倒數第2個可使用索引-2,依次類推code
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks[-1]) 獲得: zhaoliu
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick) 獲得: zhangsan lisi wangwu zhaoliu for cat in cats: for dog in dogs for item in list_of_items 使用單數和複數的式名稱可幫助判斷代碼段處理的是單個列表元素仍是整個列表。
在每條記錄中打印一條消息。排序
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") 獲得: Zhangsan, welcome to china Lisi, welcome to china Wangwu, welcome to china Zhaoliu, welcome to china
執行多行代碼,這裏須要注意一下,接下來的代碼都是須要縮進的索引
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") print("hello,python") 獲得: Zhangsan, welcome to china hello,python Lisi, welcome to china hello,python Wangwu, welcome to china hello,python Zhaoliu, welcome to china hello,python
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") print("hello,python") print("print all message and print finish!") 獲得: Zhangsan, welcome to china hello,python Lisi, welcome to china hello,python Wangwu, welcome to china hello,python Zhaoliu, welcome to china hello,python print all message and print finish! 能夠看到最後一條要打印的消息只打印一次,最後一條沒有縮進,所以只打印一次
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") 獲得: File "/Users/liuking/Documents/python/python_learn/test.py", line 22 print(nick.title()+", welcome to china") ^ IndentationError: expected an indented block
其實想打印兩行的消息,結果只打印了一行,print("hello,python") 忘記縮進了,結果只是最後一條打印了這條消息 nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") print("hello,python") 獲得: Zhangsan, welcome to china Lisi, welcome to china Wangwu, welcome to china Zhaoliu, welcome to china hello,python
message = 'hello python world' print(message) 獲得: File "/Users/liuking/Documents/python/python_learn/test.py", line 20 print(message) ^ IndentationError: unexpected indent
第三個打印的消息沒有縮進,結果每一行都被打印出來了。 nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") print("hello,python") print("print all message and print finish!") 獲得: Zhangsan, welcome to china hello,python print all message and print finish! Lisi, welcome to china hello,python print all message and print finish! Wangwu, welcome to china hello,python print all message and print finish! Zhaoliu, welcome to china hello,python print all message and print finish!
函數range()讓你可以輕鬆地生成一系列的數字。
for value in range(1,5): print(value) 獲得: 1 2 3 4 只打印了1〜4 函數range()從指定的第一個值開始數,並在到達你指定的你第二個值後中止。
要建立數字列表,可以使用函數list()將range()的結果直接轉換爲列表,若是將range()做爲list()的參數,輸出將爲一個數字列表。
numbers = list(range(1,6)) print(numbers) 獲得: [1, 2, 3, 4, 5]
把10個整數的平方加入列表中,並打印出來
squares = [] numbers = range(1,11) for number in numbers: squares.append(number**2) print(squares) 獲得: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
最小值,最大值,求和
digits = [1,2,3,4,5,6,7,8,9,0] print(min(digits)) print(max(digits)) print(sum(digits)) 獲得: 0 9 45
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks[0:3]) 前一個數從0開始,後一個數從1開始數 print(nicks[2:3]) 從2開始,截止到第4個元素 print(nicks[2:]) 從2開始,沒有指定截止數據,直接數到末尾 print(nicks[:2]) 沒有指定開始,默認從0開始 print(nicks[:]) 沒有指定開始,也沒有指定結束的,直接複製整個列表 print(nicks[-2:]) 從倒數第2個開始 獲得: ['zhangsan', 'lisi', 'wangwu'] ['wangwu'] ['wangwu', 'zhaoliu'] ['zhangsan', 'lisi'] ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['wangwu', 'zhaoliu']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks[0:3]: print(nick.title()) 獲得: Zhangsan Lisi Wangwu
nicks =['zhangsan','lisi','wangwu','zhaoliu'] nicks_copy = nicks[:] print("original nicks") print(nicks) print("copy nicks") print(nicks_copy) 獲得: original nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] copy nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
爲了覈實咱們確實有兩個列表,
咱們能夠再添加一下東西
nicks =['zhangsan','lisi','wangwu','zhaoliu'] nicks_copy = nicks[:] nicks.append('zhangsanfeng') nicks_copy.append('zhangwuji') print("original nicks") print(nicks) print("copy nicks") print(nicks_copy) 獲得: original nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng'] copy nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangwuji']
若是咱們只是簡單的nicks賦值給nicks_copy就不能獲得兩個列表
nicks =['zhangsan','lisi','wangwu','zhaoliu'] nicks_copy = nicks; nicks.append('zhangsanfeng') nicks_copy.append('zhangwuji') print("original nicks") print(nicks) print("copy nicks") print(nicks_copy) 獲得: original nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji'] copy nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji'] 由於nicks和nicks_copy都指向同一個列表,因此都打印出了相同的列表,這裏要特別注意
python將不能修改的值稱爲不可變的,而不可變的列表被稱爲元組。有的時候須要建立一系列不可修改的元素,元組能夠知足這種須要。
元組看起來像列表,但使用圓括號而不是方括號來標識,定義元組後,就可使用索引來訪問其元素。
point = (200,50,300,90) print(point[0]) print(point[1]) print(point[2]) print(point[-1]) 獲得: 200 50 300 90
points = (200,50,300,90) for point in points: print(point) 獲得: 200 50 300 90
print("original data") points = (200,50,300,90) for point in points: print(point) print("\nmodify data") points = (1,2,3,4) for point in points: print(point) 獲得: original data 200 50 300 90 modify data 1 2 3 4
request_topping = ['mushrooms','onions','pineapple'] print('mushrooms' in request_topping) print('mush' in request_topping) 獲得: True False
request_topping = ['mushrooms','onions','pineapple'] print('mushrooms' not in request_topping) print('mush' not in request_topping) 獲得: False True
在Python中字典是一系列的鍵值對,每個鍵都與一個值相關聯,與鍵相關聯的值能夠是數字,字符串,列表,乃至字典。
alien_0 = {'color':'green','point':5} print(alien_0['color']) 獲得: green
alien_0 = {'color':'green','point':5} print(alien_0) alien_0['x_point'] = 250 alien_0['y_point'] = 100 print(alien_0) 獲得: {'color': 'green', 'point': 5} {'color': 'green', 'y_point': 100, 'x_point': 250, 'point': 5}
alien_0 = {} alien_0['x_point'] = 250 alien_0['y_point'] = 100 print(alien_0) 獲得: {'y_point': 100, 'x_point': 250}
alien_0 = {} alien_0['y_point'] = 100 print(alien_0) alien_0['y_point'] = 1000 print(alien_0) 獲得: {'y_point': 100} {'y_point': 1000}
alien_0 = {'color':'green','point':5} print(alien_0) del alien_0['point'] print(alien_0) 獲得: {'color': 'green', 'point': 5} {'color': 'green'}
values = {'1':'one','2':'two','3':'three','4':'four'} for value in values.items(): print(value) for key,value in values.items(): print("\nkey:"+key) print("value:"+value) 獲得: ('1', 'one') ('3', 'three') ('2', 'two') ('4', 'four') key:1 value:one key:3 value:three key:2 value:two key:4 value:four
values = {'1':'one','2':'two','3':'three','4':'four'} for value in values.keys(): print(value) 獲得: 1 3 2 4
values = {'1':'one','2':'two','3':'three','4':'four'} for value in values.values(): print(value) 獲得: one three two four
values = {'first':'one','second':'two','three':'three'} for value in sorted(values.keys()): print(value) 獲得: first second three
完
注意:用戶輸入只能從終端運行,不能直接經過sublime來運行。
os x系統從終端運行python程序:
1. liukingdeMacBook-Pro:~ liuking$ cd Desktop 2. liukingdeMacBook-Pro:Desktop liuking$ ls 3. input.py 4. python3 input.py 5. 輸出獲得結果 6.
首先:寫一段python 文件
name = input("Please enter your name: ") print("Hello,"+name) 在終端中運行獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py Please enter your name: kobe bryant Hello,kobe bryant liukingdeMacBook-Pro:Desktop liuking$
多行輸入展現:
多行展現能夠用+=來追加字符串。
prompt = "If you tell us who you are,we can personalize the message you see." prompt += "\nWhat is your first name?" name = input(prompt) print("\n Hello,"+name) 獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py If you tell us who you are,we can personalize the message you see. What is your first name?zhang Hello,zhang liukingdeMacBook-Pro:Desktop liuking$
注意如下幾點:
height = input("How tall are you ,in inches? ") height = int(height) if height >= 36: print("\n you're tall enought to ride") else: print("\nyou'll be able to ride when you're a little older.") 獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py How tall are you ,in inches? 43 you're tall enought to ride liukingdeMacBook-Pro:Desktop liuking$ 注意這裏使用了int()把數據類型轉換了一下,
求模運算符不會指出一個數是另外一個數的多少倍,而只指出餘數是多少
>>> 5%3 2 >>> 6%2 0 >>>
number = input("遍歷你輸入的數據:") number = int(number) begin = int(0) while begin <= number: print(begin) begin += 1; 獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py 遍歷你輸入的數據:10 0 1 2 3 4 5 6 7 8 9 10
promt = "\nTell me something and I will repeat it back to you:" promt += "\n Enter 'quit' to end the program." message = "" while message != 'quit': message = input(promt) if message != 'quit': print(message) 終端運行獲得: liukingdeMacBook-Pro:DeskTop liuking$ python3 input.py Tell me something and I will repeat it back to you: Enter 'quit' to end the program: NBA NBA Tell me something and I will repeat it back to you: Enter 'quit' to end the program: CBA CBA Tell me something and I will repeat it back to you: Enter 'quit' to end the program: quit liukingdeMacBook-Pro:DeskTop liuking$
其它使用方式:
unconfirmed_users = ['one','two','three'] confirmed_users = [] while unconfirmed_users: current_user = unconfirmed_users.pop() print("verifying User:"+current_user) confirmed_users.append(current_user) # 顯示全部已驗證用戶
print("\n The following users have been confirmed: ")
for user in confirmed_users:
print(user.title())
獲得:
verifying User:three
verifying User:two
verifying User:one
The following users have been confirmed:
Three
Two
One
#####2.使用用戶輸入來填充字典
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name?") response = input("Which mountain would you like to climb someday?") # 將答案存在字典中 responses[name] = response # 看看是否還有人要參加調查 repeat = input("would you like to let another person respond?(Y/N)") if repeat == 'N': polling_active = False
print("\n----Poll results-----") for name,response in responses.items(): print(name+" would like to climb "+ response+".") 在終端運行獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py What is your name?Kobe Which mountain would you like to climb someday?武當山 would you like to let another person respond?(Y/N)Y What is your name?姚明 Which mountain would you like to climb someday?靈山 would you like to let another person respond?(Y/N)N ----Poll results----- Kobe would like to climb 武當山. 姚明 would like to climb 靈山. liukingdeMacBook-Pro:Desktop liuking$
完。
message = "hello world python" print(message)
name = 'ada lovelace' print(name.title()) 輸出獲得: Ada Lovelace
title()以首字母大寫的方式顯示每一個單詞,即每一個單詞的首字母都改成大寫
print(name.upper()) print(name.lower()) 獲得: ADA LOVELACE ada lovelace
用「+」 來拼接字符串
「\t,\n」來空格與換行
msg = ' python ' print(msg.rstrip()) print(msg.lstrip()) print(msg.strip()) 獲得 python python python
#####4.使用字符串避免語法錯誤
單引號與單引號一對,
雙引號與雙引號是一對,
通常要成對出現,且。
####4.使用函數str()避免類型錯誤
age = 23 msg = "Happy "+str(age)+" rd Birthday" # 必須使用str()不然python識別不了 print(msg)
bicycles = ['trek','cannondale','redline','specialized'] print(bicycles)
print(bicycles[0]) 獲得 trek
names =['zhangsan','lisi','wangwu','zhaoliu'] print(names) names[0] = 'zhangsanfeng' print(names) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu']
在列表末尾添加元素
names.append('qianda') print(names) 獲得: ['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu', 'qianda'] cars = [] cars.append('honda') cars.append('honda2') cars.append('honda3') print(cars) 獲得 ['honda', 'honda2', 'honda3']
在列表中插入元素
cars.insert(0,'honda0') print(cars) 獲得: ['honda0', 'honda', 'honda2', 'honda3']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] del nicks[0] print(nicks) 獲得: ['lisi', 'wangwu', 'zhaoliu']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) poped_nicks = nicks.pop(); print(nicks) print(poped_nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhangsan', 'lisi', 'wangwu'] zhaoliu
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) poped_nicks = nicks.pop(0) print('The first name is '+poped_nicks.title()+'.') 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] The first name is Zhangsan.
若是不肯定使用del語句仍是pop()方法,有一個簡單的標準:若是你要從列表中刪除的一個元素,且再也不以任何方式使用它,就使用del語句;若是你要在刪除元素後還能繼續使用它,就使用方法pop()
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) nicks.remove('lisi') print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhangsan', 'wangwu', 'zhaoliu']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) nicks.sort(); print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['lisi', 'wangwu', 'zhangsan', 'zhaoliu'] 還能夠按字母順序相反的順序排列列表元素,只須要向sort()方法傳遞參數reverse = True nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) nicks.sort(reverse = True); print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhaoliu', 'zhangsan', 'wangwu', 'lisi']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) print(sorted(nicks)) print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['lisi', 'wangwu', 'zhangsan', 'zhaoliu'] ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] 還能夠相反順序臨時排序 nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) print(sorted(nicks,reverse = True)) print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhaoliu', 'zhangsan', 'wangwu', 'lisi'] ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
#####3.倒着打印列表,按元素反轉列表排序
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks) nicks.reverse() print(nicks) 獲得: ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['zhaoliu', 'wangwu', 'lisi', 'zhangsan'] 方法reverse()永久性地修改列表元素的排列順序,但可隨時恢復原來的排列順序,只須要再次調用reverse()
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(len(nicks)) 獲得:4
####4.使用列表時避免索引錯誤
注意元素的個數,另外訪問最後一個元素時,均可使用索引-1,倒數第2個可使用索引-2,依次類推
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks[-1]) 獲得: zhaoliu
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick) 獲得: zhangsan lisi wangwu zhaoliu for cat in cats: for dog in dogs for item in list_of_items 使用單數和複數的式名稱可幫助判斷代碼段處理的是單個列表元素仍是整個列表。
在每條記錄中打印一條消息。
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") 獲得: Zhangsan, welcome to china Lisi, welcome to china Wangwu, welcome to china Zhaoliu, welcome to china
執行多行代碼,這裏須要注意一下,接下來的代碼都是須要縮進的
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") print("hello,python") 獲得: Zhangsan, welcome to china hello,python Lisi, welcome to china hello,python Wangwu, welcome to china hello,python Zhaoliu, welcome to china hello,python
#####2.在for循環結束後執行一些操做
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") print("hello,python") print("print all message and print finish!") 獲得: Zhangsan, welcome to china hello,python Lisi, welcome to china hello,python Wangwu, welcome to china hello,python Zhaoliu, welcome to china hello,python print all message and print finish! 能夠看到最後一條要打印的消息只打印一次,最後一條沒有縮進,所以只打印一次
####2.避免縮進錯誤
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") 獲得: File "/Users/liuking/Documents/python/python_learn/test.py", line 22 print(nick.title()+", welcome to china") ^ IndentationError: expected an indented block
其實想打印兩行的消息,結果只打印了一行,print("hello,python") 忘記縮進了,結果只是最後一條打印了這條消息 nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") print("hello,python") 獲得: Zhangsan, welcome to china Lisi, welcome to china Wangwu, welcome to china Zhaoliu, welcome to china hello,python
message = 'hello python world' print(message) 獲得: File "/Users/liuking/Documents/python/python_learn/test.py", line 20 print(message) ^ IndentationError: unexpected indent
第三個打印的消息沒有縮進,結果每一行都被打印出來了。 nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks: print(nick.title()+", welcome to china") print("hello,python") print("print all message and print finish!") 獲得: Zhangsan, welcome to china hello,python print all message and print finish! Lisi, welcome to china hello,python print all message and print finish! Wangwu, welcome to china hello,python print all message and print finish! Zhaoliu, welcome to china hello,python print all message and print finish!
函數range()讓你可以輕鬆地生成一系列的數字。
for value in range(1,5): print(value) 獲得: 1 2 3 4 只打印了1〜4 函數range()從指定的第一個值開始數,並在到達你指定的你第二個值後中止。
#####2.使用range()建立數字列表
要建立數字列表,可以使用函數list()將range()的結果直接轉換爲列表,若是將range()做爲list()的參數,輸出將爲一個數字列表。
numbers = list(range(1,6)) print(numbers) 獲得: [1, 2, 3, 4, 5]
把10個整數的平方加入列表中,並打印出來
squares = [] numbers = range(1,11) for number in numbers: squares.append(number**2) print(squares) 獲得: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
最小值,最大值,求和
digits = [1,2,3,4,5,6,7,8,9,0] print(min(digits)) print(max(digits)) print(sum(digits)) 獲得: 0 9 45
nicks =['zhangsan','lisi','wangwu','zhaoliu'] print(nicks[0:3]) 前一個數從0開始,後一個數從1開始數 print(nicks[2:3]) 從2開始,截止到第4個元素 print(nicks[2:]) 從2開始,沒有指定截止數據,直接數到末尾 print(nicks[:2]) 沒有指定開始,默認從0開始 print(nicks[:]) 沒有指定開始,也沒有指定結束的,直接複製整個列表 print(nicks[-2:]) 從倒數第2個開始 獲得: ['zhangsan', 'lisi', 'wangwu'] ['wangwu'] ['wangwu', 'zhaoliu'] ['zhangsan', 'lisi'] ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] ['wangwu', 'zhaoliu']
nicks =['zhangsan','lisi','wangwu','zhaoliu'] for nick in nicks[0:3]: print(nick.title()) 獲得: Zhangsan Lisi Wangwu
nicks =['zhangsan','lisi','wangwu','zhaoliu'] nicks_copy = nicks[:] print("original nicks") print(nicks) print("copy nicks") print(nicks_copy) 獲得: original nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'] copy nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
爲了覈實咱們確實有兩個列表,
咱們能夠再添加一下東西
nicks =['zhangsan','lisi','wangwu','zhaoliu'] nicks_copy = nicks[:] nicks.append('zhangsanfeng') nicks_copy.append('zhangwuji') print("original nicks") print(nicks) print("copy nicks") print(nicks_copy) 獲得: original nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng'] copy nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangwuji']
若是咱們只是簡單的nicks賦值給nicks_copy就不能獲得兩個列表
nicks =['zhangsan','lisi','wangwu','zhaoliu'] nicks_copy = nicks; nicks.append('zhangsanfeng') nicks_copy.append('zhangwuji') print("original nicks") print(nicks) print("copy nicks") print(nicks_copy) 獲得: original nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji'] copy nicks ['zhangsan', 'lisi', 'wangwu', 'zhaoliu', 'zhangsanfeng', 'zhangwuji'] 由於nicks和nicks_copy都指向同一個列表,因此都打印出了相同的列表,這裏要特別注意
####5.元組
python將不能修改的值稱爲不可變的,而不可變的列表被稱爲元組。有的時候須要建立一系列不可修改的元素,元組能夠知足這種須要。
元組看起來像列表,但使用圓括號而不是方括號來標識,定義元組後,就可使用索引來訪問其元素。
point = (200,50,300,90) print(point[0]) print(point[1]) print(point[2]) print(point[-1]) 獲得: 200 50 300 90
points = (200,50,300,90) for point in points: print(point) 獲得: 200 50 300 90
print("original data") points = (200,50,300,90) for point in points: print(point) print("\nmodify data") points = (1,2,3,4) for point in points: print(point) 獲得: original data 200 50 300 90 modify data 1 2 3 4
request_topping = ['mushrooms','onions','pineapple'] print('mushrooms' in request_topping) print('mush' in request_topping) 獲得: True False
request_topping = ['mushrooms','onions','pineapple'] print('mushrooms' not in request_topping) print('mush' not in request_topping) 獲得: False True
在Python中字典是一系列的鍵值對,每個鍵都與一個值相關聯,與鍵相關聯的值能夠是數字,字符串,列表,乃至字典。
alien_0 = {'color':'green','point':5} print(alien_0['color']) 獲得: green
alien_0 = {'color':'green','point':5} print(alien_0) alien_0['x_point'] = 250 alien_0['y_point'] = 100 print(alien_0) 獲得: {'color': 'green', 'point': 5} {'color': 'green', 'y_point': 100, 'x_point': 250, 'point': 5}
alien_0 = {} alien_0['x_point'] = 250 alien_0['y_point'] = 100 print(alien_0) 獲得: {'y_point': 100, 'x_point': 250}
alien_0 = {} alien_0['y_point'] = 100 print(alien_0) alien_0['y_point'] = 1000 print(alien_0) 獲得: {'y_point': 100} {'y_point': 1000}
alien_0 = {'color':'green','point':5} print(alien_0) del alien_0['point'] print(alien_0) 獲得: {'color': 'green', 'point': 5} {'color': 'green'}
values = {'1':'one','2':'two','3':'three','4':'four'} for value in values.items(): print(value) for key,value in values.items(): print("\nkey:"+key) print("value:"+value) 獲得: ('1', 'one') ('3', 'three') ('2', 'two') ('4', 'four') key:1 value:one key:3 value:three key:2 value:two key:4 value:four
values = {'1':'one','2':'two','3':'three','4':'four'} for value in values.keys(): print(value) 獲得: 1 3 2 4
values = {'1':'one','2':'two','3':'three','4':'four'} for value in values.values(): print(value) 獲得: one three two four
values = {'first':'one','second':'two','three':'three'} for value in sorted(values.keys()): print(value) 獲得: first second three
完
注意:用戶輸入只能從終端運行,不能直接經過sublime來運行。
os x系統從終端運行python程序:
1. liukingdeMacBook-Pro:~ liuking$ cd Desktop 2. liukingdeMacBook-Pro:Desktop liuking$ ls 3. input.py 4. python3 input.py 5. 輸出獲得結果 6.
首先:寫一段python 文件
name = input("Please enter your name: ") print("Hello,"+name) 在終端中運行獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py Please enter your name: kobe bryant Hello,kobe bryant liukingdeMacBook-Pro:Desktop liuking$
多行輸入展現:
多行展現能夠用+=來追加字符串。
prompt = "If you tell us who you are,we can personalize the message you see." prompt += "\nWhat is your first name?" name = input(prompt) print("\n Hello,"+name) 獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py If you tell us who you are,we can personalize the message you see. What is your first name?zhang Hello,zhang liukingdeMacBook-Pro:Desktop liuking$
注意如下幾點:
height = input("How tall are you ,in inches? ") height = int(height) if height >= 36: print("\n you're tall enought to ride") else: print("\nyou'll be able to ride when you're a little older.") 獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py How tall are you ,in inches? 43 you're tall enought to ride liukingdeMacBook-Pro:Desktop liuking$ 注意這裏使用了int()把數據類型轉換了一下,
求模運算符不會指出一個數是另外一個數的多少倍,而只指出餘數是多少
>>> 5%3 2 >>> 6%2 0 >>>
####2.Whil循環
#####1.使用While循環
number = input("遍歷你輸入的數據:") number = int(number) begin = int(0) while begin <= number: print(begin) begin += 1; 獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py 遍歷你輸入的數據:10 0 1 2 3 4 5 6 7 8 9 10
promt = "\nTell me something and I will repeat it back to you:" promt += "\n Enter 'quit' to end the program." message = "" while message != 'quit': message = input(promt) if message != 'quit': print(message) 終端運行獲得: liukingdeMacBook-Pro:DeskTop liuking$ python3 input.py Tell me something and I will repeat it back to you: Enter 'quit' to end the program: NBA NBA Tell me something and I will repeat it back to you: Enter 'quit' to end the program: CBA CBA Tell me something and I will repeat it back to you: Enter 'quit' to end the program: quit liukingdeMacBook-Pro:DeskTop liuking$
其它使用方式:
unconfirmed_users = ['one','two','three'] confirmed_users = [] while unconfirmed_users: current_user = unconfirmed_users.pop() print("verifying User:"+current_user) confirmed_users.append(current_user) # 顯示全部已驗證用戶
print("\n The following users have been confirmed: ")
for user in confirmed_users:
print(user.title())
獲得:
verifying User:three
verifying User:two
verifying User:one
The following users have been confirmed:
Three
Two
One
#####2.使用用戶輸入來填充字典
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name?") response = input("Which mountain would you like to climb someday?") # 將答案存在字典中 responses[name] = response # 看看是否還有人要參加調查 repeat = input("would you like to let another person respond?(Y/N)") if repeat == 'N': polling_active = False
print("\n----Poll results-----") for name,response in responses.items(): print(name+" would like to climb "+ response+".") 在終端運行獲得: liukingdeMacBook-Pro:Desktop liuking$ python3 input.py What is your name?Kobe Which mountain would you like to climb someday?武當山 would you like to let another person respond?(Y/N)Y What is your name?姚明 Which mountain would you like to climb someday?靈山 would you like to let another person respond?(Y/N)N ----Poll results----- Kobe would like to climb 武當山. 姚明 would like to climb 靈山. liukingdeMacBook-Pro:Desktop liuking$
完。