Python 語法糖
,換行連接
s = '' s += 'a' + \ 'b' + \ 'c' n = 1 + 2 + \ 3 # 6
while,for 循環外的 else
如果 while 循環正常結束(沒有break退出)就會執行else。
num = [1,2,3,4] mark = 0while mark < len(num): n = num[mark] if n % 2 == 0: print(n) # break mark += 1else: print("done")
zip() 平行迭代
a = [1,2,3] b = ['one','two','three'] list(zip(a,b)) # [(1, 'one'), (2, 'two'), (3, 'three')]
列表推導式
x = [num for num in range(6)] # [0, 1, 2, 3, 4, 5] y = [num for num in range(6) if num % 2 == 0] # [0, 2, 4] # 多层嵌套 rows = range(1,4) cols = range(1,3) for i in rows: for j in cols: print(i,j) # 同 rows = range(1,4) cols = range(1,3) x = [(i,j) for i in rows for j in cols]
字典推導式
{ key_exp : value_exp fro expression in iterable }
{ key_exp : value_exp fro expression in iterable }元組沒有推導式本以為元組推導式是列表推導式改成括號,後來發現那個生成器推導式。 產生器推導式
#查询每个字母出现的次数。 strs = 'Hello World' s = { k : strs.count(k) for k in set(strs) }函數
函数关键字参数,默认参数值
def do(a=0,b,c) return (a,b,c) do(a=1,b=3,c=2)
函数默认参数值在函数定义时已经计算出来,而不是在程序运行时。
列表字典等可变数据类型不可以作为默认参数值。
def buygy(arg, result=[]): result.append(arg) print(result)
changed:
def nobuygy(arg, result=None): if result == None: result = [] result.append(arg) print(result) # or def nobuygy2(arg): result = [] result.append(arg) print(result)
*args 收集位置参数
def do(*args): print(args) do(1,2,3) (1,2,3,'d')
**kwargs 收集关键字参数
def do(**kwargs): print(kwargs) do(a=1,b=2,c='la') # {'c': 'la', 'a': 1, 'b': 2}
lamba 匿名函数
a = lambda x: x*x a(4) # 16
生成器
生成器是用来创建Python序列的一个对象。可以用它迭代序列而不需要在内存中创建和存储整个序列。
通常,生成器是为迭代器产生数据的。
生成器函数函数和普通函数类似,返回值使用 yield 而不是 return 。
def my_range(first=0,last=10,step=1): number = first while number < last: yield number number += step >>> my_range() ... <generator object my_range at 0x7f02ea0a2bf8>
装饰器
有时需要在不改变源代码的情况下修改已经存在的函数。
装饰器实质上是一个函数,它把函数作为参数输入到另一个函数。 举个栗子:
# 一个装饰器 def document_it(func): def new_function(*args, **kwargs): print("Runing function: ", func.__name__) print("Positional arguments: ", args) print("Keyword arguments: ", kwargs) result = func(*args, **kwargs) print("Result: " ,result) return result return new_function # 人工赋值 def add_ints(a, b): return a + b cooler_add_ints = document_it(add_ints) #人工对装饰器赋值 cooler_add_ints(3,5) # 函数器前加装饰器名字 @document_it def add_ints(a, b): return a + b
可以使用多个装饰器,多个装饰由内向外向外顺序执行。
命名空间和作用域
a = 1234 def test(): print("a = ",a) # True #### a = 1234 def test(): a = a -1 #False print("a = ",a)
可以使用全局变量 global a 。
a = 1234 def test(): global a a = a -1 #True print("a = ",a)
Python 提供了两个获取命名空间内容的函数 local() global()
_ 和 __
Python 保留用法。 举个栗子:
def amazing(): '''This is the amazing. Hello world''' print("The function named: ", amazing.__name__) print("The function docstring is: \n", amazing.__doc__)
异常处理,try...except
只有错误发生时才执行的代码。 举个栗子:
>>> l = [1,2,3] >>> index = 5 >>> l[index] Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: list index out of range
再试下:
>>> l = [1,2,3] >>> index = 5 >>> try: ... l[index] ... except: ... print("Error: need a position between 0 and", len(l)-1, ", But got", index) ... Error: need a position between 0 and 2 , But got 5
没有自定异常类型使用任何错误。
获取异常对象,except exceptiontype as name
hort_list = [1,2,3]while 1: value = input("Position [q to quit]? ") if value == 'q': break try: position = int(value) print(short_list[position]) except IndexError as err: print("Bad index: ", position) except Exception as other: print("Something else broke: ", other)
自定义异常
异常是一个类。类 Exception 的子类。
class UppercaseException(Exception): pass words = ['a','b','c','AA'] for i in words: if i.isupper(): raise UppercaseException(i) # error Traceback (most recent call last): File "<stdin>", line 3, in <module> __main__.UppercaseException: AA
命令行参数
命令行参数
python文件:
import sys print(sys.argv)
PPrint()友好输出
与print()用法相同,输出结果像是列表字典时会不同。
类
子类super()调用父类方法
举个栗子:
class Person(): def __init__(self, name): self.name = nameclass email(Person): def __init__(self, name, email): super().__init__(name) self.email = email a = email('me', 'me@me.me')>>> a.name... 'me'>>> a.email... 'me@me.me'
self.__name 保护私有特性
class Person(): def __init__(self, name): self.__name = name a = Person('me')>>> a.name... AttributeError: 'Person' object has no attribute '__name'# 小技巧a._Person__name
实例方法( instance method )
实例方法,以self作为第一个参数,当它被调用时,Python会把调用该方法的的对象作为self参数传入。
class A(): count = 2 def __init__(self): # 这就是一个实例方法 A.count += 1
类方法 @classmethod
class A(): count = 2 def __init__(self): A.count += 1 @classmethod def hello(h): print("hello",h.count)
注意,使用h.count(类特征),而不是self.count(对象特征)。
静态方法 @staticmethod
class A(): @staticmethod def hello(): print("hello, staticmethod") >>> A.hello()
创建即用,优雅不失风格。
特殊方法(sqecial method)
一个普通方法:
class word(): def __init__(self, text): self.text = text def equals(self, word2): #注意 return self.text.lower() == word2.text.lower() a1 = word('aa') a2 = word('AA') a3 = word('33') a1.equals(a2) # True
使用特殊方法:
class word(): def __init__(self, text): self.text = text def __eq__(self, word2): #注意,使用__eq__ return self.text.lower() == word2.text.lower() a1 = word('aa') a2 = word('AA') a3 = word('33') a1 == a2# True
# True
其他还有:
*方法名* *使用* __eq__(self, other) self == other __ne__(self, other) self != other __lt__(self, other) self < other __gt__(self, other) self > other __le__(self, other) self <= other __ge__(self, other) self >= other __add__(self, other) self + other __sub__(self, other) self - other __mul__(self, other) self * other __floordiv__(self, other) self // other __truediv__(self, other) self / other __mod__(self, other) self % other __pow__(self, other) self ** other __str__(self) str(self) __repr__(self) repr(self) __len__(self) len(self)
文本字符串
'%-10d | %-10f | %10s | %10x' % ( 1, 1.2, 'ccc', 0xf ) # '1 | 1.200000 | ccc | 33'
{} 和 .format
'{} {} {}'.format(11,22,33) # 11 22 33 '{2:2d} {0:-10d} {1:10d}'.format(11,22,33) # :后面是格式标识符 # 33 11 22 '{a} {b} {c}'.format(a=11,b=22,c=33)

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3漢化版
中文版,非常好用

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),