文章目錄
- 一些優秀的博主
- 僅供自己查閱!!!
- 首先是掌握基本語法!
- 內置的運算符函數
- 函數模塊補充知識點
- pass
- 函數返回多個值
- 關于默認參數使用的注意事項
- 可變參數的使用方法
- 天天向上代碼
- 單元測試
- 異常處理代碼
- 單例模式
- Python 中的 if __name__ == '__main__' 該如何理解
- python環境搭建和pycharm的安裝配置及漢化(零基礎小白版)
- PyCharm和git安裝教程
- 爬蟲
- 簡單例子1
- 簡單例子2
- BeautifulSoup的使用1
- BeautifulSoup的使用1
一些優秀的博主
http://blog.konghy.cn/
廖雪峰大牛
Python3教程
僅供自己查閱!!!
首先是掌握基本語法!
先來幾個代碼
str1 = input("請輸入一個人的名字:")
str2 = input("請輸入一個國家的名字:")
print("世界這么大,{}想去看看{}:".format(str1,str2))
- 1到N求和
n = input("請輸入一個整數:")
sum = 0for i in range(int(n)):sum += i + 1
print("1到N求和的結果:",sum)
- 乘法口訣表
for i in range(1,10):for j in range(1,i +1):print("{}*{}={:2} ".format(j,i,i*j),end = '')print('')
- 打印1! + 2! + 3! + …10!
sum , tem = 0, 1
for i in range(1,4):print("{}".format(i))
for i in range(1,4):tem = i * temsum += tem
print("{}".format(sum))
- 猴子吃桃問題!
n = 1
for i in range(5,0,-1):n = (n + 1) << 1
print(n)
- 攝氏度和華氏度溫度轉換
TempStr = input("")if TempStr[0] in ['F','f']:C = (eval(TempStr) -32 ) /1.8print("{:.2f}C".format(C))
elif TempStr[0] in ['C','c']:F = 1.8 * eval(TempStr) + 32print("{:.2f}F".format(F))
else:print("輸入格式錯誤")
- 轉義字符處理方法
r’‘表示’'內部的字符串默認不轉義
# -*- coding: utf-8 -*-
n = 123
f = 456.789
s1 = 'Hello, world'
s2 = 'Hello, \'Adam\''
s3 = r'Hello, "Bart"'
s4 = r'''Hello,
Lisa!'''
可以看看這幾個輸出結果,在理解一下轉義字符吧
Hello, world
Hello, 'Adam'
Hello, "Bart"
Hello,
Lisa!
內置的運算符函數
- 這個要看,比較常用,掌握基本的意義
https://www.cnblogs.com/xiao1/p/5856890.html
函數模塊補充知識點
加入定義了一個函數,我們先不寫,但是其他模塊寫好了,要跑一下看看效果,可是這個函數沒有內容編譯器會報錯這個時候有一個概念
pass
- 空函數
def nop():pass
這樣子讓代碼是可以順利編譯運行的
if age >= 18:pass
函數返回多個值
def TestReturnValue(a, b, c, d):return a + b, c * dnum1, num2 = TestReturnValue(1, 2, 3, 4)print(num1, num2)r = TestReturnValue(1, 2, 3, 4)
print(r)
運行結果
3 12
(3, 12)Process finished with exit code 0
原來返回值是一個tuple!但是,在語法上,返回一個tuple可以省略括號,而多個變量可以同時接收一個tuple,按位置賦給對應的值,所以,Python的函數返回多值其實就是返回一個tuple,但寫起來更方便。《廖雪峰老師解釋》
關于默認參數使用的注意事項
- 如果你沒有第一種寫法,就會出現如下輸出所示的錯誤。本來指向給你的輸出后面加一個‘END’,但是每次調用就會多一個’END’。
def add_end_Right(L=None):if L is None:L = []L.append('END')return Ldef add_end_False(L=[]):L.append('END')return Lprint(add_end_Right())
print(add_end_Right())
print(add_end_Right())print(add_end_False())
print(add_end_False())
print(add_end_False())
- 輸出結果
['END']
['END']
['END']['END']
['END', 'END']
['END', 'END', 'END']
可變參數的使用方法
def Calculation(*num):count = 0for i in num:count += ireturn countprint(Calculation(1,2,3,4))
- 輸出
10
天天向上代碼
import math
dayup = math.pow((1.0 + 0.005), 365)
daydown = math.pow((1.0 - 0.005),365)print("向上:{:.2f},向下:{:.2f}.".format(dayup,daydown))
def dayUP(df):dayup = 0.01for i in range(365):if i % 7 in [6,0]:dayup = dayup * (1 - 0.01)else:dayup = dayup * (1 + df)return dayupdayfactor = 0.01
while(dayUP(dayfactor) < 37.78):dayfactor += 0.001print("每天努力參數是:{:.3f}.".format(dayfactor))
單元測試
原文鏈接
單元測試是用來對一個模塊、一個函數或者一個類來進行正確性檢驗的測試工作。
比如對函數abs(),我們可以編寫出以下幾個測試用例:
輸入正數,比如1、1.2、0.99,期待返回值與輸入相同;
輸入負數,比如-1、-1.2、-0.99,期待返回值與輸入相反;
輸入0,期待返回0;
輸入非數值類型,比如None、[]、{},期待拋出TypeError。
把上面的測試用例放到一個測試模塊里,就是一個完整的單元測試。
如果單元測試通過,說明我們測試的這個函數能夠正常工作。如果單元測試不通過,要么函數有bug,要么測試條件輸入不正確,總之,需要修復使單元測試能夠通過。
異常處理代碼
try:<body>
except <ErrorType1>:<handler1>except <ErrorType2>:<handler2>
except:<handler0>
else:<process_else>
finally:<process_finally>
單例模式
class Singleton(object):class _A(object):def __init__(self):passdef display(self):return id(self)_instance = Nonedef __init__(self):if Singleton._instance is None:Singleton._instance = Singleton._A()def __getattr__(self, attr):return getattr(self._instance, attr)if __name__ == '__main__':s1 = Singleton()s2 = Singleton()print(id(s1), s1.display())print(id(s2), s2.display())
代碼的解釋
def getattr(self, attr):
return getattr(self._instance, attr)
# 例如這里有一個類 A ,,有兩個屬性
>>> class A:
... test1 = "this test1"
... test2 = "this test2"
...
>>># 然后實例化一個對象
>>> a = A()# 就可以用 getattr 直接去獲取對象 a 的屬性值
>>> getattr(a, "test1")
'this test1'
>>>
>>> getattr(a, "test2")
'this test2'
>>>
Python 中的 if name == ‘main’ 該如何理解
http://blog.konghy.cn/2017/04/24/python-entry-program/
python環境搭建和pycharm的安裝配置及漢化(零基礎小白版)
https://blog.csdn.net/ling_mochen/article/details/79314118#commentBox
PyCharm和git安裝教程
https://blog.csdn.net/csdn_kou/article/details/83720765
爬蟲
學習資源是中國大學mooc的爬蟲課程。《嵩天老師》
下面寫幾個簡單的代碼!熟悉這幾個代碼的書寫以后基本可以完成需求!
簡單例子1
import requestsr = requests.get("https://www.baidu.com")
fo = open("baidu.txt", "w+")
r.encoding = 'utf-8'
str = r.text
line = fo.write( str )
簡單例子2
import requests
url = "https://item.jd.com/2967929.html"
try:r = requests.get(url)r.raise_for_status()//如果不是200就會報錯r.encoding = r.apparent_encoding//轉utf-8格式print(r.text[:1000])//只有前1000行
except:print("False")fo.close()
BeautifulSoup的使用1
fo = open("jingdong.md","w")url = "https://item.jd.com/2967929.html"
try:r = requests.get(url)r.encoding = r.apparent_encodingdemo = r.textsoup = BeautifulSoup(demo,"html.parser")fo.write(soup.prettify())fo.writelines(soup.prettify())
except:print("False")fo.close()
BeautifulSoup的使用1
fo = open("baidu.md","w")try:r = requests.get("https://www.baidu.com")r.encoding = r.apparent_encodingdemo = r.textsoup = BeautifulSoup(demo,"html.parser")fo.write(soup.prettify())fo.writelines(soup.prettify())
except:print("False")
fo.close()
附贈
爬蟲和python例子開源鏈接