Python手記-5:Python入門基礎

官宣,截至2020 年01月01日,Python2已停止更新,Python 2.7是Python 2.x最後的版本。關於Python 3.x 版本與Python 2.x之間的區別可以參考:https://www.runoob.com/python/python-2x-3x.html

關於Python編碼規範參考:https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/#comments

1.數據類型與運算

1.1 數據類型

1.2 簡單運算

2.Python語句

2.1 if 條件語句

2.2 for 循環語句

2.3 while 循環語句

2.4 try/except異常處理語句

3 函數與Python庫

3.1 函數

3.2 Python庫(摘自官文)

1.數據類型與運算

1.1 數據類型

Python有6中數據類型:數字、字符串、列表、字典、元祖、集合。 

  • Python 3支持int、float、bool、complex(複數),在Python 3裏,只有一種整數類型int表示爲長整型,沒有Python 2中的long;
>>> a=1 
>>> print(type(a))  #  type()函數顯示變量類型。
<class 'int'>
>>> name='chengyu'
>>> print(type(name))
<class 'str'>
>>> c=str(a)+name  # str()函數轉換數字爲字符串
>>> print(c)
1chengyu
>>> c=name+'1'  
>>> print(type(c))
<class 'str'>
  • 列表元素可以是字符串、數字、列表,用[]標識;
>>> listtest=['撒野', '殘次品', '殺破狼', '某某', '全球高考', '刺青'] 
>>> for i in listtest:
...   print(i)
... 
撒野
殘次品
殺破狼
某某
全球高考
刺青
>>> listtest=['木蘇里',1,['某某','全球高考','一級律師']]
>>> for i in listtest:
...   print(i)
... 
木蘇里
1
['某某', '全球高考', '一級律師']
>>> numb = len(listtest)  # 列表元素個數統計
>>> print(numb)
3
>>> numb1 = listtest[1]  # 指定輸出列表單個元素,起始序號爲0.
>>> print(numb1)
1
>>> numb2 = listtest[0:2]  # 列表多個元素輸出
>>> print(numb2)
['木蘇里', 1]
>>> numb3 = listtest[0:1]  # 序號遵循“左開右閉”原則
>>> print(numb3)
['木蘇里']
>>> listtest=['木蘇里',1,['某某','全球高考','一級律師']]
>>> listtest.append('絕美愛情')  # append()追加元素
>>> print(listtest)
['木蘇里', 1, ['某某', '全球高考', '一級律師'], '絕美愛情']


  • 列表是有序的對象結合(每個元素只有一個部分),字典是無序的對象集合,每個元素有兩部分組成(鍵+值)。兩者之間的區別在於:字典當中的元素時通過鍵來存取的,而不是通過偏移存取, 用{} 標識。
# 提取指定key的值:字典名[‘鍵名’]
>>> dicttest = {'木蘇里':'某某','priest':'撒野','羲和清零':'助理建築師','水千丞':'一醉經年'}
>>> print(dicttest['木蘇里'])
某某

# 輸出整個列表
>>> for i in dicttest:
...   print(i + '作品:' + dicttest[i])
... 
木蘇里作品:某某
priest作品:撒野
羲和清零作品:助理建築師
水千丞作品:一醉經年

# items()函數遍歷輸出整個列表
>>> dictitems = dicttest.items()
>>> print(dictitems)
dict_items([('木蘇里', '某某'), ('priest', '撒野'), ('羲和清零', '助理建築師'), ('水千丞', '一醉經年')])
  • 元組:類似列表,不同之處:列表[]標識,元組()標識,另外元組的元素不能修改,元素之間用逗號隔開;
>>> tupletest = ('顧一', '林二', '邢三', '李四')
>>> print(tupletest[0:3])
('顧一', '林二', '邢三')
  • 集合是一個無序不重複元素的序列,類似列表,基本功能元素間的關係測試和存儲不重複元素,輸出無序。
>>> settest = ('顧一', '林二', '邢三', '李四', '顧一')
>>> print(set(settest))
{'顧一', '李四', '林二', '邢三'}

 

1.2 簡單運算

# 術運算符,運算優先級:** > * > / > % > // > + -

  • print(10+34)
  • print(30-32)
  • print(3*2) # 乘
  • print(3**2) # 冪運算
  • print(34/3) # 除
  • print(34//3) # 取整數
  • print(34%3) # 取餘數
  • print("喜歡你"*100) # 字符運算
[root@chengyu ~]# python3
Python 3.8.2 (default, Mar 16 2020, 14:21:03)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 10+34
44
>>> 30-32
-2
>>> 3*2
6
>>> 3**2
9
>>> 34/3
11.333333333333334
>>> 34//3
11
>>> 34%3
1
>>> "喜歡你"*100
'喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你喜歡你'

邏輯運算not、and、or:

>>> year = 2020
>>> month = 4
>>> if (year == 2020) and (month < 5):
...   print('過去,喜歡是一廂情願')
... else:
...   print('未來,喜歡是義無反顧')
... 
過去,喜歡是一廂情願

>>> if (year > 2020) or (month != 4):
...   print('time is dog')
... else:
...   print('love is color blind')
... 
love is color blind

>>> if not(year == 2020 and month == 4):
...   print(date)
... else:
...   print('幸福是:天上星,杯中月,眼前人!')
... 
幸福是:天上星,杯中月,眼前人!

2.Python語句

2.1 if 條件語句

if 條件語句主要用於判斷,基本的語法:

if 判斷條件:
  執行代碼1
else:
  執行代碼2

>>> salary = 20000
>>> if salary >= 20000:
...   print('處於工資分佈top:1.6%')
... elif salary >= 10000 and salary <= 15000:
...   print('處於工資分佈top:5.4%')
... elif salary >= 8000 and salary <= 10000:
...   print('處於工資分佈top:11%')
... else:
...   print('二八定律80%人羣')
... 
處於工資分佈top:1.6%

2.2 for 循環語句

for語句:

for i in 循環區域:
  循環執行的代碼

>>> citylist=['哈爾濱', '武漢', '廣州', '深圳']
>>> for city in range(len(citylist)):
...   print('城市名:' + citylist[city])
... 
城市名:哈爾濱
城市名:武漢
城市名:廣州
城市名:深圳

>>> for city in range(len(citylist)):
...   if citylist[city] == '哈爾濱':
...     print(citylist[city] + '學府四道街22:00的路燈')
...     continue
...   else:
...     print('城市名:' + citylist[city])
... 
哈爾濱學府四道街22:00的路燈
城市名:武漢
城市名:廣州
城市名:深圳

>>> for city in citylist:
...    if city == '哈爾濱':
...      print(city + '學府四道街22:00的路燈')
...      break
...    else:
...     print('城市名:' + city)
... 
哈爾濱學府四道街22:00的路燈

2.3 while 循環語句

控制條件變量要繼續使用就用while,否則用for,已知循環次數用for循環,未知循環次數用while循環。

while 判斷條件:
  重複執行的代碼

>>> a=1
>>> while a < 20:
...   a+=5
...   print(a)
... 
6
11
16
21

>>> a=1
>>> while a < 20:
...   print(a)
...   a+=5
...   if a > 15:
...     break
... 
1
6
11

2.4 try/except異常處理語句

即使語句或表達式在語法上是正確的,執行時,仍可能會引發錯誤,try/except就是監查try語句塊中的執行異常,通過except語句捕獲異常信息並處理,工作原理:

  • 首先,執行 try 子句try except 關鍵字之間的(多行)語句);

  • 如果沒有異常發生,則跳過 except 子句並完成 try 語句的執行;

  • 如果在執行 try 子句時發生了異常,則跳過該子句中剩下的部分;然後,如果異常的類型和 except 關鍵字後面的異常匹配,則執行 except 子句,然後繼續執行 try 語句之後的代碼;

  •  如果發生的異常和 except 子句中指定的異常不匹配,則將其傳遞到外部的 try 語句中;如果沒有找到處理程序,則它是一個 未處理異常,執行將停止並顯示如上所示的消息。

try:
<主執行語句>        
except:
<主執行語句false時要執行的語句>

>>> 1 + 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> try:
...   print(1 + 'a')
... except:
...   print('數字和字符串不可直接相加')
... 
數字和字符串不可直接相加      

3 函數與Python庫

3.1 函數

def 函數名(參數):
  代碼

>>> def dataadd(datalist):
...   datalist.append([1,2,3])
...   print (datalist)
... 
>>> dataadd([4,5])
[4, 5, [1, 2, 3]]

Python常用的內置函數:

3.2 Python庫(摘自官文)

引用庫的兩種方法:

  • import 庫名

  • from 庫名 import 庫裏的功能

  1. os 模塊提供許多與操作系統交互的函數;
>>> import os
>>> os.getcwd()
'/root'
一定要使用 import os 而不是 from os import * 。這將避免內建的 open() 函數被 os.open()
隱式替換掉,它們的使用方式大不相同。
內置的 dir() 和 help() 函數可用作交互式輔助工具,用於處理大型模塊,如 os:
>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>

2. glob 模塊提供在目錄中使用通配符搜索創建文件列表的函數;

>>> import glob
>>> glob.glob('/home/*.py')
['/home/pyttest.py', '/home/test1.py', '/home/test.py']

3.re 模塊爲高級字符串處理提供正則表達式工具;

>>> import re
>>> re.findall(r'\bf[a-z]*','whichfootorhandfellfastest')
['foot','fell','fastest']
>>> re.sub(r'(\b[a-z]+)\1',r'\1','catinthethehat')'
catinthehat'

4.math 模塊提供對浮點數學的底層 C 庫函數的訪問,random 模塊提供了進行隨機選擇的工具,statistics 模塊計算數值數據的基本統計屬性(均值,中位數,方差等);

>>> import math
>>> math.cos(math.pi / 4)
0.7071067811865476
>>> math.log(1024, 2)
10.0
>>> import random
>>> random.choice(['Monday', 'Tuesday', 'Wednesday'])
'Wednesday'
>>> random.sample(range(10), 5)  
[2, 3, 4, 6, 1]
>>> random.random()  # random float
0.47573922852176354
>>> random.randrange(10)  # random integer chosen from range(10)
6
>>> import statistics
>>> data = [1.2, 4.4, 5.24, 2.5, 6.1]
>>> statistics.mean(data)
3.888
>>> statistics.median(data)
4.4
>>> statistics.variance(data)
4.03372

5.urllib.request用於訪問互聯網和處理互聯網協議;

6.datetime 模塊提供以簡單和複雜的方式操作日期和時間的類。

>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2020, 4, 22)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'04-22-20. 22 Apr 2020 is a Wednesday on the 22 day of April.'

 

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