1. Type
1. Variables have no type, data have type
Example: num = 1 --->num has no type, 1 is type int
2. Format output
= "Zhang San"
age = 18
print("I am" + name + ", this year" + age + "year") #This will cause an error. When splicing with +, positive numbers and strings cannot be spliced
3. Placeholder
%c Characters
%s string
%d There is a matching decimal integer
%uUnsigned decimal integer
%o octal integer
%x hexadecimal integer (small letter 0x)
%X hexadecimal integer (capsular letter 0X)
%f floating point number
%e scientific notation method (lowercase 'e')
%E Scientific Nominal Method (lowercase 'E')
Abbreviation of %g%f and %e
Abbreviation of %G%f and %E
3. Operators
1.
/Dividget result is a floating point number
//Gram dividing is not rounding, it is the first integer smaller than the result
% take balance
**index
2. Compound operator (when performing a conforming operation, no matter what the situation is, first calculate the equation on the right of the equal sign)
+=
-=
*=
/=
**=
//=
3. Common data type conversion (input() inputs string)
int(x) converts x into an integer
float(x) converts x into a floating point number
complex(real,[,imag]) creates a plural number, real is the real part, and image is the imag part
str(x) converts x into a string
repr(x) converts x into an expression string
eval(str) is used to calculate valid python expressions in strings and return an object
tuple(s) converts sequence s into a tuple
list(s) converts sequence s into a list
chr(x) converts an integer into a Unicode character
ord(x) converts a character into an ASCII integer value
hex(x) converts an integer into a hex string
4. Slice
name = "abcdef"
print(name[0:3]) takes the subscript 0-2 characters
print(name[0:5]) takes the subscript 0-4 characters
print(name[3:5]) takes the subscript 3-4 characters
print(name[2:]) takes the character after subscript 2 to the last
print(name[1:-1]) takes the character from the beginning to the last second character from the subscript 1
5. Common operations of strings
find(str, 0, len(mystr)) Find whether the str character appears in the string, starting from the subscript of 0 to the end; if it is not found, print -1
index(str, 0, len(mystr)) is the same as the find() method, except that if str is not in mystr, an exception will be reported.
count() returns the number of times str appears between start and end in mystr
replace() replaces str1 in mystr with str2. If count is specified, the replacement will not exceed count times.
(str,2) Slice mystr with str as the delimiter, 2 means to split only a few strings
capitalize capitalizes the first character of the string
title capitalizes the first letter of each word in the string
startswith checks whether the string starts with "str", and then returns True
endswith checks whether the string ends with "str", and then returns True
lower converts all uppercase characters into lowercase
upper Convert all lowercases in characters to uppercase
ljust returns a new string with left alignment of the original string and fills it with spaces to the remaining length
rjust returns a new string with the right alignment of the original string and fills it with spaces to the remaining length
center returns a new string centered and filled with spaces to length width
lstrip deletes the whitespace character on the left side of str
rstrip deletes the whitespace character on the left side of str
strip deletes whitespace characters at both ends of mystr string
rfind is almost the same as find
rindex is similar to index(), but starts from the right.
partition divide mystr into three parts by str, before str, after str
rpartition is similar to the partition() function, but starts from the right.
splitlines are separated by rows and return a list containing each row as elements.
isalpha Returns True if all mystr characters are letters, otherwise returns False
isdigit Returns True if mystr only contains numbers or False if otherwise.
isalnum Returns True if all mystr characters are letters or numbers, otherwise returns False
isspace returns True if only spaces are included in mystr, otherwise False.
Each string in joinmystr is inserted after the str to form a new string
6. Common operations of lists (lists are ordered, repetitive and mutable)
Add action:
list_1.append("asd") is added directly to the last
list_1.extend([1,2]) adds elements from another collection to the list one by one
list_1,insert(index,obj)index means to add to the specified subscript, obj means to add content
Change the operation:
list_1[1] is modified according to the corresponding position
check:
in(exist), if there is, the result is true, otherwise it is false
not in (not exist), if not, then the result is true, otherwise false
Index and count are used the same as in strings. ('a',1,4) Find the location where a appears according to index 1 to index 4 (this position is still the index of the principle)
Delete operation:
del: Delete according to the subscript
pop: Delete the last element
remove: Delete according to the value of the element
Sort reverse
sort is to arrange the list in a specific order. reverse=True can be changed to reverse order, from large to small.
reverse is to reverse the list
7: Tuple (the elements of the tuple cannot be modified)
Index and count are used the same as strings and lists
8: Dictionary (unordered mutable) Only immutable data types can be used as keys for dictionaries
If you access a non-existent key value, an error will be reported.
When we are not sure whether a key exists in the dictionary and want to get its value, we can use the get method and set the default value.
Add action:
1. Accessing non-existent elements based on the index will cause an error
2. If this "key" is in the dictionary and does not exist when using the variable name ['key'] = data, then this element will be added.
demo: Add new elements
Delete operation:
del
del info["name"]
clear() Clear the entire dictionary, but the dictionary itself still exists
len(dic) measures the number of key-value pairs in the dictionary
Return a list containing all KEYs in the dictionary
Returns a list containing all values of the dictionary
Returns a list of all (key, value) ancestors
dic.has_keydict.has_key(key) Returns True if key is in the dictionary, otherwise returns False
Iterate through the elements of the dictionary
dict = {"name":"zhangsan","sex":"nan"}
for item in ()
print item
>>('name','zhangsan')
>>('sex','nan')
Iterate through all key-value pairs
dict = {"name":"zhangsan","sex":"nan"}
for k,v in ()
print (k,v)
>>name,zhangsan
>>sex,nan
Implement index traversal with subscripts
>>> chars = ['a', 'b', 'c', 'd']
>>> for i, chr in enumerate(chars):
... print i, chr
...
0 a
1 b
2 c
3 d
cmp? Only in python
cmp(item1, item2) compares two values
About Quote:
Use 1: Immutable type, modify formal parameters, and do not affect actual parameters
Use 2: Change the actual parameter by modifying the variable type as the actual parameter
Use 3: When a mutable type is used as a real parameter, re-copy the formal parameters in the function
Result: The variable type is used as an actual parameter. If it is a formal parameter, modifying the formal parameter will not affect the actual parameter.
Some summary about Python
I hope that in the future, I can study and summarize while learning Python, and summarize my previous studies first, and then I will continue to summarize and update.
Why choose Python
Classmates often ask me why I chose Python. I like this language very much because it is simple and flexible, easy to learn, easy to read, portable and powerful.
advanced
It can be said that we will reach a new level with the emergence of each generation of programming languages. From assembly language to C Pascal, with the birth of C language, modern compiled languages such as C++ and Java were produced. Later, there were powerful interpreted scripting languages Python and Perl that can make system calls...
For example, there are some advanced data structures in Python. Lists and dictionaries are built into the language itself and can be used directly. These important building units are provided in the core language, which can shorten the development time and code amount and produce better readable code.
Object-oriented
Python is object-oriented programming
Memory Manager
The biggest disadvantage of C or C++ is that memory management is the responsibility of the developers. So even for an application that rarely accesses, modifys, and manages memory, programmers must perform these duties beyond performing basic tasks. These unnecessary burdens and responsibilities imposed on developers often distract themselves.
In Python, since memory management is the responsibility of the Python interpreter, developers can be freed from memory transactions, focus on the most direct goals, and only focus on developing the primary applications in the plan. This will make fewer errors, more robust programs, and shorter development cycles.
Explanatory and Compilation
Python is an interpreted language, which means there is no compilation process during development. Generally speaking, because it is not running in local machine code, purely interpreted languages usually run slower than compiled languages. However, similar to Java, Python is actually compiled bytes, and the result is that it can generate an intermediate form that is similar to machine language. This not only improves Python's performance, but also allows it to maintain the advantages of interpreted languages.
Why is Python running slower than C?
Because every simple operation of dynamic languages such as Python requires a large number of instructions to complete. Python is a dynamic language, and variables are just references to objects. For example, for a simple operation: a+b, in C, only one machine instruction ADD is needed. For Python, variables a and b have no types themselves, and their values have types, so you need to judge the type before adding, then read the numerical value, add it, generate a new object, store the operation result, return the object, and of course, memory overflow and other issues may also be considered.
Python Basics
Data Type
Data types in python can be divided into: strings, boolean types, integers, floating-point numbers, numbers, lists, tuples, dictionaries and dates.
String
Immutable objects, single quotes can be used, double quotes can be extended to represent a single line string, three quotes can be used to represent a multi-line string, and single quotes and double quotes can be used freely in three quotes.
ASCII code
What makes strings special is the encoding problem. We know that computers were invented by Americans. Initially, only 127 letters were encoded into the computer, including upper and lower case letters, numbers and some symbols. This encoding table is called the ASCII code table.
Unicode
It is obviously not enough to deal with a Chinese language, and it cannot conflict with ASCII code, so China has formulated the GB2312 code. There are many languages all over the world. In multi-language mixed text, there will be garbled code when displayed. Therefore, Unicode came into being. It unifies all languages into one set of encodings, so there will be no garbled code problem. ASCII code represents a character with one byte, while Unicode represents a character with two bytes. A string represented by Unicode is represented by u'...'.
UTF-8
What does "#coding:utf-8" often written at the beginning of a .py file mean? We know that Unicode encoding has twice as much storage space than ASCII encoding, which is very unprofitable in storage and transmission. If the text written is all in English, using Unicode encoding is a waste. So UTF-8 encoding appeared. UTF-8 encoding encodes a Unicode character into 1-6 bytes according to different numerical sizes, and ASCII code can be regarded as part of UTF-8.
Encoding and decoding
In Python 2.7, the coded string given by the operating system will receive the string in the format. The default format is different from the format used, and various errors will occur.
Solution:
1. Know the encoding format used by the system
2. Decode the obtained page in system format first, and then encode it into utf8 format
3.Use uft8 encoding in your script
4. After the processing is finished, decode your string utf8 first, and then encode the system format.
In Python, decode() and encode() are usually used for decoding and encoding.
Boolean type
A boolean value has only two values: True and Flase.
Integer
Includes integers and negative integers.
Floating point number
It is decimals. Integers and floating-point numbers are stored differently in the computer. Integer operations are always accurate. Floating-point operations may have rounding errors.
List
List is a variable ordered table, a built-in data type in Python, which can add, delete, and replace elements in it at any time.
A list in Python is an iterator. We know that Python is written in C. So what is the internal implementation of list? Lists in Python are implemented based on PyListObject, which is a variable-length object that maintains the address of the list internally and performs memory management and other functions to implement list functions.
Tuple Tuple
Another ordered table other than tuples is called tuple tuple, but once tuple is initialized, it cannot be modified. When defined, the elements of the tuple are determined. Why introduce tuple? Because tuple is immutable, the code is safer. If you can use tuple instead of list, try to use tuple.
Since tuples are immutable, modifying elements is illegal, but it can be combined by joining and combining elements, such as: tuple3 = tuple1 + tuple2.
Use the del statement to delete the entire tuple.
Dictionary Dict
Python has built-in dictionary, which uses key-value storage, and has extremely fast search speed. Compared with list, the search speed is much higher.
Why is dict search so fast? Because the implementation principle of dict is the same as looking up dictionary. Suppose the dictionary contains 10,000 Chinese characters, we need to search for a certain character. One way is to turn the dictionary back from the first page until we find the word we want. This method is to find elements in the list. The larger the list, the slower the search. The second method is to first look up the page number corresponding to this character in the index table of the dictionary (such as the radical table), then turn directly to the page and find the character. No matter which character you look for, this search speed is very fast and will not slow down as the dictionary size increases.
The initialization of the dict is as follows:
a = {}
a['A'] = 1
Difference between Dict and List: Dict's search speed and insertion speed are extremely fast and will not increase with the increase of key; however, dict will occupy a lot of memory and waste a lot of memory.
Dict is an immutable object, because the key is used to calculate the storage location of the value. In order to ensure the correctness of the result, the object as the key cannot be changed, immutable objects such as strings and integers can be used as the key in the dict.
Combined with Set
set is similar to dict, and is also a set of keys, but the difference is that there are no duplicate keys in set.
Variable and immutable
To sum up, immutable objects in Python include: strings, integers, and tuples; mutable objects include: lists, collections, and dictionaries.
For mutable objects, such as list, the content inside the list will change, while for immutable objects, such as str, use the replace() method, although the value can be changed, the value of the variable will not change. Why?
for example:
#coding:utf-8 a = 'abc' b = ('a','A') print b print a
a is a variable, and 'abc' is a string object. Why is the value of a still 'abc' after executing the above code? It is because a itself is a variable, and the object pointed to is 'abc'. The call method replace is used on the string object 'abc', but the content of 'abc' is not changed. It just creates a new object and assigns it to the b variable.
For immutable objects, calling any method of its own will not change the content of the object itself. These methods will create a new object and return it, ensuring that the immutable object itself is never mutable.
Passing value or passing reference
An interesting question that Python encounters when passing parameters is: Is the function's argument passing through value or reference?
For immutable objects as function parameters, they are equivalent to the value passing of C language;
For mutable objects as function parameters, it is equivalent to reference transfer in C language.
Advanced Features
Iterator
What is iterator in Python?
An iterator is a way to access the elements of a collection. The object of the iterator starts from the first element of the collection and ends until all elements are accessed. The iterator can only move forward but not backward.
For traversing data structures (tuple, lists) that support random access, iterators have no advantage over for loops because the iterators lose their index values. But for data structures that cannot be accessed randomly, iterators are the only way to access elements.
The iterator does not require that all elements in the entire iteration process be prepared in advance. The iterator only calculates the element when it iterates to an element. The iterator only calculates the element when it iterates to an element. Before or after this, the element may not exist or be destroyed. This feature makes the iterator particularly suitable for traversing some huge or infinite sets.
There are two basic methods in the iterator:
Next method: Return the next element of the iterator
__iter__ method: Returns the iterator object itself.
Generator
Functions with yield are called generators in Python. yield is to turn the function into a generator. When using yield during function execution, it is like using yield to interrupt the execution multiple times. Each interrupt will return the current iteration value through yield.
When the data volume is large, it is more efficient to use the generator.
Decorators
A function is an object, and a function object can also be assigned to a variable, so the function can also be called through a variable. The way to dynamically add functionality during code runs is called a decorator. Use Python's @ syntax to place the decorator at the function definition.
Metaclass
Classes are code snippets used to describe how to generate an object. In Python, a class is also an object. As long as the class keyword is used, the Python interpreter will create an object when executing it. This object itself has the ability to create an object, so it is a class, but it is still an object itself. Therefore, the following operations can be implemented: it can be assigned to a variable, it can be copied, it can be added to it, and it can be passed as a function parameter.
This is also the biggest difference between dynamic languages and static languages. The definitions of functions and classes are not defined at compile time, but are dynamically created at runtime. That is, in Python, classes can be created dynamically, and classes are also objects. This is what Python does behind the scenes when using the keyword class. These are all implemented through metaclasses.
So what exactly is metaclass?
Metaclasses are used to create classes. Creating classes is to create instance objects of the class, but we know that classes are objects, and metaclasses are used to create these classes (objects), so metaclasses are classes of classes.
Metaclasses are things that create objects like classes. Metaclasses can be called class factories.
The main purpose of metaclasses is to create APIs.
Closure
What are closures in Python?
If a variable in an external scope is referenced in an internal function, the internal function is considered a closure. In Python, we call a function A, and this function A returns a function B to you, and the returned function B is called a closure.
A decorator is a closure.