python開發之數據類型概述 判斷語句 while循環

一.數據類型概述
數據類型比較
• 按存儲模型分類
– 標量類型:數值、字符串
– 容器類型:列表、元組、字典
• 按更新模型分類:
– 可變類型:列表、字典
– 不可變類型:數字、字符串、元組
• 按訪問模型分類
– 直接訪問:數字
– 順序訪問:字符串、列表、元組
– 映射訪問:字典
1.數字
1.1 基本數字類型
• int:有符號整數
• bool:布爾值
– True:1
– False:0
• float:浮點數
• complex:複數
1.2 數字表示方式
• python默認以十進制數顯示
• 數字以0o或0O開頭表示爲8進制數
• 數字以0x或0X開頭表示16進制數
• 數字以0b或0B開頭表示2進制數
2. 字符串
2.1 定義字符串
• python中字符串被定義爲引號之間的字符集合
• python支持使用成對的單引號或雙引號
• 無論單引號,還是雙引號,表示的意義相同
• python還支持三引號(三個連續的單引號或者雙引號),可以用來包含特殊字符
• python不區分字符和字符串
2.2 字符串切片
• 使用索引運算符[ ]和切片運算符[ : ]可得到子字符串
• 第一個字符的索引是0,最後一個字符的索引是-1
• 子字符串包含切片中的起始下標,但不包含結束下標

>>> py_str  =   'python'    
>>> py_str[0]   
'P' 
>>> py_str[-2]  
'o' 
>>> py_str[2:4] 
'th'    
>>> py_str[2:]  
'thon'  
>>> py_str[:4]  
'Pyth'  

2.3 字符串連接操作
• 使用+號可以將多個字符串拼接在一起
• 使用*號可以將一個字符串重複多次

>>> py_str='python' 
>>> is_cool='is Cool‘   
>>> print py_str + ' ' + is_cool    
python  is  Cool    
>>> py_str  *   2   
'pythonpython'  
  1. 列表
    3.1 定義列表
    • 可以將列表當成普通的“數組”,它能保存任意數量任意類型的python對象
    • 像字符串一樣,列表也支持下標和切片操作
    • 列表中的項目可以改變
>>> alist   =   [1, "tom",  2,  "alice"]    
>>> alist[1]    =   'bob‘   
>>> alist[2:]   

3.2 列表操作
• 使用in或not in判斷成員關係
• 使用append方法向列表中追加元素

>>> alist = [1, "tom",  2,  "alice"]    
>>> 'tom'   in  alist   
True    
>>> 'alice' not in  alist   
False   
>>> alist.append(3) 
>>> alist[5]='bob'  
Traceback (most recent call last):  
File "<stdin>", line 1, in  <module>    
IndexError: list assignment index out of range

4.元組
4.1元組的定義及操作
• 可以認爲元組是“靜態”的列表
• 元組一旦定義,不能改變

>>> atuple  =   (1, "tom",  2,  "alice")    
>>> 'tom'   in  atuple  
True    
>>> atuple[0]   =   3   
Traceback (most recent call last):  
File "<stdin>", line 1, in  <module>    
TypeError:'tuple' object does not support item assignment   

5.字典
5.1字典的定義及操作
• 字典是由鍵-值(key-value)對構成的映射數據類型
• 通過鍵取值,不支持下標操作

>>> user_dict   =   {'name':'bob',  'age':23}   
>>> use_dict['gender']  =   'male'  
>>> 'bob'   in  user_dict   
False   
>>> 'name'  in  user_dict   
True    
>>> user_dict[0]    
Traceback (most recent  call last): 
File "<stdin>", line 1,in <module> KeyError:0   

二. 判斷語句
1.if語句
1.1if語句語法結構
• 標準if條件語句的語法
if expression:
if_suite
else:
else_suite
• 如果表達式的值非0或者爲布爾值True, 則代碼if_suite被執行;否則就去執行else_suite
• 代碼組是一個python術語,它由一條或多條語句組成,表示一個子代碼塊
1.2 if語句示例解析

•  只要表達式數字爲非零值即爲True
>>> if  10: 
... print('Yes')    
Yes 
•  空字符串、空列表、空元組,空字典的值均爲False
>>> if  "": 
...   print('Yes')  
... else:   
...   print('No')   
No
  1. 擴展if語句
    2.1 擴展if語句結構
    if expression1:
    if_suite
    elif expression2:
    elif_suite
    else:
    else_suite
    2.2條件表達式
    • Python 在很長的一段時間裏沒有條件表達式(C ? X :Y),或稱三元運算符,因爲範·羅薩姆一直拒絕加入這樣的功能
    • 從Python 2.5集成的語法確定爲: X if C else Y
>>> x,  y   =   3,  4   
>>> smaller =   x   if  x   <   y   else    y   
>>> print   smaller 
3   

2.3.1案例:編寫判斷成績的程序
• 創建grade.py腳本,根據用戶輸入的成績分檔,要求
如下:
1. 如果成績大於60分,輸出“及格”
2. 如果成績大於70分,輸出“良”
3. 如果成績大於80分,輸出“好”
4. 如果成績大於90分,輸出“優秀”
5. 否則輸出“你要努力了”

[root@miss ~]# cat grade.py
score = int(input('成績:'))
if score >= 90:
    print('優秀')
elif score >= 80:
    print('好')
elif score >= 70:
    print('良')
elif score >= 60:
    print('及格')
else:
    print('你要每天努力了')

或
[root@miss ~]# cat grade2.py 
score = int(input('成績:'))

if score >= 60 and score < 70:
    print('及格')
elif 70 <= score < 80:
    print('良')
elif 80 <= score < 90:
    print('好')
elif score >= 90:
    print('優秀')
else:
    print('你要努力了!')

2.3.2案例:編寫石頭剪刀布小遊戲
編寫game.py,要求如下:
1. 計算機隨機出拳
2. 玩家自己決定如何出拳
3. 代碼儘量簡化

[root@miss ~]# cat game.py
import random

computer = random.choice(['石頭', '剪刀', '布'])
player = input('請出拳(石頭/剪刀/布):')

# print('您出了:', player, '計算機出的是:', computer)
print('您出了: %s, 計算機出的是: %s' % (player, computer))
if player == '石頭':
    if computer == '石頭':
        print('平局')
    elif computer == '剪刀':
        print('You WIN!!!')
    else:
        print('You LOSE!!!')
elif player == '剪刀':
    if computer == '石頭':
        print('You LOSE!!!')
    elif computer == '剪刀':
        print('平局')
    else:
        print('You WIN!!!')
else:
    if computer == '石頭':
        print('You WIN!!!')
    elif computer == '剪刀':
        print('You LOSE!!!')
    else:
        print('平局')

 或
 [root@miss ~]# cat game2.py
 import random

all_choices = ['石頭', '剪刀', '布']
win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['布', '石頭']]
prompt = '''(0) 石頭
(1) 剪刀
(2) 布
請選擇(0/1/2):'''
computer = random.choice(all_choices)
ind = int(input(prompt))
player = all_choices[ind]

print('您出了: %s, 計算機出的是: %s' % (player, computer))
if player == computer:
    print('\033[32;1m平局\033[0m')
elif [player, computer] in win_list:
    print('\033[31;1mYou WIN!!!\033[0m')
else:
    print('\033[31;1mYou LOSE!!!\033[0m')

3.while循環
3.1循環概述
• 一組被重複執行的語句稱之爲循環體,能否繼續重複,決定循環的終止條件
• Python中的循環有while循環和for循環
• 循環次數未知的情況下,建議採用while循環
• 循環次數可以預知的情況下,建議採用for循環
3.2while循環語法結構
• 當需要語句不斷的重複執行時,可以使用while循環

while   expression: 
     while_suite

• 語句while_suite會被連續不斷的循環執行,直到表達式的值變成0或False

sum100  =   0   
counter =   1   

while   counter <=  100:    
        sum100  +=  counter 
        counter +=  1   
print   ("result    is  %d" %   sum100) 

3.3 break語句
• break語句可以結束當前循環然後跳轉到下條語句
• 寫程序的時候,應儘量避免重複的代碼,在這種情況下可以使用while-break結構

name=input('username:   ')  
while name != 'tom':    
      name = input('username:   ')  
#可以替換爲
while True: 
      name = input('username:   ')  
      if name == 'tom': 
          break 

3.4 continue語句
• 當遇到continue語句時,程序會終止當前循環,並忽略剩餘的語句,然後回到循環的頂端
• 如果仍然滿足循環條件,循環體內語句繼續執行,否則退出循環

sum100=0    
counter=0   
while counter <= 100:   
      counter += 1  
      if counter % 2:   
          continue  
      sum100    +=  counter 
print("result  is  %d"  %  sum100)  

3.5 else語句
• python中的while語句也支持else子句
• else子句只在循環完成後執行
• break語句也會跳過else塊

sum10 = 0   
i = 1   

while i <=  10: 
      sum10 +=  i   
      i +=  1   
else:   
      print (sum10) 

3.6案例:完善石頭剪刀布小遊戲
編寫game2.py,要求如下:
1. 基於上節game.py程序
2. 實現循環結構,要求遊戲三局兩勝

[root@miss ~]# cat game3.py 
import random

all_choices = ['石頭', '剪刀', '布']
win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['布', '石頭']]
prompt = '''(0) 石頭
(1) 剪刀
(2) 布
請選擇(0/1/2):'''
pwin = 0
cwin = 0

while pwin < 2 and cwin < 2:
    computer = random.choice(all_choices)
    ind = int(input(prompt))
    player = all_choices[ind]

    print('您出了: %s, 計算機出的是: %s' % (player, computer))
    if player == computer:
        print('\033[32;1m平局\033[0m')
    elif [player, computer] in win_list:
        pwin += 1
        print('\033[31;1mYou WIN!!!\033[0m')
    else:
        cwin += 1
        print('\033[31;1mYou LOSE!!!\033[0m')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章