Python 菜鳥詳解

Python 是一門高級編程語言, 它簡單易用,而且人們已經開始發現它的魅力. 對於 Python 菜鳥來說,學習編程絕非容易的事,但一旦掌握了 Python,你可以使用它來完成各種各樣的任務,包括數據分析、機器學習、Web 開發等等. 今天,我們將從不同的角度來闡述 Python 泛菜鳥的各種技術點,幫助你更好的掌握這門編程語言.

一、Python 菜鳥基礎語法

1、Python 環境的搭建

直接去官網下載安裝即可
https://www.python.org/downloads/

2、Python 編寫第一個程序

print(“Hello World!”)

3、Python 聲明變量

# Python 學習變量的使用
counter = 100          # 整型變量
miles = 1000.0       # 浮點型變量
name = "Python"     # 字符串變量
 
print (counter)
print (miles)
print (name)

4、Python 數據類型

#Python 3 支持 int、float、complex(複數)
#Python3.x 支持bytes、str兩種類型的字符串,其中,'b'或'B'前綴表示byte字符串,沒有則表示unicode字符串。
a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))

5、Python 運算符

#Python算術運算符
print(5+4)   #加法
print(4.3-2)  #減法
print(3*7)   #乘法
print(2/4)   #除法,得到一個浮點數
print(2//4)  #除法,得到一個整數
print(17%3)  #取余 
print(2**5)  #乘方 

#Python比較運算符
a, b = 10, 20
print("a = ", a)
print("b = ", b)
print("a == b: ", a == b) # 等於
print("a != b: ", a != b) # 不等於
print("a > b: ", a > b) # 大於
print("a < b: ", a = b: ", a >= b) # 大於等於
print("a <= b: ", a <= b) # 小於等於

#Python賦值運算符
a = 21
b = 10
c = 0
c = a + b
print("c = a + b: ", c) # 賦值運算符
c += a
print("c += a : ", c)
c *= a
print("c *= a : ", c)
c /= a 
print("c /= a : ", c)
c = 2
c %= a
print("c %= a : ", c)
c **= a
print("c **= a : ", c)
c //= a
print("c //= a : ", c)

二、Python 數據分析

1、NumPy 基礎操作

import numpy as np
# 創建新的數組
x = np.array([1, 2, 3, 4, 5])
# 打印數組
print(x)
# 將列錶轉化為數組
y = np.array([[1, 2, 3], [4, 5, 6]])
# 打印多維數組
print(y)
# 打印數組大小
print("數組大小:", y.shape)
# 訪問數組元素(與 Python 列表類似)
print("y[1,2]為:", y[1, 2])

2、Pandas 數據分析

import pandas as pd
# 創造一個字典使'Name'作為關鍵字
df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob'],
                   'Age': [20, 21, 22],
                   'Gender': ['M', 'F', 'M']})
# 輸出數據框對象
print(df) 

3、Matplotlib 數據可視化

import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y = np.sin(x)
# 繪圖
plt.plot(x, y)
# 繪圖標題
plt.title('y=sin(x)')
# x、y軸標題
plt.xlabel('x')
plt.ylabel('y')
# 顯示
plt.show()

三、Python Web 開發

1、Flask 基於 Python 的 Web 開發框架

from flask import Flask, render_template,request,redirect,url_for,session
app = Flask(__name__)
app.secret_key = 'demo_key'  # session的密鑰
todos = []
@app.route('/')
def index():
    return render_template('index.html', todos=todos)

@app.route('/add', methods=['POST'])
def add():
    # 用戶輸入的任務列表加入到todos列表中
    content = request.form['content']
    todos.append(content)
    return redirect(url_for('index')) 

2、Django

# 安裝django
pip install django==2.0
# 創建並運行django項目
django-admin startproject firstproject
python manage.py runserver

3、Pyramid

# 安裝 Pyramid
pip install pyramid
# 創建 Pyramid項目
pcreate -s starter myproject
# 安裝所需的依賴項
cd myproject && pip install -e .
# 運行 Pyramid
pserve development.ini
# 瀏覽器中查看
localhost:6543

四、Python 機器學習

1、scikit-learn

from sklearn import datasets
# 導入數據集
iris = datasets.load_iris()
X = iris.data
y = iris.target

# 劃分為測試和訓練數據集
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=33)

# Z-score特徵規範化
from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)

# 使用KNN分類器
from sklearn.neighbors import KNeighborsClassifier
knc = KNeighborsClassifier()
knc.fit(X_train, y_train)
y_predict = knc.predict(X_test)

# 模型評估
from sklearn.metrics import classification_report
print('Accuracy: {}\n'.format(knc.score(X_test, y_test)))
print(classification_report(y_test, y_predict, target_names=iris.target_names))

# 數據可視化
import matplotlib.pyplot as plt
plt.scatter(X[y==0, 0], X[y==0, 1], color='red', marker='o', label='setosa')
plt.scatter(X[y==1, 0], X[y==1, 1], color='blue', marker='x', label='versicolor')
plt.scatter(X[y==2, 0], X[y==2, 1], color='green', marker='+', label='virginica')
plt.legend(loc='upper left')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.show()

2、TensorFlow

import tensorflow as tf
# 創建常量
a = tf.constant(5)
b = tf.constant(2)
c = tf.constant(3)

# 使用add()函數將兩個常量相加
d = tf.add(a, b)

# 使用multiply()函數將常量d乘3
e = tf.multiply(d, 3)

# 使用subtract()函數將常量e減c
f = tf.subtract(e, c)

# 創建會話並傳遞f來執行計算圖操作
with tf.Session() as sess:
    print(sess.run(f))

3、Keras

import keras
from keras.models import Sequential
from keras.layers import Dense, Activation

# 初始化模型
model = Sequential()

# 添加輸入層和隱藏層
model.add(Dense(units=64, input_dim=100))
model.add(Activation('relu'))

# 添加輸出層
model.add(Dense(units=10))
model.add(Activation('softmax'))

# 編譯模型
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

# 擬合模型
model.fit(X_train, y_train, epochs=20, batch_size=128)

# 評估模型
loss_and_metrics = model.evaluate(X_test, y_test, batch_size=128)

五、Python 爬蟲

1、Requests 爬蟲庫

import requests

# 發送 GET 請求
r = requests.get('http://www.baidu.com')

# 打印響應正文
print(r.text)
# 打印響應狀態碼
print(r.status_code)
# 打印響應頭部
print(r.headers)

2、BeautifulSoup 網頁解析庫

import requests
from bs4 import BeautifulSoup

# 發送 GET 請求
r = requests.get('http://www.baidu.com')

# 解析 HTML 代碼
soup = BeautifulSoup(r.text, 'html.parser')

# 檢索並打印所有鏈接
for link in soup.find_all('a'):
    print(link.get('href'))

3、Scrapy 爬蟲框架

# 安裝 Scrapy
pip install scrapy

# 創建新項目
scrapy startproject example

# 創建新爬蟲
scrapy genspider myspider example.com

# 運行爬蟲
scrapy crawl myspider

六、Python 性能優化

1、使用生成器替代列表

# 使用列表
def read_file():
    with open('huge_text_file.txt') as f:
        lines = f.readlines()
        for line in lines:
            yield line

# 使用生成器
def read_file():
    with open('huge_text_file.txt') as f:
        for line in f:
            yield line

2、使用 itertools 模塊優化代碼

import itertools
# 串行執行
for i in itertools.chain((1,2,3),('a','b','c')):
    print(i)

# 並行執行
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
    for result in executor.map(do_something, alist):
        print(result)

3、使用 functools.lru_cache() 優化並實現記憶化

import functools
@functools.lru_cache()
def fib(n):
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)

# 獲得斐波那契數列的第10項
print(fib(10))

Python 可以適用來完成各種各樣的工作,用來開發數據分析、機器學習、Web 應用和爬蟲等等都非常方便。希望以上內容對你理解和掌握 Python 的技能有所幫助!

原創文章,作者:QJBUB,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/369634.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
QJBUB的頭像QJBUB
上一篇 2025-04-13 11:45
下一篇 2025-04-13 11:45

相關推薦

  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29

發表回復

登錄後才能評論