Professional Documents
Culture Documents
Python Basics
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their
respective holders.
Notice
The purchased products, services, and features are stipulated by the contract made between Huawei
and the customer. All or part of the products, services, and features described in this document may
not be within the purchase scope or the usage scope. Unless otherwise specified in the contract, all
statements, information, and recommendations in this document are provided "AS IS" without
warranties, guarantees or representations of any kind, either expressed or implied.
The information in this document is subject to change without notice. Every effort has been made
in the preparation of this document to ensure accuracy of the contents, but all statements,
information, and recommendations in this document do not constitute a warranty of any kind,
express or implied.
Website: https://e.huawei.com
Python Basics Page 1
Contents
1 Introduction to Python
Python is one of the most popular programming languages, and is the most widely used
programming language in the artificial intelligence (AI) field. Python 2 and Python 3 are
mainstream versions. Here, we will learn about Python 3.
1.1 Overview
Python is a universal advanced programming language. It is completely open-source. The
author of Python is Guido Van Rossum.
1.4.2 IDE
PyCharm: a development environment with extremely powerful and convenient functions
Eclipse: a development tool widely used in Java and Python
Jupyter Notebook: web-based interactive computing environment.
Python Basics Page 6
2 Basic Programming
a="python"; del(a)
range(start, stop, [step]): generates an iterative sequence (including the start position,
end position, and step).
range(0,20,4)
type(obj): type of the returned object.
type(print): generates builtin_function_or_method.
dir(obj): views the built-in methods and attributes of an object.
dir(print)
2.2.2 Number
Python 3 supports values of int, float, bool, and complex types.
Basic operations of the Number type are as follows:
Addition (+)
Subtraction (-)
Multiplication (x)
Division (/)
Modulo/Rounding (%, //)
Power (**)
If the operation is performed on numbers of different types (such as int and float), the
result type is the type with higher precision.
2.2.3 String
In Python, a string is a sequence with multiple characters. The number of characters
indicates the length of the string.
Python does not have a character data type. A single character is considered as a string
with length 1.
To declare a string, you only need to use single quotation marks ('...') or double
quotation marks ("...") to enclose the content. You can also use three consecutive
quotation marks ('''...''' or """...""").
The escape character (\) and the original string r can be used in the string.
Operator:
+: Two strings are concatenated. Example: a="hello";b="world" =>a+b= 'helloworld'.
*: A new string is obtained by multiplying a string by a number. Example: "a"*2=>"aa"
Format Description
%s String
Format Description
Symbol Description
m indicates the minimum total width of the display, and n indicates the
m.n
number of digits after the decimal point.
2.2.6 List
A list is a sequence in which elements can be of any data type and elements can be
added or deleted at any time.
In a list, elements are enclosed by a pair of square brackets and are separated by
commas (,). You can create a list in either of the following ways:
List = list(obj1, obj2,…)
List = [obj1, obj2, ….]
List comprehensions
Operator:
+: Combines lists, for example, the result of [1,2]+[2,3] is [1, 2, 2, 3].
x: Multiplies a list by a number to obtain a new list, for example, the result of [1,2] x 2 is
[1, 2, 1, 2].
Python Basics Page 11
2.2.8 Tuple
A tuple is a sequence in which elements can be of any data type.
Data stored in tuples is of higher security than that on lists.
Elements in a tuple are enclosed by a pair of parentheses and are separated by commas
(,). A tuple can be created in the following three ways:
Tuple = tuple(obj1, obj2, …)
Python Basics Page 12
2.2.9 Dictionary
Each element of the dictionary consists of a key and value. Therefore, the elements of the
dictionary are also called key-value pairs. A key is immutable and unique. If a dictionary
has duplicate keys, the value of a later key overwrites the value of the previous key.
When there is a large amount of data, the access speed of dictionary data is higher than
that of a list block.
Elements in a dictionary are enclosed by a pair of braces and are separated by commas
(,). Common methods of creating a dictionary are as follows:
Dict = {key:value,}
Dict = dict(key=value,)
Dict = dict([(key,value),])
Dictionary comprehensions
2.2.11 Set
Every element in a set is unique, and duplicate elements are deleted.
Elements in a set are enclosed by braces and are separated by commas (,). You can
create a set in the following ways:
Set = set()
Set = {obj1,obj2,…}
Logical operations:
Intersection set1 & set2: same elements in the two sets
Symmetric difference set1 ^ set2: elements which are in either of the sets and not in their
intersection
Union set1 | set2: all elements in the two sets with duplicate elements deleted
Difference set set1 - set 2: elements contained in set 1 but not contained in set 2.
2.2.14 Operator
Python has the following operators:
Arithmetical operator
Comparison operator: ==, !=, >, <, >=, <=
Assignment operator: =, +=, –=, /=, *=, **=, //=
Bitwise operator: &, |, ^
Logical operator: and, or, not
Membership operator: in, not in
Identity operator: is, is not
Python Basics Page 15
class class name (parent class): # class keyword to declare the class. Multiple
parent classes are supported. By default, the classes inherit from the object class.
’’’Class description document’’’
...Class body...
Access
Description
Mode
Open a file in read-only mode. The pointer will be placed at the beginning
r
of the file. This is the default mode.
Open a file in write-only mode. If the file already exists, the content in the
w
file will be overwritten. If the file does not exist, a new file will be created.
Open a file for appending new content to it. If the file already exists, the
file pointer is placed at the end of the file. New content will be written
a
after the existing content. If the file does not exist, a new file will be
created and content will be written to it.
Open a file for reading in binary mode. The pointer will be placed at the
rb
beginning of the file. This is the default mode.
Open a file for writing in binary mode. If the file already exists, the
wb content in the file will be overwritten. If the file does not exist, a new file
will be created.
Open a file for appending in binary mode. If the file already exists, the file
pointer is placed at the end of the file. New content will be written after
ab
the existing content. If the file does not exist, a new file will be created
and content will be written to it.
Open a file for reading and writing. The pointer will be placed at the
r+
beginning of the file.
Open a file for reading and writing. If the file already exists, the content in
w+ the file will be overwritten. If the file does not exist, a new file will be
created.
Open a file for reading and writing. If the file already exists, the file
pointer is placed at the end of the file. Content will be appended to the
a+
file. If the file does not exist, a new file will be created for reading and
writing.
Open a file for reading and writing in binary mode. The pointer will be
rb+
placed at the beginning of the file.
wb+ Open a file for reading and writing in binary mode. If the file already
Python Basics Page 22
Access
Description
Mode
exists, the content in the file will be overwritten. If the file does not exist, a
new file will be created.
Open a file for appending in binary mode. If the file already exists, the file
ab+ pointer is placed at the end of the file. If the file does not exist, a new file
will be created for reading and writing.
2.7.2 Exceptions
In most cases, there are two distinguishable kinds of errors: syntax errors and exceptions.
Syntax errors: Errors occur when you write the code and before you execute the code.
Exceptions: Exceptions occur when you attempt to execute the code. For example, an
exception occurs when a divisor is 0.
Common Python exceptions are as follows:
ZeroDivisionError: division or modulo by zero (all data types)
OSError: operating system error
SyntaxError: syntax error
IndentationError: indentation error
StopIteration: end of iteration
3 Advanced Programming
3.2 Multitasking
3.2.1 Multitasking
The operating system can run multiple programs at the same time.
Execution modes of multiple tasks:
Concurrency: Multiple tasks are executed alternately.
Parallel: Multiple tasks are executed at the same time.
Implementation of multiple tasks:
Python Basics Page 25
Thread
Process
Coroutine
3.2.2 Thread
A thread is the minimum execution unit of the operating system.
All threads in a process share global variables.
Because of the global interpreter lock (GIL), multithreading cannot be implemented in
Python.
GIL is a lock used for data integrity protection and status synchronization among threads.
3.2.4 Process
A process is the minimum resource allocation unit of the operating system.
A program has at least one process, and a process has at least one thread.
Data is shared among threads in the same process.
Each process has independent memory space.
subgroup
whose number
is num.
print(re.search("(\w
Returns a tuple
\w\w)-
groups(default=None) containing all ('abc', '123')
(\d\d\d)","abc-
subgroups.
123").groups())
Returns a res =
dictionary re.search("(?P<lamb
containing all >\w\w\w)-
named (?P<num>\d\d\d)"," {'lamb':'abc',
groupdict(default=None)
subgroups of abc-123") 'num': '123'}
the match,
keyed by the Print(str(res.groupdi
subgroup name. ct()))
res
The value is =re.search("abc","aB
re.i,re.IGNORECASE cxx",re.I) aBc
case insensitive.
print(res.group())
In this mode, ^
and $ match
the start and
end of the res =
target string re.search("^aB","aBc
re.M,re.MULTILINE xx",re.M) aB
respectively, but
not the start print(res.group())
and end of any
line within the
target string.
re2.
Matches any
res=re.search("b.b",
. character (except bob
"xxxbobxxx")
\n).
Matches a regular
res=
expression that
+ re.search("bob+","xxxxbo bobbbb
appears one or
bbbbob")
multiple times.
Matches a regular
expression that res=re.search("bob?","bob
? bob
appears zero or one bod")
time.
Matches a regular
res=re.search("bob{2}","b
{N} expression that bobb
obbbbod")
appears N times.
Matches a regular
expression that res=re.search("bob{2,3}","
{M,N} bobbb
appears M to N bobbbbod")
times.
3.6.2 Generators
A generator is a special kind of iterator.
A generator can return one or more values each time it iterates, and it can record the
current state.
Generator creation methods:
Use the yield keyword.
Use the generator expression (derivation).
Python Basics Page 31
The execution of a program suspends when the generator statement is encountered. The
execution resumes only when the next() or send() method is used.
When the send() method is used, data is transferred.
3.6.3 Closures
A closure is an entity consisting of functions and their associated reference environments.
In Python, if an internal function references a variable in an external scope (not a global
scope), the internal function is considered as a closure.
You cannot modify a local variable in an external scope in a closure.
Simple implementation of a closure:
def func():
n=1
def inner():
return n+1
return inner
3.6.4 Decorators
A decorator is essentially a Python function that adds new functions to the code without
changing the code structure.
The working process of a decorator is as follows: Transfer the function to be decorated as
a parameter to the decorator function (function with the same name), and return the
decorated function.
Decorator is an application of closures.
Usage of decorators:
@ Decorator function
def func():
pass
3.7 Extension
3.7.1 JSON
JavaScript Object Notation (JSON) is a lightweight data exchange format that is easy to
read and write. Its form is similar to that of a dictionary in Python.
To use JSON functions in Python, you need to import the JSON library using the import
json statement.
json.dumps: Encodes a Python object into a JSON string.
json.loads: Decodes an encoded JSON string into a Python object.
Python Basics Page 32
3.7.2 Metaclasses
In Python, a class itself is an object, and the class that creates such an object is called a
metaclass.
You can use type() to create metaclasses in Python.
type(name, base, dict), in which name indicates the class name, base indicates the tuple
of classes from which the current class derives (which is used in inheritance scenarios and
can be left empty), and dict indicates the dictionary that contains attributes, including
names and values.
Metaclasses of all classes are created using type().
Metaclasses are used to create APIs.
Everything in Python is an object, either an instance of a class or an instance of a
metaclass, except the type class. The type class is its own metaclass.
4 Quiz