Follow 👆 the official account and reply 'python' to receive a beginner's tutorial! Source from the internet, please delete if infringed.
1. Variables have no type, data has type
Example: num = 1 —-> num has no type, 1 is of type int
2. Formatted Output
2. name = “Zhang San”
age = 18
print(“I am ” + name + “, this year I am ” + age + ” years old”) # This will report an error, using + to concatenate, numbers and strings cannot be concatenated
3. Placeholders
%c character %s string %d decimal integer %u unsigned decimal integer %o octal integer %x hexadecimal integer (lowercase 0x) %X hexadecimal integer (uppercase 0X) %f floating point %e scientific notation (lowercase ‘e’) %E scientific notation (uppercase ‘E’) %g shorthand for %f and %e %G shorthand for %f and %E
3. Operators
1.
/ Division results in a floating point number
// Floor division not rounding, takes the first integer less than the result
% Modulus
** Exponentiation
2. Compound assignment operators (when performing compound operations, regardless of the situation, the right side of the equation is calculated first)
+= -= *= /= **= //=
3. Common data type conversions (input() inputs as strings)
int(x) converts x to an integer float(x) converts x to a floating point complex(real,[,imag]) creates a complex number, real is the real part, imag is the imaginary part str(x) converts x to a string repr(x) converts x to an expression string eval(str) used to calculate valid python expressions in a string and return an object tuple(s) converts sequence s to a tuple list(s) converts sequence s to a list chr(x) converts an integer to a Unicode character ord(x) converts a character to an ASCII integer value hex(x) converts an integer to a hexadecimal string
4. Slicing
name = “abcdef” print(name[0:3]) takes characters from index 0-2 print(name[0:5]) takes characters from index 0-4 print(name[3:5]) takes characters from index 3-4 print(name[2:]) takes characters from index 2 to the end print(name[1:-1]) takes characters from index 1 to the second last character
5. Common string operations
find(str, 0, len(mystr)) checks if str appears in mystr starting from index 0; prints -1 if not found index(str, 0, len(mystr)) similar to find() but raises an exception if str is not in mystr .count() returns the number of occurrences of str between start and end in mystr .replace() replaces str1 in mystr with str2, if count specified, replaces no more than count times. mystr.split(str, 2) slices mystr with str as the delimiter, 2 means only split a few strings capitalize capitalizes the first character of the string title capitalizes the first letter of each word in the string startswith checks if the string starts with “str”, returns True if it does endswith checks if the string ends with “str”, returns True if it does lower converts all uppercase characters in the string to lowercase upper converts all lowercase characters in the string to uppercase ljust returns a new string left-aligned with the original string, padded with spaces to the remaining length rjust returns a new string right-aligned with the original string, padded with spaces to the remaining length center returns a new string centered with the original string, padded with spaces to length width lstrip removes whitespace characters from the left side of str rstrip removes whitespace characters from the right side of str strip removes whitespace characters from both ends of mystr rfind finds from the right similar to find rindex similar to index() but starts from the right .partition splits mystr into three parts using str, before str, str, and after str .rpartition similar to partition() but starts from the right .splitlines splits by line, returns a list with each line as an element .isalpha returns True if all characters in mystr are letters, otherwise returns False .isdigit returns True if mystr contains only digits, otherwise returns False .isalnum returns True if all characters in mystr are letters or digits, otherwise returns False .isspace returns True if mystr contains only spaces, otherwise returns False .join inserts str after each string in mystr to form a new string
6. Common operations on lists (lists are ordered, can be repeated, and mutable)
Add operations:
list_1.append(“asd”) directly adds to the end list_1.extend([1,2]) adds elements from another collection to the list one by one list_1.insert(index, obj) index indicates where to add, obj represents the content to be added
Modify operations:
list_1[1] modifies according to the corresponding position
Search:
in (exists), if exists then the result is true, otherwise false not in (does not exist), if does not exist then the result is true, otherwise false index and count have the same usage as in strings a.index(‘a’,1,4) searches for the position of a in the range of index 1 to index 4 (this position is still the original index)
Delete operations:
del: deletes by index pop: deletes the last element remove: deletes by value
Sorting: sort reverse
sort arranges the list in a specific order, parameter reverse=True can change to reverse order, from large to small, reverse is to reverse the list
7. Tuples (tuple elements cannot be modified)
index and count have the same usage as in strings and lists
8. Dictionaries (unordered and mutable) only immutable data types can be used as dictionary keys
Accessing a non-existent key will raise an error,
When we are unsure if a key exists in the dictionary and want to get its value, we can use the get method, and also set a default value
Add operations:
1. Accessing a non-existent element by index will raise an error
2. If using variable_name[‘key’] = data, if this “key” does not exist in the dictionary, it will add this element
demo: adding a new element
Delete operations: del del info[“name”] clear() clears the entire dictionary, but the dictionary itself still exists len(dic) measures the number of key-value pairs in the dictionary dic.keys returns a list containing all keys in the dictionary dic.values returns a list containing all values in the dictionary dic.items returns a list containing all (key, value) tuples in the dictionary dic.has_key dict.has_key(key) returns True if key is in the dictionary, otherwise returns False
Traversing dictionary elements
dict = {“name”:”zhangsan”,”sex”:”nan”} for item in dict.items() print item>>(‘name’,’zhangsan’)>>(‘sex’,’nan’)
Traversing all key-value pairs
dict = {“name”:”zhangsan”,”sex”:”nan”} for k, v in dict.items() print (k, v)>>name,zhangsan>>sex,nan
Implementing indexed traversal
>>> chars = [‘a’, ‘b’, ‘c’, ‘d’]>>> for i, chr in enumerate(chars):… print i, chr…0 a1 b2 c3 dcmp? only in Python
cmp(item1, item2) compares two values
About references:
Usage 1: immutable types, modifying parameters does not affect actual parameters Usage 2: mutable types as actual parameters modifying will change actual parameters Usage 3: when using mutable types as actual parameters, reassigning in the function to parameters Result: mutable types as actual parameters, if reassigned to parameters, modifying parameters does not affect actual parameters
Summary of Python I hope to summarize while learning Python in the future, starting with my previous learning, and continuously summarizing and updating.
Why Choose Python Many students often ask me why I choose Python. I really like this language because of its simplicity and flexibility, ease of learning, readability, portability, and powerful functionality.
Advanced
It can be said that with the emergence of each generation of programming languages, we reach a new height. From assembly language to C, Pascal, etc., with the birth of C language, modern compiled languages like C++, Java emerged, followed by powerful interpreted scripting languages like Python and Perl… For example, Python has some advanced data structures, lists and dictionaries are built into the language and can be used directly, providing these important building blocks in the core language can shorten development time and code volume, resulting in better readability of code.
Object-Oriented
Python is an object-oriented programming language
Memory Manager
The biggest drawback of C or C++ is that memory management is the responsibility of the developer. Therefore, even for an application that rarely accesses, modifies, and manages memory, programmers must perform these duties in addition to executing basic tasks. These unnecessary burdens and responsibilities placed on developers often distract them. In Python, since memory management is handled by the Python interpreter, developers can be freed from memory transactions and focus entirely on the direct goal, solely dedicated to the primary applications in the development plan. This leads to fewer errors, more robust programs, and shorter development cycles.
Interpreted and Compiled
Python is an interpreted language, which means that the compilation step is eliminated during development. Generally speaking, since it does not run in native machine code, pure interpreted languages usually run slower than compiled languages. However, similar to Java, Python is actually byte-compiled, resulting in a form of intermediate language that is close to machine language. This not only improves Python’s performance but also retains the advantages of an interpreted language.
Why Python runs slower than C language
Because dynamic languages like Python require a large number of instructions to complete each simple operation. Python is a dynamic language, where variables are just references to objects. For a simple operation: a+b, in C language, only one machine instruction ADD is needed, while in Python, variables a and b have no types themselves, but their values have types. Therefore, before adding, the type must be checked, then the value is read, added, a new object is created, the result is stored, and the object is returned. Of course, memory overflow and other issues may also be considered.
Python BasicsData Types
Data types in Python can be divided into: strings, boolean types, integers, floating points, numbers, lists, tuples, dictionaries, and dates.
Strings
Immutable objects, can be enclosed in single quotes, double quotes for single-line strings, and triple quotes for multi-line strings, allowing the use of single and double quotes freely.
ASCII Code
Strings are special due to encoding issues. We know that computers were invented by Americans, and initially, only 127 letters were encoded in computers, including uppercase and lowercase letters, numbers, and some symbols. This encoding table is called the ASCII code table.
Unicode
To handle Chinese characters, one byte is obviously not enough, and it cannot conflict with ASCII code. Therefore, China formulated the GB2312 encoding. There are many languages worldwide, and in mixed-language texts, there will definitely be garbled characters. Therefore, Unicode was born, unifying all languages into one encoding system to avoid garbled characters. ASCII uses one byte to represent one character, while Unicode uses two bytes to represent one character. Strings represented in Unicode are denoted as u’…’.
UTF-8
What does the “#coding:utf-8” written at the beginning of .py files mean? We know that Unicode encoding occupies twice the storage space of ASCII encoding, which is very inefficient for storage and transmission if the text written is all in English. Therefore, UTF-8 encoding emerged, which encodes a Unicode character into 1-6 bytes depending on its numerical size, and can consider ASCII as part of UTF-8.
Encoding and Decoding
In Python 2.7, the encoding of the string given by the operating system is the format it receives. If the default format is different from the format used, various errors will occur. Solutions: 1. Know the encoding format used by the system 2. Decode the obtained page using the system format, then encode it into utf8 format 3. Your script uses utf8 encoding uniformly 4. After processing, first decode your string in utf8, then encode it in 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 False
Integer
Includes positive and negative integers.
Floating Point
Is a decimal. The storage of integers and floating points in computers is different. The operation of integers is always accurate, while floating-point operations may have rounding errors.
List
A list is a mutable ordered table, which is a built-in data type in Python, allowing elements to be added, deleted, or replaced at any time. Lists in Python are iterators. Since Python is written in C, how is the internal implementation of list done? Lists in Python are implemented based on PyListObject, which is a variable-length object that maintains the address of the list internally and manages memory to implement list functionality.
Tuple
Another ordered table other than lists is called a tuple, but once a tuple is initialized, it cannot be modified. When defining, the elements of the tuple are determined. Why introduce tuples? Because tuples are immutable, the code is safer. If a tuple can replace a list, it is better to use a tuple. Since tuples are immutable, modifying elements is illegal, but can be combined by connecting elements, for example: tuple3 = tuple1 + tuple2. The del statement can delete the entire tuple.
Dictionary
Python has built-in dictionaries, using key-value storage, with extremely fast lookup speeds. Compared to lists, the lookup speed is much higher. Why is the lookup speed of dict so fast? Because the implementation principle of dict is the same as looking up words in a dictionary. Suppose the dictionary contains 10,000 Chinese characters, and we want to find a certain character. One method is to flip through the dictionary from the first page until we find the character we want. This method is how to find elements in a list; the larger the list, the slower the lookup. The second method is to first check the index table of the dictionary (like the radical table) for the page number corresponding to the character, and then directly flip to that page to find the character. No matter which character is found, this lookup speed is very fast and will not slow down as the size of the dictionary increases. The initialization of dict is as follows:
a = {} a[‘A’] = 1 The difference between Dict and List: The lookup and insertion speed of Dict is extremely fast and does not increase with the increase of keys; however, dict occupies a lot of memory, leading to more memory waste. Dict is an immutable object because the key is used to calculate the storage location of the value, to ensure the correctness of the result, the object used as a key cannot change. Immutable objects like strings and integers can be used as keys in dict.
Combining with Set
Set is similar to dict, also a collection of keys, but in set, there are no duplicate keys.
Mutable and Immutable
In summary, immutable objects in Python include: strings, integers, tuples; mutable objects include: lists, sets, dictionaries. For mutable objects, such as lists, the contents of the list will change when performing operations on the list, while for immutable objects, such as strings, using the replace() method can change the value, but the value of the variable will not change. Why? For example:
1 2 3 4 5 6 |
|
a is a variable, while ‘abc’ is the string object. Why does the value of a remain ‘abc’ after executing the above code? Because a itself is a variable pointing to the object ‘abc’. Calling the method replace acts on the string object ‘abc’, but does not change the content of ‘abc’, it only creates a new object and assigns it to variable b. For immutable objects, calling any method on itself does not change the content of the object. These methods create new objects and return, ensuring that immutable objects remain immutable.
Pass by Value or Reference
An interesting question encountered by Python during parameter passing is: Is function parameter passing by value or by reference? For immutable objects as function parameters, it is equivalent to value passing in C-style languages; for mutable objects as function parameters, it is equivalent to reference passing in C-style languages.
Advanced FeaturesIterators
What are iterators in Python? An iterator is a way to access elements of a collection, starting from the first element of the collection and accessing until all elements are finished. Iterators can only move forward and cannot move backward. For traversing data structures that support random access (tuples, lists), iterators have no advantage over for loops because iterators lose their index values. However, for data structures that cannot be accessed randomly, iterators are the only way to access elements. Iterators do not require preparing all elements in the entire iteration process in advance; they only calculate an element when iterating to that element. This feature makes iterators particularly suitable for traversing large or infinite collections. There are two basic methods in iterators: the next method: returns the next element of the iterator __iter__ method: returns the iterator object itself.
Generators
Functions with yield in Python are called generators. Yield turns the function into a generator, and using yield during function execution interrupts the execution multiple times, each interruption returns the current iteration value. When the data volume is large, using generators is more efficient.
Decorators
A function is an object, and function objects can also be assigned to variables, so the function can be called through the variable. The method of dynamically adding functionality during code execution is called a decorator. Using Python’s @ syntax, place the decorator at the function definition.
Metaclasses
Classes are code segments used to describe how to generate an object. In Python, classes are also objects. As soon as the Python interpreter executes the class keyword, it creates an object. This object itself has the ability to create objects, so it is a class, but it is also an object. Therefore, the following operations can be performed: it can be assigned to a variable, copied, have attributes added, and passed as function parameters. 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 created dynamically at runtime. In Python, classes can be created dynamically, and classes are objects, which is what Python does behind the scenes when using the class keyword. All of this is achieved through metaclasses. So what exactly is a metaclass? A metaclass is something that creates classes. Creating classes is for creating instances of classes, but we know that classes are objects, so metaclasses are used to create these classes (objects), making metaclasses the factory of classes. The main purpose of metaclasses is to create APIs.
Closures
What are closures in Python? If an internal function references a variable in an external scope, then the internal function is considered a closure. In Python’s language, calling a function A that returns a function B to you is called a closure. Decorators are a closure.
Receive the latest 2023 Python zero-based learning materials,Reply in the background:Python