Python是一種高級編程語言,它又被稱為「膠水語言」,因為它能夠很好地與其他語言進行協作,比如C、C++和Java等。Python語言具有簡單易學、開放源碼、可移植性強、支持多種編程範式(面向對象、函數式等)、可擴展性和健壯性等優點,已經成為數據科學、機器學習、Web開發等領域中最流行的語言之一。
一、Python基礎語法
1、變量
# 變量定義 a = 1 b = 'hello' c = [1, 2, 3] # 變量運算 d = a + 2 e = b + ' world' f = c[0] # 變量類型轉換 a_str = str(a) b_int = int(b) c_str = str(c)
2、流程控制
# 條件語句 if a > 1: print('a>1') elif a == 1: print('a=1') else: print('a<1') # 循環語句 for i in range(5): print(i) while a < 5: print(a) a += 1
3、函數和模塊
# 函數定義 def add(x, y): return x + y # 運行函數 res = add(1, 2) print(res) # 導入模塊 import math # 使用模塊函數 res = math.sqrt(4) print(res)
二、面向對象編程
1、類和對象
# 類定義 class Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): print('My name is %s, I am %d years old.' % (self.name, self.age)) # 對象創建 p1 = Person('Tom', 20) # 對象方法調用 p1.introduce()
2、繼承和多態
# 繼承 class Student(Person): def study(self): print('I am studying!') # 多態 class Teacher(Person): def introduce(self): print('I am a teacher, my name is %s.' % self.name) # 多態調用 p2 = Teacher('Jack', 30) p2.introduce()
三、Python高級應用
1、文件操作
# 寫入文件 with open('test.txt', 'w') as f: f.write('hello\nworld\n') # 讀取文件 with open('test.txt', 'r') as f: lines = f.readlines() for line in lines: print(line.strip())
2、正則表達式
import re # 匹配 str = 'name:Tom, age:20' res = re.findall('name:(\w+), age:(\d+)', str) print(res)
3、網絡編程
import socket # 創建socket對象 s = socket.socket() # 建立連接 s.connect(('www.baidu.com', 80)) # 發送HTTP請求 s.send(b'GET / HTTP/1.1\r\nHost: www.baidu.com\r\n\r\n') # 接收服務器返回數據 res = s.recv(1024) print(res.decode()) # 關閉連接 s.close()
4、多線程編程
import threading import time # 線程函數定義 def run(): for i in range(5): time.sleep(1) print('run:', i) # 創建線程 t = threading.Thread(target=run) # 啟動線程 t.start() # 主線程繼續執行 for i in range(5): time.sleep(1) print('main:', i) # 等待線程結束 t.join()
以上只是Python編程的冰山一角,掌握Python編程基礎及高級技巧才能真正使用Python編寫豐富、高效的應用程序。通過不斷實踐和學習,相信大家都能成為Python編程大師!
原創文章,作者:WJFWD,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/317881.html