日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python3参考秘籍-附PDF下载

發布時間:2024/2/28 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python3参考秘籍-附PDF下载 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 簡介
  • Python的主要數據類型
  • Python中的String操作
    • 基本操作
    • String連接
    • String復制
  • Math操作
  • 內置函數
  • 函數**Function**
    • 傳遞參數
  • 列表
    • 添加元素
    • 從list中刪除元素
    • 合并list
    • 創建嵌套的list
    • list排序
    • list切片
    • 修改list的值
    • list遍歷
    • list拷貝
    • list高級操作
  • 元組
    • 元組切片
    • 元組轉為list
  • 字典
    • 創建字典
    • 訪問字典的元素
    • 修改字典的元素
    • 遍歷字典
  • if語句
  • Python循環
    • for循環
    • while循環
    • break loop
  • Class
    • 創建class
    • 創建Object
    • 創建子類
  • 異常
    • 內置異常類型
    • 異常處理

簡介

Python作為一個開源的優秀語言,隨著它在數據分析和機器學習方面的優勢,已經得到越來越多人的喜愛。據說小學生都要開始學Python了。

Python的優秀之處在于可以安裝很多非常強大的lib庫,從而進行非常強大的科學計算。

講真,這么優秀的語言,有沒有什么辦法可以快速的進行學習呢?

有的,本文就是python3的基礎秘籍,看了這本秘籍python3的核心思想就掌握了,文末還有PDF下載鏈接哦,歡迎大家下載。

Python的主要數據類型

python中所有的值都可以被看做是一個對象Object。每一個對象都有一個類型。

下面是三種最最常用的類型:

  • Integers (int)

整數類型,比如: -2, -1, 0, 1, 2, 3, 4, 5

  • Floating-point numbers (float)

浮點類型,比如:-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25

  • Strings

字符串類型,比如:“www.flydean.com”

注意,字符串是不可變的,如果我們使用replace() 或者 join() 方法,則會創建新的字符串。

除此之外,還有三種類型,分別是列表,字典和元組。

  • 列表

列表用方括號表示: a_list = [2, 3, 7, None]

  • 元組

元組用圓括號表示: tup=(1,2,3) 或者直接用逗號表示:tup=1,2,3

Python中的String操作

python中String有三種創建方式,分別可以用單引號,雙引號和三引號來表示。

基本操作

my_string = “Let’s Learn Python!” another_string = ‘It may seem difficult first, but you can do it!’ a_long_string = ‘’‘Yes, you can even master multi-line stringsthat cover more than one linewith some practice’’’

也可以使用print來輸出:

print(“Let’s print out a string!”)

String連接

String可以使用加號進行連接。

string_one = “I’m reading “ string_two = “a new great book!” string_three = string_one + string_two

注意,加號連接不能連接兩種不同的類型,比如String + integer,如果你這樣做的話,會報下面的錯誤:

TypeError: Can’t convert ‘intobject to str implicitly

String復制

String可以使用 * 來進行復制操作:

‘Alice’ * 5 ‘AliceAliceAliceAliceAlice’

或者直接使用print:

print(“Alice” * 5)

Math操作

我們看下python中的數學操作符:

操作符含義舉例
**指數操作2 * 3 = 8*
%余數22 % 8 = 6
//整數除法22 // 8 = 2
/除法22 / 8 = 2.75
*****乘法3*3= 9
-減法5-2= 3
+加法2+2= 4

內置函數

我們前面已經學過了python中內置的函數print(),接下來我們再看其他的幾個常用的內置函數:

  • Input() Function

input用來接收用戶輸入,所有的輸入都是以string形式進行存儲:

name = input(“Hi! What’s your name? “) print(“Nice to meet you “ + name + “!”) age = input(“How old are you “) print(“So, you are already “ + str(age) + “ years old,+ name + “!”)

運行結果如下:

Hi! What’s your name? “Jim” Nice to meet you, Jim! How old are you? 25 So, you are already 25 years old, Jim!
  • len() Function

len()用來表示字符串,列表,元組和字典的長度。

舉個例子:

# testing len() str1 = “Hope you are enjoying our tutorial!” print(“The length of the string is :, len(str1))

輸出:

The length of the string is: 35
  • filter()

filter從可遍歷的對象,比如列表,元組和字典中過濾對應的元素:

ages = [5, 12, 17, 18, 24, 32] def myFunc(x):if x < 18:return Falseelse: return True adults = filter(myFunc, ages) for x in adults:print(x)

函數Function

python中,函數可以看做是用來執行特定功能的一段代碼。

我們使用def來定義函數:

def add_numbers(x, y, z): a= x + yb= x + zc= y + z print(a, b, c)add_numbers(1, 2, 3)

注意,函數的內容要以空格或者tab來進行分隔。

傳遞參數

函數可以傳遞參數,并可以通過通過命名參數賦值來傳遞參數:

# Define function with parameters def product_info(productname, dollars):print("productname: " + productname)print("Price " + str(dollars))# Call function with parameters assigned as above product_info("White T-shirt", 15)# Call function with keyword arguments product_info(productname="jeans", dollars=45)

列表

列表用來表示有順序的數據集合。和String不同的是,List是可變的。

看一個list的例子:

my_list = [1, 2, 3] my_list2 = [“a”, “b”, “c”] my_list3 = [4, d, “book”, 5]

除此之外,還可以使用list() 來對元組進行轉換:

alpha_list = list((1,2,3)) print(alpha_list)

添加元素

我們使用append() 來添加元素:

beta_list = [“apple”, “banana”, “orange”] beta_list.append(“grape”) print(beta_list)

或者使用insert() 來在特定的index添加元素:

beta_list = [“apple”, “banana”, “orange”] beta_list.insert(2 grape”) print(beta_list)

從list中刪除元素

我們使用remove() 來刪除元素

beta_list = [“apple”, “banana”, “orange”] beta_list.remove(“apple”) print(beta_list)

或者使用pop() 來刪除最后的元素:

beta_list = [“apple”, “banana”, “orange”] beta_list.pop() print(beta_list)

或者使用del 來刪除具體的元素:

beta_list = [“apple”, “banana”, “orange”] del beta_list [1] print(beta_list)

合并list

我們可以使用+來合并兩個list:

my_list = [1, 2, 3] my_list2 = [“a”, “b”, “c”] combo_list = my_list + my_list2 combo_list [1, 2, 3, ‘a’, ‘b’, ‘c’]

創建嵌套的list

我們還可以在list中創建list:

my_nested_list = [my_list, my_list2] my_nested_list [[1, 2, 3], [‘a’, ‘b’, ‘c’]]

list排序

我們使用sort()來進行list排序:

alpha_list = [34, 23, 67, 100, 88, 2] alpha_list.sort() alpha_list [2, 23, 34, 67, 88, 100]

list切片

我們使用[x:y]來進行list切片:

alpha_list[0:4] [2, 23, 34, 67]

修改list的值

我們可以通過index來改變list的值:

beta_list = [“apple”, “banana”, “orange”] beta_list[1] = “pear” print(beta_list)

輸出:

[‘apple’, ‘pear’, ‘cherry’]

list遍歷

我們使用for loop 來進行list的遍歷:

for x in range(1,4): beta_list += [‘fruit’] print(beta_list)

list拷貝

可以使用copy() 來進行list的拷貝:

beta_list = [“apple”, “banana”, “orange”] beta_list = beta_list.copy() print(beta_list)

或者使用list()來拷貝:

beta_list = [“apple”, “banana”, “orange”] beta_list = list (beta_list) print(beta_list)

list高級操作

list還可以進行一些高級操作:

list_variable = [x for x in iterable]number_list = [x ** 2 for x in range(10) if x % 2 == 0] print(number_list)

元組

元組的英文名叫Tuples,和list不同的是,元組是不能被修改的。并且元組的速度會比list要快。

看下怎么創建元組:

my_tuple = (1, 2, 3, 4, 5) my_tuple[0:3] (1, 2, 3)

元組切片

numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) print(numbers[1:11:2])

輸出:

(1,3,5,7,9)

元組轉為list

可以使用list和tuple進行相互轉換:

x = (“apple”, “orange”, “pear”) y = list(x) y[1] = “grape” x = tuple(y) print(x)

字典

字典是一個key-value的集合。

在python中key可以是String,Boolean或者integer類型:

Customer 1= {‘username’: ‘john-sea’, ‘online’: false, ‘friends’:100}

創建字典

下面是兩種創建空字典的方式:

new_dict = {} other_dict= dict()

或者像下面這樣來初始賦值:

new_dict = { “brand”: “Honda”, “model”: “Civic”, “year”: 1995 } print(new_dict)

訪問字典的元素

我們這樣訪問字典:

x = new_dict[“brand”]

或者使用dict.keys(),dict.values(),dict.items()來獲取要訪問的元素。

修改字典的元素

我們可以這樣修改字典的元素:

#Change the “year” to 2020: new_dict= { “brand”: “Honda”, “model”: “Civic”, “year”: 1995 } new_dict[“year”] = 2020

遍歷字典

看下怎么遍歷字典:

#print all key names in the dictionary for x in new_dict:print(x) #print all values in the dictionary for x in new_dict:print(new_dict[x]) #loop through both keys and values for x, y in my_dict.items(): print(x, y)

if語句

和其他的語言一樣,python也支持基本的邏輯判斷語句:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

看下在python中if語句是怎么使用的:

if 5 > 1:print(“That’s True!”)

if語句還可以嵌套:

x = 35if x > 20:print(“Above twenty,) if x > 30:print(and also above 30!”)

elif

a = 45 b = 45 if b > a:print(“b is greater than a”) elif a == b:print(“a and b are equal”)

if else:

if age < 4: ticket_price = 0 elif age < 18: ticket_price = 10 else: ticket_price = 15

if not:

new_list = [1, 2, 3, 4] x = 10 if x not in new_list:print(“’x’ isn’t on the list, so this is True!”)

Pass:

a = 33 b = 200 if b > a: pass

Python循環

python支持兩種類型的循環,for和while

for循環

for x in “apple”: print(x)

for可以遍歷list, tuple,dictionary,string等等。

while循環

#print as long as x is less than 8 i =1 while i< 8:print(x) i += 1

break loop

i =1 while i < 8:print(i) if i == 4:breaki += 1

Class

Python作為一個面向對象的編程語言,幾乎所有的元素都可以看做是一個對象。對象可以看做是Class的實例。

接下來我們來看一下class的基本操作。

創建class

class TestClass: z =5

上面的例子我們定義了一個class,并且指定了它的一個屬性z。

創建Object

p1 = TestClass() print(p1.x)

還可以給class分配不同的屬性和方法:

class car(object):“””docstring”””def __init__(self, color, doors, tires):“””Constructor”””self.color = colorself.doors = doorsself.tires = tiresdef brake(self):“””Stop the car“””return “Braking”def drive(self): “””Drive the car“””return “I’m driving!”

創建子類

每一個class都可以子類化

class Car(Vehicle):“””The Car class “””def brake(self):“””Override brake method“””return “The car class is breaking slowly!”if __name__ == “__main__”:car = Car(“yellow”, 2, 4, “car”)car.brake()‘The car class is breaking slowly!’car.drive()“I’m driving a yellow car!”

異常

python有內置的異常處理機制,用來處理程序中的異常信息。

內置異常類型

  • AttributeError — 屬性引用和賦值異常
  • IOError — IO異常
  • ImportError — import異常
  • IndexError — index超出范圍
  • KeyError — 字典中的key不存在
  • KeyboardInterrupt — Control-C 或者 Delete時,報的異常
  • NameError — 找不到 local 或者 global 的name
  • OSError — 系統相關的錯誤
  • SyntaxError — 解釋器異常
  • TypeError — 類型操作錯誤
  • ValueError — 內置操作參數類型正確,但是value不對。
  • ZeroDivisionError — 除0錯誤

異常處理

使用try,catch來處理異常:

my_dict = {“a”:1, “b”:2, “c”:3} try:value = my_dict[“d”] except KeyError:print(“That key does not exist!”)

處理多個異常:

my_dict = {“a”:1, “b”:2, “c”:3} try:value = my_dict[“d”] except IndexError:print(“This index does not exist!”) except KeyError:print(“This key is not in the dictionary!”) except:print(“Some other problem happened!”)

try/except else:

my_dict = {“a”:1, “b”:2, “c”:3} try:value = my_dict[“a”] except KeyError:print(“A KeyError occurred!”) else:print(“No error occurred!”)
  • 最后附上Python3秘籍的PDF版本: python3-cheatsheet.pdf

本文已收錄于 http://www.flydean.com/python3-cheatsheet/

最通俗的解讀,最深刻的干貨,最簡潔的教程,眾多你不知道的小技巧等你來發現!

歡迎關注我的公眾號:「程序那些事」,懂技術,更懂你!

總結

以上是生活随笔為你收集整理的python3参考秘籍-附PDF下载的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。