Python入門三部曲(二)

1.起步

2.變量和簡單數據類型

1.變量

message = "hello world python"
print(message)

2.命名

1.命名與使用
2.使用變量時避免命名錯誤

3.字符串

1.使用方法修改字符串的大小寫
name = 'ada lovelace'
print(name.title())

輸出得到:
Ada Lovelace

title()以首字母大寫的方式顯示每個單詞,即每個單詞的首字母都改爲大寫

print(name.upper())
print(name.lower())

得到:
ADA LOVELACE
ada lovelace
2.拼接字符串

用“+” 來拼接字符串

“\t,\n”來空格與換行

3.刪除空白
  1. rstrip() 刪除末尾的空白
  2. lstrip() 刪除頭部的空白
  3. strip() 刪除字符串兩端的空白
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)

3.列表簡介

1.列表是什麼

bicycles = ['trek','cannondale','redline','specialized']

print(bicycles)
1.訪問列表元素
print(bicycles[0])

得到

trek
2.索引從0而不是1開始

2.修改,添加和刪除元素

1.修改列表元素
names =['zhangsan','lisi','wangwu','zhaoliu']
print(names)

names[0] = 'zhangsanfeng'
print(names)

得到:
['zhangsan', 'lisi', 'wangwu', 'zhaoliu']
['zhangsanfeng', 'lisi', 'wangwu', 'zhaoliu']
2.列表中添加元素
  • 在列表末尾添加元素
  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'] 3.2.3列表中刪除元素 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
    • 彈出列表中任何位置處的元素
    • 使用方法pop()刪除元素 有時候要將元素從列表中刪除,並接着使用它的值,方法pop()可刪除列表末尾的元素,並讓你能夠接着使用它。
    • 使用del語句刪除元素
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']

3.組織列表

1.使用方法sort()對列表進行永久性排序—按字母排序
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']
2.使用方法sorted()對列表進行臨時排序—按字母排序
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()
4.確定列表的長度
nicks =['zhangsan','lisi','wangwu','zhaoliu']
print(len(nicks))

得到:4

4.使用列表時避免索引錯誤

注意元素的個數,另外訪問最後一個元素時,都可使用索引-1,倒數第2個可以使用索引-2,依次類推

nicks =['zhangsan','lisi','wangwu','zhaoliu']
print(nicks[-1])

得到:
zhaoliu

4.操作列表

1.遍歷整個列表

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

使用單數和複數的式名稱可幫助判斷代碼段處理的是單個列表元素還是整個列表。
1.在for循壞環中執行更多的操作

在每條記錄中打印一條消息。

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!
  • 遺漏了冒號 漏掉了冒號,python不知道程序意欲何爲。

3.創建數值列表

1.使用函數range()

函數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]
3.對數字列表執行簡單的統計計算

最小值,最大值,求和

digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))

得到:
0
9
45

4.使用列表的一部分

1.切片
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']
2.遍歷切片
nicks =['zhangsan','lisi','wangwu','zhaoliu']
for nick in nicks[0:3]:
    print(nick.title())

得到:
Zhangsan
Lisi
Wangwu
3.複製列表—-需要特別注意了
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

5.if語句

1.條件測試

  • 檢查相等用‘==’
  • 檢查不相等用‘!=’
  • 檢查多個條件
    1. 使用and檢查多個條件:要檢查是否兩個條件都爲True,可使用關鍵字and將兩個條件測試合而爲一;如果每個測試都通過了,整個表達式爲就爲True,如果至少有一個測試沒有通過,則整個表達式爲False
    2. 使用or檢查多個條件:至少有一個條件滿足,就能通過整修測試,僅當兩個測試都沒有通過時,使用or的表達式才爲False
  • 檢查特定值是否包含在列表中,使用關鍵字in
request_topping = ['mushrooms','onions','pineapple']
print('mushrooms' in request_topping)
print('mush' in request_topping)

得到:
True
False
  • 檢查特定值是否不包含在列表中,使用關鍵字not in
request_topping = ['mushrooms','onions','pineapple']
print('mushrooms' not in request_topping)
print('mush' not in request_topping)

得到:
False
True

2.if語句 主要注意的是代碼縮進,

  • if
  • if-else
  • if-elif-else
  • 多個elif代碼塊
  • 省略else代碼塊

6.字典

1.字典的簡單使用

在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'}

2.遍歷字典

  • 遍歷所有的鍵值對
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
1.遍歷字典中所有的鍵
values = {'1':'one','2':'two','3':'three','4':'four'}

for value in values.keys():
    print(value)

得到:
1
3
2
4
2.遍歷字典中所有的值
values = {'1':'one','2':'two','3':'three','4':'four'}

for value in values.values():
    print(value)

得到:
one
three
two
four
3.按順序遍歷字典中所有鍵
values = {'first':'one','second':'two','three':'three'}

for value in sorted(values.keys()):
    print(value)

得到:
first
second
three

7.用戶輸入和while循環

1.函數input()工作原理

注意:用戶輸入只能從終端運行,不能直接通過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$

注意以下幾點:

  1. 使用int()來獲取數值輸入
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()把數據類型轉換了一下,
  1. 求模運算符

求模運算符不會指出一個數是另一個數的多少倍,而只指出餘數是多少

>>> 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
2.讓用戶選擇何時退出
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$

其它使用方式:

  • 使用boolean 標記來判斷
  • 使用break退出循環
  • 使用continue

3.使用While循環來處理列表和字典

1.在列表之間移動元素
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$

完。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章