search
HomeBackend DevelopmentPython TutorialAnalyze the basic syntax of Python in simple terms

Share 10 posts every day and fly together!

1. List fragmentation:

Analyze the basic syntax of Python in simple terms

2. The magic of the list:

(1) Compare size:

2_Analyze the basic syntax of Python in simple terms

(2) List addition:

Analyze the basic syntax of Python in simple terms

(3) When lists are multiplied, they become compound assignments:

Analyze the basic syntax of Python in simple terms

(4) The usage of in/not in in the list:

Analyze the basic syntax of Python in simple terms

(5) The concept of "copy" of list fragmentation:

Sharded copy syntax: list name[:];

The essence of sharded copy: open up a new memory space;

Analyze the basic syntax of Python in simple terms

Note: The real copy requires the sharding method;

3. The difference between tuples and lists:

Answer: Tuples and lists are the largest The difference is that you can modify the elements in the list at will, and you can insert or delete an element at will, but this is not possible for tuples. Tuples are immutable (like strings), so you can’t expect to perform original operations on tuples. advanced operations such as sorting.

3_Analyze the basic syntax of Python in simple terms

Note: Tuples can be defined without parentheses (list = 1,2,3,4)

Analyze the basic syntax of Python in simple terms

4. Use string concatenation to update and delete:

4_Analyze the basic syntax of Python in simple terms

Analyze the basic syntax of Python in simple terms

5. Use join to separate String:

5_Analyze the basic syntax of Python in simple terms

split() is exactly the opposite of join(). split() is used to split the string:

Analyze the basic syntax of Python in simple terms

The

replace() method, as its name suggests, replaces the specified string:

Analyze the basic syntax of Python in simple terms

6. String formatting:

(1) format () Function usage:

6_Analyze the basic syntax of Python in simple terms

(2) Formatting operator: %

Analyze the basic syntax of Python in simple terms

7, sequence:

(1) list(), tuple(), str(obj);

7_Analyze the basic syntax of Python in simple terms

##(2) len();

Analyze the basic syntax of Python in simple terms

(3) max() and min();

Analyze the basic syntax of Python in simple terms

(4) sum(), sorted() and reversed();

Analyze the basic syntax of Python in simple terms

(5) enumerate() and zip();

Analyze the basic syntax of Python in simple terms

8, python function:

(1) Function document

Analyze the basic syntax of Python in simple terms

(2) Keyword parameters: Analyze the basic syntax of Python in simple terms

Analyze the basic syntax of Python in simple terms

(3) Default parameters :

This is very similar to PHP

Analyze the basic syntax of Python in simple terms

(4) Collect parameters:

This is very interesting, prepared for lazy people

Analyze the basic syntax of Python in simple terms

The asterisk * can actually be packaged and 'unpacked'. If you need to pass a list a into the collection parameter *params of the test parameter, then an error will occur when calling test(a). This You need to add an asterisk (*) in front of a to indicate that the actual parameters need to be "unpacked" before they can be used:

Analyze the basic syntax of Python in simple terms

(5) Global variables:

Analyze the basic syntax of Python in simple termsBut it is not ruled out that some people still insist on the eight-character principle of "accept humbly and never change" and still feel it is necessary to modify this global variable in the function, then you might as well use global Keywords to achieve the goal!

Analyze the basic syntax of Python in simple terms

## (6) Inline function:

(7) Closure: this I personally find it the most interesting and profound;

Closure is an important grammatical structure of functional programming. Functional programming is a programming paradigm. The famous functional programming language is LISP language (you may have heard I have said that this language is mainly used in graphics and artificial intelligence, and has always been considered a language used by genius programmers)

Note: Closures target internal functions, so they cannot be used directly externally. Adjust the internal function; Analyze the basic syntax of Python in simple terms

(8) lambda expression: 8_1Analyze the basic syntax of Python in simple terms Also known as anonymous function

Analyze the basic syntax of Python in simple terms (9) filter( ) and map():

filter() has two parameters. The first parameter can be a function or None. If it is a function, the second iterable data will be used. Each element in is calculated as a parameter of the function, and the returned True value is filtered out; if the first parameter is None, the True value in the second parameter is directly filtered out. Come, let's take a look directly. Example:

Analyze the basic syntax of Python in simple terms

##map does not mean map here. In the field of programming, map is generally used to explain the built-in function map(). There are also two parameters, which are still a function and an iterable sequence. Each element of the sequence is used as a parameter of the function for operation and processing until each element of the iterable sequence is processed, and a new sequence composed of all processed elements is returned. . With the experience of filter() just now, let's look at the code directly:

## (10) Recursion is "magical": Analyze the basic syntax of Python in simple terms

The concept of recursion is the category of algorithms. It does not originally belong to the grammatical content of the Python language. However, recursion is discussed in every programming language teaching series. That is because if you master the methods and techniques of recursion, you will find that this It’s a great programming idea!

##Having said so much, I haven’t talked about the concept of recursion in programming! Recursion, in principle, is the function call itself. A behavior, let’s look at a factorial example:

9. Dictionaries and collections:

Analyze the basic syntax of Python in simple terms (1) Create and access dictionaries:

Dictionary is the only mapping type in Python. Mapping is a term in mathematics that refers to the "correspondence" relationship between elements between two sets of elements. As shown in the figure, the mapping diagram;

is created by {}: 9_1_Analyze the basic syntax of Python in simple terms

Create a dictionary through dict(): Analyze the basic syntax of Python in simple terms

It is recommended to use {} to create a dictionary, which looks comfortable;

Analyze the basic syntax of Python in simple terms (2) Dictionary built-in method:

fromkeys()The method is used to create and return a new dictionary. It has two parameters: the first parameter is the key of the dictionary; the second parameter is optional and is passed in The value corresponding to the key. If not provided, the default is None. For example:

9_2_Analyze the basic syntax of Python in simple termsThis example tells us that we cannot always take things for granted. Sometimes reality will give you a hard blow. The fromkeys() method does not The values ​​"one", "two" and "three" will be assigned to keys 1, 2 and 3 respectively, because fromkeys() treats ("one", "two", "three") as one value.

-------------------------------------------------- -------------------------------------------------- ------------

key(), values() and items():

keys() is used to return the dictionary keys, values() is used to return all values ​​in the dictionary, then items() of course returns all key-value pairs (i.e. items) in the dictionary, for example:

9_Analyze the basic syntax of Python in simple terms

------------------------------------------------- -------------------------------------------------- ----------

get(), in and not in: The

get() method provides a more relaxed way to access the dictionary item, when the key does not exist, the get() method does not report an error, but silently returns a None, indicating that nothing was found; if you want to return the specified value when the data cannot be found, you can use the second The default return value corresponding to the parameter setting;

9_Analyze the basic syntax of Python in simple terms

If you don’t know whether a key is in the dictionary, you can use the membership operator (in or not in) to judge;

--------------------------------------- -------------------------------------------------- ------------------

clear() clears a specified dictionary:

Some students may think that using Clear the dictionary by assigning the variable name to an empty dictionary. This has certain drawbacks. Let’s take a look at an example;

9_Analyze the basic syntax of Python in simple terms

--------- -------------------------------------------------- --------------------------------------------------

The copy() method is to copy the dictionary:

9_Analyze the basic syntax of Python in simple terms

-------------- -------------------------------------------------- -------------------------------------

pop() And the popitem() method:

pop() pops up the corresponding value for a given key, and popitem() pops up an item. These two are easier:

Analyze the basic syntax of Python in simple terms

The setdefault() method is somewhat similar to the get() method, but setdefault() will automatically add it when it cannot find the corresponding key in the dictionary:

Analyze the basic syntax of Python in simple terms------------------------------------------------ -------------------------------------------------- -----

update() method is used to update the dictionary: (In fact, there is a method above, but this one is more authentic)

Analyze the basic syntax of Python in simple terms

10. Sets:

In Python3, if you enclose a bunch of numbers in braces but do not reflect the mapping relationship, then Python will think that the bunch of things is a set.

10_Analyze the basic syntax of Python in simple terms

Since the elements in the set are unordered, they cannot be accessed using subscripts like sequences. But you can use iteration to read the data in the collection one by one: (add() and remove() methods)

Analyze the basic syntax of Python in simple terms

Sometimes you want the data in the collection to be stable, that is, like a tuple, elements in the collection cannot be added or deleted at will. Then we can define an immutable collection. The frozenset() function is used here. Yes, it freezes the elements:

Analyze the basic syntax of Python in simple terms

The above is the detailed content of Analyze the basic syntax of Python in simple terms. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)