Python Quick Reference

泓熠 (HY)

Copyright © 2026, 泓熠 (HY).
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.

Python Interpreter Installation

C Python
The official Python interpreter, which is use C language to achieve.
Pypy
The interpreter which use Python to achieve.

Python Installation in Debian 12/13


# Coding complier installation
apt install  #
	-y  # Answer yes automatically if any.
	# No options.
		python3 # Install Python3 in Debian.
		python3-venv # Install Python3 virtual environment.
		python3-full # Install full python3, which includes IDLE and other graphical software.
		python3-pip # Install the pip toos.
		python3-numpy # In Debian, pip command is unable, most of pypi packages are included by apt source. These can be installed through this way.
		pipx # This toos can replace the enabled pip in Debian.

pip3  #
pip  #
	install  # Install a package included by pypi.
		CoolProp # The name of package.
	install numpy -i https://pyi.tuna.tsinghua.edu.cn/simple # Install a package using the mirror site appointed.
	list # Show all packages installed by pip/pip3.
	install './example/mymodule.whl' # Install 3rd part package by appointing .whl file.
	uninstall numpy # Uninstall a package.
	install --upgrade pip # Upgrade the pip tools.

python3 -m venv  # Create or delete a virtual environment by venv.
	# Create a virtual environment.
	--clear  # Delete virtual environment.
		./myenv # The path where the virtual environment is created.

source  #
.  # Equal to source.
	./myenv/bin/activate # Enter the virtual environment created.

pip  #
	install CoolProp # When entered a virtual environment, all packages included by pypi can installed through pip.

deactivate # Exit current virtual environment.

			

File & Run & Comment & Symbol

Run

python3  # Launch Python3.
	# Enter the Python Shell.
	--version # View current Python version installed.
	example.py # The path of the file to run through Python3.

			
Comment

# This is end-of-line or long-line comment.
"""
This is
multi-line
comment.
"""
'''
This is
multi-line
comment.
'''

			

Symbols

Symbol Description
. The module in package
The function in module
The attribute or method of object
() The argument of function or method
The literial quantity of tuple
The futher class when define a class
The default attribute when create a object
The priority of the operation
[] The literial quantity of list
Sequential slicing
{} The literial of set or dict(ionary)
The formated part in a str(ing) when formatting
''
""
The literial of str(ing)

Usual IDE (Integrated Development Environment)

IDLE
The official Python build-in IDE.
Pycharm
JetBrains
Jupyter
A interactive notebook for markdown and Python or Julia.

The Three Methods to Format String.

Use the "format" method.


'{0:_:>+20,.5} and {1}'.format(a, b) # This is an example.

'{
	0 # 0 means the 1st variable.
	1 # 1 means the 2nd variable.
		: # A fixed boot character.
			# Default has none.
			_ # The character to full.
				# Default.
				> # Justify right as the default.
				< # Justify left.
				^ # Justify center.
					# Default has none.
					+ # The plus character.
					- # The minus character.
						20 # The output width equivalent to 20.
							# The default has none.
							, # The thousand separator is ",", which is used in int(eger) and float.
							_ # The thousand separator is "_".
								.5 # The decimal place is 5.
									b # The number type is int(eger) binary mode.
									d # The number type is int(eger) decimal form.
									c # The number type is unicode characters corresponding to int(egers).
									x # The number type is int(eger) in lower-case hexadecimal form.
									X # The number type is int(eger) in upper-case hexadecimal form.
									f # The number type is floating point with a standard floating point form.
									% # The numberdata type is percentage form of floating number.
									E # Floating-point numbers correspond to the scientific notation form of the upper-case letter E.
									e # Floating-point numbers correspond to the scientific notation form of the lower-case letter e.
										}and{
											0 # 0 means the 1st variable.
											1 # 1 means the 2nd variable.
												}'.format(
													a,  # The 1st variable name.
														b # The 2nd variable name. Here are indeterminate length parameters.
															)

			

Using the "%" character


num = 1

f'The number is {%5.2f}' % (num) # This is an example.

f'The number is {
	%
		5 # The output width is 5. whose default is none.
			.2 # The decimal place is 2, whose defaule is none.
				f # The number type is floating number.
					}' % (
						num # The variable in the % position.
							)

			

Quckly formatting


a = 1

f'a is {
	a # The variable.
		}' # Fast format a str(ing).

print(f"{a = }") # This will print "a = 1", which can print the name and the value of variable conveniently.

			

Escape Character

Escape Character Description
\n New line symbol
\t Horizontal tab symbol
\\ Blackslash
\" Double quotation mark
\' Simgle quotation mark

Basic Syntax

Line breaks and indents that indicate statement attribution are mandatory rules.


# The assignment Statement.
none_example = None # An assignment statement which stores data in a variable.
a = b = 1 # Continuous assignment statement, run from right to left.
b = (a := 1) # The walrus operator, assigns and causes the entire parenthesis container to return the assigned value.
a, b = [1, 2] # Extract list elements and assign values.
a, b = (1, 2) # Extract the tuple elements and assign values.

# The Selection Statement.
if none: # The conditional statement, where "if" should be followed by a logical quantity.
	pass # The "pass" has no meaning, just as a format placeholder.
	continue # Jump this round of the loop, and then continue the next round.
elif bool_false: # The conditional statement, where "elif" should be followed by a logical quantity.
	pass
else:
	break # End the while loop.

# Loop statement.
while bool_true: # The loop statement. where "while" should be followed by a logical quantity.
	pass

# Iteration statement
for i in a: # Traversal statement, which make the variables equivalent to the elements in the iterator in turn.
	pass
2d_array = [[1, 2], [3, 4]]
for x, y in 2d_array: # Traverse two variables simultaneously over the two-dimensional data. On the round 1, x=1 and y=2; on the round 2 x=3 and y=4.
	pass

			

Operator

Numeric operator

Operator Meaning
+ Plus numbers
Sequence splicing
- Miums
* Mulitiply the number
Mulitiply the sequence
Sequence objects are split into multiple parameters
/ Devide
// Devide exactly
% Devide and calculate remainder
** Power
Split the dict(ionary) object into multiple keyword parameters
and AND, if the left return False, it will return False directly, the right will not run.
or OR, if the left return True, it will return True directly, the right will not run.
not NOT
in Whether in?
not in Whether not in?
>= More than or equal to?
Binary left shift operation, Discard the high and pad the low with zeros.
<= Less than or equal to?
Binary left shift operation, Discard the high and pad the low with zeros.
> More than?
< Less than?
1 < a < 2 In the interval?
! Not equal to?
is The same object?
is not Not the same object?
\ Set and dict(ionary) union
Binary OR operation
& Binary AND operation
^ Binary XOR operation
~ Binary NOT operation

The Naming Rule of Identifiers

Number

Number Description
123 Decimal int(eger) literal value.
1.2e+04 Decimal int(eger) represented in scientific notation literal value
0b10110 Binary int(eger) literal value (beginging with 0b
0o13415 Octonary int(eger) literal value (begining with 0o)
0x4328fba Hexadecimal int(eger) literal value (begining with 0x)
1.5 Decimal float literal value.

Bool Value and the None Value

Bool literal value Description
True The true bool value literal value
False The false bool value literal value
None The "None" literal value

String

Literal value Description
'example'
"example"
String literal value in a row

'''
example
''' # Cross-line str(ing) literal value, like multi-line comments.
"""
example
""" # Cross-line str(ing) literal value, like multi-line comments.

		
The operation of str(ing).

str_eg # Below the method will not change this object.
	.replace(  #
		"replaced",  # The part to be displaced.
			"replacing"  # The part to displace.
				) # Replace the part in the str(ing) and return.
	.strip(
		# Default is space symbol (\b) and linkbreak (\n).
		"st1"  # The character to remove.
				) # Remove the character in the begining and end to generate a new str(ing) to return.
	.split(  #
		# Default is space symbol (\b).
		","  # Split by this character.
			) # Return a list which is composed by some str(ings) splited and return.
	.lower() # Conver all letters in the str(ing) to lowercase and return.
	.upper() # Conver all letters in the str(ing) to upper and return.

			

Tuple

Tuple Desctiption
{} The literal value of a empty tuple
(1,'a') The literal value of a tumple
('a', ) The literal value of a tuple which has only an element. It must has a comma, otherwise will be confusing with funcition parameters.

tuple_eg = ([1, 2], "a")
tuple_eg[1] = "b" # Syntax WRONG.
tuple_eg[0][1] = 3 # Syntax correct.

			

List

List Description
[] The literal value of a empty list
['a', 1] The literal value of a list

list_a = list_b # Assign a list for different identifiers, which have same id (id function). if change a object for a name, then another object will be change.
list_example[1] = 1 # Index and slice elements in a list can be assigned again.
del list_eg[2] # Delete the element appointed index in this object.
list_eg # Below the method will change this list object.
	.insert( # Insert an element in this list object.
		1,  # The element index which on the right of the insert position.
			"a" # The element to insert.
	.append( # Append an element in this list object.
		"c" # The element to append.
	.extend( # Extend a list in the end of this list.
		list_b # The list to extend.
	.pop( # Delete the element appointed in the list.
		1 # The index of the element to delete.
		# Default index is -1.
	.remove( # Remove the element appointed on the far left.
		'c' # The element to remove.
	.reverse( # Reverse the list.
	clear( # Clear this set.
				) # Return None.

			

Set


set_a = {1, 1, "a"} # The set literal value. Elements will be automatically de-duplicated.
set_example # Below the method will change this set object.
set_a # Below the method will change this set object.
	.add( # Add an element in the set.
		"python" # The element to add.
	.remove( # Remove an element in this set object.
		"python" # The element to remove.
	.pop( # Remove an element in this set object.
		'element' # The element to remove.
	.difference_update( # Remove elements shared with another set.
		set_b # The other set.
	.union( # Union of two sets.
		set_b # The 2nd set.
	.diffenence( # The difference set of two sets. The first set is as the minuend of the subtraction operation.
		set_b # The subtrahend of the subtraction operation.
	.clear( # Clear the set.
			) # Return None.

			

Directory


a = {} # Empty dirctory literal quantity.
a = {"key1": "value1", "key2": "value2"} # Directory literal quantity.
dict_1["key1"] # The value of key appointed.
dict_1[ # Reassigns a value to the key of the element. If the key is not present, the new element will be added.
	"keyexample" # The key to reassign.
		] = "valueexample" # The value of the element.
dict_1.pop( # Delete element in the dict(ionary).
	"keyexample" # The key of element to delete.
		)
dict_1.keys() # Return a object dict_keys like a list including all keys.
dict_1.items() # Return a object dict_items like a list (whose elements is tuples) including keys and values.
dict_1.clear() # Empty dict(ionary).
dict_1.get(
	'a',  # The key to find.
		0 # The return value appointed if can not find.
			) # Return the value found or the return value appointed if can not find.

			

Data Container

String, list, tuple, set and dict(ionary) all is called data container.

The general function of data container.


str_a # Below method will not change the list object.
	.join(
		iter # The data container.
			) # Add a str(ing) to each element of the data container and then concatenate the generated new str(ing) to return.
len( # Will return the number of elements as a int type
max( # Will return the max element.
list( # Will return a list which the data container converts to.
tuple( # Will return a tuple which the data container converts to.
str( # Will return a str(ing) which the data container converts to.
set( # Will return a set which the data container converts to.
	box # The data container.
		) # Return.
sorted( # Will return a list sorted.
	box, # The data container.
		# Default is False.
		reverse=False # This is a bool while True is ascending order and False is descending order.
			) # Return a list sorted.

			

Sequence


seq_a # The sequence. Below will not change this seqence method.
	[
		3 # The begining index number (contained). Optional parameter is 0 as default.
			:
				0 # The end index number (not contained). Optional parameter is -1 as default.
					:
						-1 # The step. Positive number is positive order and negative number is reverse order. Optional parameter is 1 as default.
							] # Return the sequence sectioned.
	[2] # Return the element of the index number. The positive index number is positive order from left to right and the begining is 0, the negative index number is reverse order from right to left and the begining is -1.
	[False] # Equal to [0].
	[True] # Equal to [1].
	.copy() # Return a deep copy of the sequence.
seq_a # Below method will not change this sequence method.
	.center( # Will return a sequence in which the orginal sequence is center and filled character is on either hand, appoint the total lenth of the sequence.
		10, # The total lenth of the sequence.
			- # The character to fill.
	.index( # Will return the forward index number of the first one of this element in the sequence.
		"one" # The element to find.
	.count( # Will return the number of occurrences of an element in the sequence.
		"one" # The element to count.
				) # Return.

			

Function


def func_eg(): # Some functions may have no parameters.
	pass
func_eg(
	'key1'='value1',
		'key2'='value2'
			) # Call a function with multiple keyword arguments.
def func_a # The function name.
	(a, # The formal parameter.
			b="default", # Appoint the default value of the optional parameter.
				*c # The optional parameters must be placed after the required parameters.
					): # Define a function, you can set the default parameter value here.
		return x, y # End the function definition and return values which can be assigned to some identifiers.
x, y = func_a( # You can use multiple identifiers to receive multiple return values, and use one identifiers to return a tuple of multiple return values.
	1, # The 1st argument.
		2, # The 2ed arguement.
			c = 3 # Appoint the value of the parameter c.
				)
	pass # Do nothing.
def func_eg(
	*args, # A tuple is suplit to multiple positional parameters to accept parameters of variable length.
		**kwargs # A dict(ionary) is suplit to multiple keyword parameters to accept parameters of variable lenth.
			):
	pass

			

File Operation


open(
	'./text/example.txt', # Path of the file.
		'r', # Only-read mode.
		'w' # Write mode, which will delete orginal file and create a new file.
		'a' # Appending mode.
			encoding=UTF-8 # The encoding format.
				) # Return a file object.
file_eg.read(
	2 # The character count.
	# Default is the all characters.
		) # Return a str(ing) which composed by specified number of characters backward from the pointer in the file object.
file_eg.readline() # Return a str(ing) which composed by a line backward from the pointer in the file object.
file_eg.readlines() # Return a list which composed by all lines backward from the pointer in the file object.
file_eg # Below the method will change this file object.
	.flush() # Save the file.
	.close() # Save and close the file. It will remain occupied without closing the file.
with open(
	"text/example.txt", # Path of the file.
		"r", # The read-only mode.
			encoding="UTF-8" # The encoding format.
				) as file_eg: # The name of file object. Open and operate the file, and will close the file automatically after finished.
	file_eg.write("Hello") # Some operations.

			

Error


try: # Try some codes.
	pass
except  #
	NameError  # The exception appointed.
		as e # The exception object.
			: # If a an exception appointed occurs, run the following code.
	print("name is not defind")
	print(e) # Print the exception object including specific information.
except  #
	(NameError, ZeroDivisionError)  # The two or more exception appointed.
		as e: # If any exceptions appointed occurs, run the following code.
	pass

except: # If any exceptions occurs, don't print and run the following code.
except Exception: # If any exceptions occurs, don't print and run the following code.
	print("This is a bug.")

else: # If it has no exceptions, run the following code.
	pass
finally: # The following code will be run regardless whether exceptions.
	pass

			

Module and Package

A *.py file is a modual, a folder including multiple modual files and \_\_init\_\_.py file is a package.


import time # Import a module or package.
import time, turtle # Import two modules or packages simultaneously.
import mymodule # Import a custom module file or custom package folder in current directory.
import numpy as np # Import a module file or package and name to a alias.
from matplotlib import pyplot as plt # Import a module in a package, or a function in a module and name to a alias.
from time import sleep as sl # Import a module in a package, or a function in a module and name to a alias.
from time import * # Import all moduls in a package, or all functions in a module.
import mypackage.mymodule.myfunction # Import a function in a module in a package.
mypackage.mymodule.myfunction() # Call a function in a module in a package.
from mypackage import mymodule.myfunction # Import a function in a module in a package.
mymodule.myfunction() # Call a founction in a module in a package.
from mypackage.mymodule import myfunction
myfunction()
```
The interal variable in a module file.
```Python
__all__ = ['item1', 'item2'] # It only import functions in this list when using \* symbol to import.
if __name__ == "__main__": # The condition is true only when the code is not imported but is run directly.
	pass

			

Class and object


class Student: # Create a class.
	name = None # Define the default value of properties in the class.
	__term = 1 # Attributes starting with double underscores are private properties and can only be accessed when the class is being defined.
	def __init__( # Methods that begin and end with double underscores are built-in methods (magic methods). "__init__" is the constructor, which is automatically called and run when an object is created.
	# When a class is instantiated, the outer code block (within the "class" block but outside the method definition block) is run first, and then the "__init__" method definition block is run. If other ordinary methods are called, then the code blocks within those methods are run.
	# Within a class block but outside a method definition block, you cannot call properties and methods defined within the method definition block (including the "__init__" definition block). In other words, the outer level cannot call the inner level because the outer level runs before the inner level.
		self, # The first parameter in all method definitions must be self.
			defaultname, # Parameters that can be directly passed when creating an object.
				):
		self.name = defaultname # When calling a property of a class within its definition block, the .self prefix must be added.
		self.method_1 = lambda x, y: x*y # A lambda expression can be used to define a method within "__init__"
	method_2 = lambda self, a: a # A lambda expression can also be used to define a method outside of "__init__" and the first parameter must be self, otherwise it is treated as a function.
	def method_3(self, x, y): # Define methods using the def statement.
		return x*y
	# When defining properties or method within a method definition block, the "self." prefix is required.
	# You can define porperties and methods directly by name outside of a method definition block, but the first parameter of the method must be "self", otherwise it will be treated as a function.
	def __str__(self): # The output content by the "print" function.
		return f"The object of class \"Student\", name={self.name}, age={self.age}"
	def __lt__(
		self,
			other # The parameter must be "self, other".
				): # Return a bool value, which depends on below definition, without definition of this method it will report an error.
		return self.age < other.age # Return a bool value whether less than..
	def __le__(
		self, other # The parameter must be "self, other".
				): # Return a bool value, which depends on below definition, without definition of this method it will report an error.
		return self.age <= other.age # Return a bool value whether less than or equal.
	def __eq__(
		self,
			other # The parameter must be "self, other"
				): # Return a bool value, which depends on below definition, without definition of this method it will report an error.
		return self.age == other.age # Return a bool value whether equal.
	def __upterm(self): # Method staring with double underscores are private methods which can only be called when defining the class and can't be called outside the class (including within subclasses).
		self.__term = self.__term + 1 # Call a private property.
	def ordinary_upterm(self): # Define a ordinary method in a class.
		self.__upterm() # Call a private property.
Student(Jack) # Return a object created, this process is also called class instantiation.
student_eg.name = "Mike" # Assign a value to object property.
student_eg.ordinary_upterm() # Call a ordinary method of object.
print(student2) # Print the content in the method "__str__".
print(str(student2)) # Print the content in the method "__str__".
class Boy:
	gender = male
class BoyStudent(Student, Boy): # Inherited from two parent classes (Student, Boy), taking code from parent classed, in case of conflict, the parent class that was written first shall previal.
	age = 18 # Rewrite the property inherited from parent class.
	boy = OtherClass() # Define a new property, which can be a object based on other classes.
	def ordinary_upterm(self): # Rewirte the method inherited from parent class.
		super().ordinary_upterm() # Call the method of parent class.
		Student.ordinary_upterm(self) # Call the method of parent class appointed before rewritten.
		print(
			f"This is Term{
				self.__term # Call the private property inherited parent class.
					}"
						)
		print(
			f"I am {
				self.age # Call the oridinary property inherited parent class.
			} years old."
		)
def square(x):
	return x**2
def f_running(f, x): # A function can be a argument.
	return f(x)
f_running(square, x) # Make a function as a argument to pass to a function to recall.

			

Type Annotations

Equal to a comment to mark the type of value or the class of object for convinence.


data_eg: str  # Str(ing).
	= "abc"
data_eg: int  # Integer.
	= 10
data_eg: float  # Float.
	= 3.14
data_eg: bool  # Bool value.
	= True
data_eg: list  # List.
	= [1, 2, 3]
data: list[int]  # A List whose elements ar int(egers).
	= [1, 2, 3]
data: tuple =  # Tuple.
	("abc", 1, True)
data: tuple[str, int, bool]  # A tuple whose elements are str(ing), interger and bool value.
	= ("abc", 1, True)
data: set  # Set.
	= {1, 2, 3}
data: dict  # Dictionary.
	= {"abc": 123}
data: dict[str, int]  # A dict(ionary) whose element key is str(ing) and element value is int(eger).
	= {"abc": 123}
object_a: ClassA  # The class of object.
	= ClassA()
def func(data: str) -> int: # A function whose parameter is a str(ing) and return value is function.
	return eval(data)

			

Usual Internal Function


print( # Show some content on the screen.
	x, # The conetent which will displayed on the screen. This is a indefinite length parameter.
		end="" # The end of the content.
		# Optional parameter which default is "\n".
			) Return None.
input(
	x, # The content which will displayed on the screen. This is a indefinite length parameter.
		end="" # The end of the content.
		# Optional parameter which default is "\n".
			) # Return the content input by user
type(
	object # Variable or object.
		) # Return the value type of variable or class of object.
object_eg.__class__ # Return the class of object. This is equivalent to function "type".
range(
	1, # This int is a start.
	# Optional parameter which default is "0".
		5, # This int is a end.
			2 # This int is a step.
			# Optional parameter which default is "1".
				) # Return a list of int(eger) from start (including) to end (excluding).
round(
	a, # Number variables need to be rounded.
		n # The number of decimal places to retain.
		# Optional parameter which default is "0".
			) # Return a int/float as a rounding result.
chr(
	9801 # A number.
		) # Return a character corresponding to the Unicode encoding number.
ord(
	'A' # A character.
		) # Return the unicode encoding number of the character.
pow(
	4, # The power base.
		3, # The power index.
			2 # The divisor for finding the remainder after exponentiation.
			# No modulo operation.
				) # Return the modulo operation remainder after exponentiation.
int(
	'2' # The content to convert.
		) # Convert the parameter to int(eger), wich discarding the decimal part.
float(
	'1.2' # The content to convert.
		) # Return a float after converting the parameter.
dict(
	a='a',  # The key-value pair, as a indefinite length parameter.
	# Default is empty.
		b='b'
			) # Return a dict(ionary) after converting the content.
set(
	param_eg # A sequence.
	# Default is empty.
		) # Return a set after converting the content.
list(
	param_eg # A sequence.
	# Default is empty.
		) # Return a list after converting the content.
enumerate(
	iterator,  # An iterable object.
		2 # The positive index number of the starting position.
		# Default is "0".
			) # Return an enumerate object, like a list whose elements are tuple, whose 1st element is index and 2nd element is the element in original sequence.
zip(
	iterator_eg # One or multiple iterator, as a indefinite length parameter.
		) # Pack the elements from each iterator into tuples, and then combine them into a list and return. Such as zip((1, 2, 3), ('a', 'b', 'c')) is [(1, 'a'), (2, 'b'), (3, 'c')]
id(
	object_eg # An object.
		) # Return the ID.
map(
	function_eg,  # A function.
		iterable_eg # An iterable object.
			) # Return a list that generated by inserting elements of backward iterable object into the foreward function.
sum(
	sequence_eg, # A sequence.
		) # Return the sum of elements of the sequence.
reversed(
	sequence_eg # A sequence.
		) # Return an iterator after the sequence reversed.

			

Comprehension


[x**2 for x in range(10)] # Appoint a variable to iterator and substitute the variable into the expression to return a list.
list(map(lambda x: x**2, range(10))) # It's equivalent to above.
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] # Return a list whose elements are tuple. Nested iterators run loop statements from left to right. The selection statement determines the condition of the left loop statement.
{i for i in range(10)} # The set comprehension.
{i:j for i, j in zip(list_a, list_b)} # The dict(ionary) conprehension.
# The geneator comprehension is shown in the section "Generator".

			

Anonoymous Function


# The anonoymous function will return the function itself.
lambda x, y: x*y # Return a function.

			

Iterable, Sequence and Iterator


from collections.abc import Iterable
isinstance(
	object_eg, # An object to judge.
		Iterable # Judge whether iterable.
		Iterator # Judge whether iterator.
			) # Return a bool value.
iter(
	iterable_eg # An iterable.
		) # Return the iterator of iterable.
next(
	iterator_eg # An iterator.
		) # Return an object, which is equivalent to "__next__()" method.

			

Generator


def generator_eg(): # Define a generator function by "yeild" keyword.
	for i in range(1001):
		yeild i**2 # Each generated return value. Running will be paused as soon as a response is received.
def generator_eg(): # Define a generator function by generator comprehension.
	(i**2 for i in range(1001)) # The generator comprehension which is equivalent to above.
generator_eg # A generator function.
	() # Return a generator object.
for item in gen(): # Iterating over generagor objects.
	print(item)

			

Closure and Decorator


def function_eg():
	a = 1 # A closure environment which is called by inner "def" block.
	def g(): # The "outer" object.
		nonlocal a
		a += 1
		print(a) # The inner "def" block calls the object in the outer "def", it is a closure.
	return g # This generates the closure function and also returns the outer object used by the closure function.
function_eg().__closure__() # Return the closure environment.

			

A function whose parameters and return values are functinos.

Decorators are used to extend or modify the functionality of functions.


def decorator_eg(decorated_function): # Define a decorator function.
	def wrapper(*args, **kwargs): # Receives the parameters of the decorated function.
		print('decorator_eg is called') # Add some functions to decorated function.
		return decorated_function(*args, **kwargs) # Call the original function of decorated function.
	return wrapper # Return the decorated function after decorated.

new_function = decorator_eg(old_function) # Call the decorator to decorate a function.

@decorator_eg # Put a hat on the function definition statement to decorate below function.
def square(x): # The function is hated, which will be decorated after definition.
	return x**2

			

Context Manager


class Context(): # Define the class to which the context manager object belongs.
	def __enter__(self): # When the object instantiated from this class is used as context manager object, this method will be called at the begining of "with" statement.
		return self
	def __exit__(self): # When the object instantiated from this class is used as context manager object, this method will be called at the end of "with" statement.
		pass
with Context() as ctx: # Appoint the context manager.
	pass

			

Call Continuously

The parameters of function calling continuously.


def f():
	pass
	return f
f()()() # The example of continuous calling.
```
Index and slice calling continuously.
```Python
class A:
	def __getitem__(self, item): # This magic function is used to set index and slicing by "[]".
	pass
	return self
a = A()
a[][][] # The example of continuous calling.

			

The object method continuous call.


class A:
	def f(self):
		pass
		return self
a = A()
a.f().f().f() # The example of continuous calling.

			

Function and method calling continuously.


class A:
	def __call__(self, *args, **kwargs): # This magic method will set the object callable.
		pass
		return self
	def a(self):
		pass
		return self
a = A()
a().a().a().a() # The example of call.

			

The property of object calling continuously.


class A:
	@property # Decorate the method to a property.
	def a(self):
		pass
		return self
a = A()
a.a.a.a # The example of continuous calling.

			

Multiple properties continuous calling.


class A:
	def __getattr__(self, item): # This magic method is used to get the property calling.
		if item in ['b', 'c', 'd', 'e']
		pass
		return self
a = A()
a.b.c.d.e # The example of continuous calling.

			

Dynamically Generated Class


type( # Use the "type" function to create a dynamically generated class, as a object of "type" metaclass, whose parameters are default properties of type metaclass.
	'name_eg',  # This str(ing) is the name of class.
	(),  # This tuple is parent class inherited.
	{
		'attribute_eg': 'value_eg',  # The key-value pair composed by property name and property value.
		'method_eg': lambda: pass # The key-value pair composed by method name and method definition.
	}, # This dict(ionary) includes properties and methods.
) # Return a dynamically generated class (An object of meta class).
class_body = '''
def greeting(self):
	print('Hello world')
'''
class_dict = {}
exec(class_body, globals(), class_dict) # Convert a str(ing) to a dict(ionary) of properties and methods.

			

Metaclass and Metaprogramming


class M(type): # Define a metaclass statically, which is a subclass of the "type" root metaclass.
	pass
# Call the metacleass in the class definition statement.
class A(metaclass=M): # Define a class "A", whose metaclass is "M".
	pass
# Use a metaclass when dynamically defining a class.
M( # Define a class "A", which metaclass is "M".
	'A', # This str(ing) is the name of class defined dynamically.
		(),  # This tuple is parent classes.
			{} # This dict(ionary) includes properties and methods.
				) # Return a class defined dynamically.

			

Dynamically Generated Code

Write code to generate code, and run generated code.

The dynamically generated classe is a kind of dynamically generated code technology.


compile(
	'''
		print('Hello')
			''', # This str(ing) is runable code.
				'a.py' # The file name of runable code.
					'exec' # This is used to compile multiple-line code.
					'eval' # This is used to compile sigle expression.
					'single' # This is used to compile single-line interactive commands.
						) # Return the code object.
exec( # Ren the code object.
	object # The code object or str(ing).
		)
eval( # Recongnize a single-line str(ing) as python code to run it.
	'example = 1' # The single-line str(ing) to recongnze or code object.
		) # Return the return value after run.

			

Process, Thread and Coroutine

Syntactic Sugar

Syntactic sugar includes comprehension, simultaneous assignment, continous assignment, increment assignment, etc.


x, y = 1, 2 # Simultaneous assignment.
x, y = y, x # Exchage values of two variables.
x = y = 1 # Continous assignment.
x += 1 # Increment assignment.
x = 1 if True else 2 # The shorthand of selection statement and assignment statement.
eg = lambda a, b: a*b if a>b else a+b # The shorthand of selection statement and assignment statement for function.
m = [a, b][a > b] # It is equivalent to a selection statement, in which False is equivalent to "0" and True is equivalent to "1".
m = a < b and a or b # It is equivalent to a selection statement. The non-0 numer is equivalent to bool value True. Combining "and" and "or" can short-circuit some statements, preventing them from running.


import \ # Force a line break where a line break is not allowed. There should be no extra characters (including comments) after the forced newline backslash.
json,

a = 1; b = 2 # Use the ";" to merge two lines.

			

Pythonic


import this # Zen of Python

			

The "turtle" Internal Package


import turtle # Import the "turtle" package.
turtle.seup( # Set the size and position of the window.
	650,  # This number is the width.
		359,  # This number is the height.
			200,  # This number is the left edge margin.
				200 # This number is the top edge margin
					}
						)
turtle # Below method will change this object.
	.circle( # Paint a arc or circle.
		40,  # This number is the readius of the arc, in which positive number indicates turn left and negative number indecates backward movement.
			80 # This is the angle of arc angle.
	pencolor( # Set pen tip color.
		"purple" # This str(ing) or tuple is the pen tip color, which can be str(ing) or RGB tuple.
	seth( # Set the pen direction.
		40 # This number is the absolute angle pan direction.
	left( # Turn the pen to the left.
		20 # This number is the angle to turn left.
	right( # Turn the pen to the right.
		30 # This number is the angle to turn right.
	forward( # Pen forward or backward.
		100 # This number is distance forward, in which positive number indicates forward movement and negative number indicates backward movement.
		fd(-259) # Equal to "turtle.forward(-259)".
	.goto( # Send to pen tip to the position appointed.
		"100, 100" # This str(ing) is the absolute coordinate of position.
	.penup() # Pick up the pen.
	.pu() # Equal to "turtle.penup".
	.up() # Equal to "turtle.penup".
	.pendown() # Put down the pen.
	.pensize( # Set pen tip thickness.
		25 # This number is the thickness of the pen tip.
				) # Return None.
	done() # Exit the program and close the window.

			

The "random" Internal Package


import random # Import the "random" package.
random.seed( # Set the random seed.
	a # The random seed, in which default is current system time. The random numbers depend only on the random seed.
		)
random.random() # Return an float as decimal between 0 and 1.
random.randint(
	1,  # This number is the start.
		10 # This number is the end.
			) # Return an int between start and end.
random.sample(
	pop,  # A data container.
		10 # The number of elements.
			) # Randomly select a specified number of elements from the data container to form a list and return.

			

The "math" Internal Package


import math # Import the "math package导入math包

			

The "time" Internal Package


import time # Import the "time" package.
time.sleep( # Sleep some seconds.
	5 # The number of seconds.
		) # Return None.
time.time() # Return current UNIX timestamps.

			

The "datetime" Internal Package

Date and time


from typing import Union # Import "Union" module from "typing" package, which can set union type annotations.
data: list[ # The type annotation specifies the data type as a list.
	Union[str, int] # The union type annotation specifies elements in the list are str(ing) or int(eger).
		] = [1, "abc"]
data: dict[
	str,  # The union type annotation specifies keys in the dict(ionary) are str(ing).
		Union[ # The union type annotation specifies values in the dict(ionary) are str(ing) or inte(rger).
			str, 
				int
					]
						] = {'name': "Mike", 'age': 18}

			

The "json" Internal Package


import json # This package can convert between json string and python list or dict(ionary).
json.dump( # Write a dict(ionary) or a list whose elements are dic(tionary) to a json file.
	data,  # The dict(ionary) or a list whose elements are dic(tionary).
		file.json  # The json file object to write.
			) # Return None.
json.dumps(
	data,  # The diec(tionary) or list whose elements are diec(tionary) to convert.
		ensure_ascii=False # The indicates whether ASCII code conversation is used. The "True" will cause non-ASCII characters to be garbled characters.
		# Optional parameter and default is "ensure_ascii_True".
			) # Return the string after converted.
json.load( # Convert a json file object to a dict(ionary) or list.
	json_file # The json file object.
		) # Return a dict(ionary) or list whose elements are dict(ionary) after converted.
json.loads(
	json_str # A json str(ing).
		) # Return a dict(ionary) or list whose elements are dict(ionary) after converted.

			

Threading Internal Package


import threading # The package to use multipule theads package.
threading.Thread(
	group,  # Reserved parameters for future features, currently useless.
		target=sing,  # This is a function name to run.
			args,  # This is a tuple for function parameters.
				kwargs,  # This is a dictionary for function parameters.
					"name" # This str(ing)
						) # Return a thread object.
thread_obj.start() # Start the thread object.

			

The "inspect" Internal Package


import inspect
inspect.getsource(
	object_eg # An object.
		) # Return the definition source code of the object.

			

Other Interal Package

The "black" 3rd Package


pip install black # Install black.
black ./example.py # Format the source code.
python -m black ./example.py # This is equivalent to above.
black 
	-S  # Don't chage the str(ing) literal to double quotes.
	--skip-string-normalization # This is equivalent to above.
		./example.py # The file of source code.

			

The "pyinstaller" 3rd Package


pyinstaller 
	-onedir  # Package the source code to a runable binary files on a folder.
	-D  # This is equivalent to above.
	-onefile  # Package the source code to a single binary file.
	-F  # This is equivalent to above.
		--windowed  # The packaged file will not show CLI windows when running.
		--noconsolc  # This is equivalent to above.
		-w  # This is equivalent to above.
			example.py # The source code file.

			

Other 3rd Packages

nuitka
Package to binary runable file.
The "pygame" Package
Game development.
pyminifier3
Minifi source code.
The "selenium" 3rd Package
Web spider.
The "pyppeteer" 3rd Package
Spider.
The "rsa" 3rd Package
RSA encryption.
The "hashlib" 3rd Package
Hash function.
The "pyotp" 3rd Package
OTP.
The "base64" 3rd Package
Base64 encoding.
The "pillow" 3rd Package
Image process.
The "scikit" 3rd Package
Image process.
The "CoolProp" 3rd Package
Fluid properties calculating.
The "ctREFPROP" 3rd Package
Fluid properties calculating.
The "jieba" 3rd Package
Chinese word segmentation.
The "pyautogui" 3rd Package
Control the mouse.
The "tqdm" 3rd Package
Progress bar.