Python 구문 설탕
, 개행 연결
s = '' s += 'a' + \ 'b' + \ 'c' n = 1 + 2 + \ 3 # 6
while, else for 루프 외부
while 루프가 정상적으로 끝나면 실행됩니다(break 종료 없음). ) 또 다른.
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 표현식 in iterable }
#查询每个字母出现的次数。 strs = 'Hello World' s = { k : strs.count(k) for k in set(strs) }
집합 파생
{iterable의 표현식에 대한 표현식 }
튜플에는 파생이 없습니다
튜플 파생입니다 수식이 변경되었습니다 목록 이해에서 괄호까지, 나중에 생성기 이해를 발견했습니다.
제너레이터 파생
>>> num = ( x for x in range(5) )>>> num ...:<generator object <genexpr> at 0x7f50926758e0>
함수
函数关键字参数,默认参数值
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 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.

Python은 게임 및 GUI 개발에서 탁월합니다. 1) 게임 개발은 Pygame을 사용하여 드로잉, 오디오 및 기타 기능을 제공하며 2D 게임을 만드는 데 적합합니다. 2) GUI 개발은 Tkinter 또는 PYQT를 선택할 수 있습니다. Tkinter는 간단하고 사용하기 쉽고 PYQT는 풍부한 기능을 가지고 있으며 전문 개발에 적합합니다.

Python은 데이터 과학, 웹 개발 및 자동화 작업에 적합한 반면 C는 시스템 프로그래밍, 게임 개발 및 임베디드 시스템에 적합합니다. Python은 단순성과 강력한 생태계로 유명하며 C는 고성능 및 기본 제어 기능으로 유명합니다.

2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 같은 작업에 적합합니다.

2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

드림위버 CS6
시각적 웹 개발 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.
