1. 程式人生 > >python的字典和流程控制

python的字典和流程控制

字典

  • 字典是另一種可變容器模型,且可儲存任意型別物件。
    字典的每個鍵值(key=>value)對用冒號(:)分割,每個對之間用逗號(,)分割,整個字典包括在花括號({})中 ,格式如下所示:
    d = {key1 : value1, key2 : value2 }
    鍵必須是唯一的,但值則不必。值可以取任何資料型別,但鍵必須是不可變的,如字串,數字或元組。

  • 字典的定義和簡單使用

In [1]: dic ={1:4,'a':11}

In [2]: dic
Out[2]: {1: 4, 'a': 11}

In [3]: dic={1:4,'a':11,('a','b'):'dff'}

In [4]: dic
Out[4]: {1: 4, 'a': 11, ('a', 'b'): 'dff'}

字典的方法

In [5]: dic.
             dic.clear      dic.get        dic.pop        dic.update     
             dic.copy       dic.items      dic.popitem    dic.values     
             dic.fromkeys   dic.keys       dic.setdefault                

In [5]: dic.keys()
Out[5]: dict_keys([1, 'a', ('a', 'b')])

In [6]: dic.values()
Out[6]: dict_values([4, 11, 'dff'])

字典的get的使用,獲取key的value
In [12]: dic
Out[12]: {1: 4, 'a': 11, ('a', 'b'): 'dff'}

In [13]: dic.get(1)
Out[13]: 4

In [14]: dic.get('a')
Out[14]: 11

In [15]: dic.get(('a','b'))
Out[15]: 'dff'

檢查key是否在字典裡
In [17]: 'a' in dic
Out[17]: True

把key和value生成列表
In [18]: dic.items()
Out[18]: dict_items([(1, 4), ('a', 11), (('a', 'b'), 'dff')])

拷貝一個字典
In [19]: dic1=dic.copy()

In [20]: dic1
Out[20]: {1: 4, 'a': 11, ('a', 'b'): 'dff'}

pop出指定的key
In [22]: dic.pop(1)
Out[22]: 4

In [23]: dic
Out[23]: {'a': 11, ('a', 'b'): 'dff'}

更新字典,更新不相同的部分
In [24]: dic.update(dic1)

也可以通過for迴圈遍歷字典
In [25]: dic
Out[25]: {1: 4, 'a': 11, ('a', 'b'): 'dff'}

In [28]: for k in dic:
    ...:     print(k)
    ...:     
1
a
('a', 'b')

字典的練習

使用input接收使用者輸入的資訊存放在dic中,並且打印出來。

#! /usr/bin/python

info={}
name=input("please input name:")
age=input("please input age:")
gender=input("please input (M/F):")
info['name']=name
info['age']=age
info['gender']=gender
print(info)

[[email protected] studypy]# python3 dict-1.py 
please input name:wushan
please input age:26
please input (M/F):M
{'gender': 'M', 'age': '26', 'name': 'wushan'}

也可以使用items的方法進行列印

for i in info.items():
    print(i)

輸出結果
('gender', 'M')
('age', '26')
('name', 'shanwu')

for i,j in info.items():
    print(i,j)

輸出結果
gender M
name shanwu
age 26

流程控制

條件語句

if語句

  • Python 程式設計中 if 語句用於控制程式的執行,基本形式為:
    if 判斷條件:
    執行語句……
    else:
    執行語句……

其中"判斷條件"成立時(非零),則執行後面的語句,而執行內容可以多行,以縮排來區分表示同一範圍。else 為可選語句,當需要在條件不成立時執行內容則可以執行相關語句

if例項

#!/usr/bin/python3
 
age = int(input("請輸入你的年齡: "))
print("")
if age < 0:
    print("你還沒出生!")
elif age == 1:
    print("恭喜你1歲了。")
elif age == 2:
    print("恭喜你2碎了。")
elif age > 18:
    print("恭喜你成年了")

if 巢狀

  • 在巢狀 if 語句中,可以把 if…elif…else 結構放在另外一個 if…elif…else 結構中。
if 表示式1:
    語句
    if 表示式2:
        語句
    elif 表示式3:
        語句
    else:
        語句
elif 表示式4:
    語句
else:
    語句

if巢狀例子

# !/usr/bin/python3
 
num=int(input("輸入一個數字:"))
if num%2==0:
    if num%3==0:
        print ("你輸入的數字可以整除 2 和 3")
    else:
        print ("你輸入的數字可以整除 2,但不能整除 3")
else:
    if num%3==0:
        print ("你輸入的數字可以整除 3,但不能整除 2")
    else:
        print  ("你輸入的數字不能整除 2 和 3")

迴圈

while 迴圈

  • Python中while語句的一般形式:
    while 判斷條件:
    語句

while 的列子

#!/usr/bin/env python3
 
n = 100
 
sum = 0
coun = 1
while coun <= n:
    sum = sum + coun
    coun += 1
 
print("1 到 %d 之和為: %d" % (n,sum))

#輸出
1 到 100 之和為: 5050

while 迴圈使用 else 語句

#!/usr/bin/python3
 
count = 0
while count < 5:
   print (count, " 小於 5")
   count = count + 1
else:
   print (count, " 大於或等於 5")
# 輸出
0  小於 5
1  小於 5
2  小於 5
3  小於 5
4  小於 5
5  大於或等於 5

for迴圈

  • Python for迴圈可以遍歷任何序列的專案,如一個列表或者一個字串。

例子

a="asdfgjk"
for i in a:
    print(i)
#輸出
a
s
d
f
g
j
k

continue:

  • 結束本次迴圈,跳到下次迴圈

break

  • 結束當前的迴圈。
#!/usr/bin/python3
 
for let in 'abcde':     
   if let == 'b':
      break
   print ('當前字母為 :', let)
#輸出
當前字母為 : a
  
var = 10                    
while var > 0:              
   print ('當期變數值為 :', var)
   var = var -1
   if var == 5:
      break
print ("拜拜!")
#輸出
當期變數值為 : 10
當期變數值為 : 9
當期變數值為 : 8
當期變數值為 : 7
當期變數值為 : 6
拜拜!

乘法口訣

for i in range(1,5):
    for j in range(1,i+1):
        print('{1}*{0}={2}'.format(i,j,i * j),end=" ")
    print()

#輸出
1*1=1 
1*2=2 2*2=4 
1*3=3 2*3=6 3*3=9 
1*4=4 2*4=8 3*4=12 4*4=16