The most complete summary of Python basic syntax and data types

The most complete summary of Python basic syntax and data types

Abstract: Summarizes the most complete basic syntax and data types of Python. This article will take you to learn Python.

This article is shared from the " Summary of the Most Complete Basic Syntax and Data Types of Python " in the HUAWEI CLOUD Community , the original author: Beishan.

Life is short, I use Python. Summarizes the most complete basic syntax and data types of Python, and this article takes you to learn Python.

1. Python's most complete basic summary

1.1 Write the first program

1.2 Comments in Python

1.3 Basic Architecture of Python Code

1.4 Data type

1.5 Operator

1.6 Built-in functions

1.7 String type

1.8 Use% placeholders to format strings

1.9 Use the format() function to format a string

1.10 Use f-string to format strings

1.11 String manipulation

1.12 list and tuple

1.12.1 list

1.12.2 List operation function

1.13 tuple

1.14 Dictionary type

1.14.1 Dictionary type operation method

1.15 Collection type

1.15.1 Set operations

1.15.2 Set operations

Write the first program

Haha, an introductory language. Of course, the first sentence is hello world. Compared with C and Java, the syntax of Python is very simple, just print() directly.

Now we start to write the first program: output Hello World!

It will output a string "Hello World!".
If the print() function is called multiple times, as follows:

As you can see, each print() statement occupies one line. If you want to output the above three sentences to the same line, you can do this:

By adding end="" to the print, the original default output of the print() function is added with a newline, and the output is changed to an empty string after the output, so that there will be no newline.

In addition, in addition to receiving string parameters, print() can also receive any other parameters. You can also call a function to print out the result of the function execution. It can also be an expression to print out the result of the expression.

Comments in Python

In the previous code, we used # to add comments to the code after the print() statement. This is a very common way of commenting: single-line comments.

If there are multiple lines of comments, you can use three pairs of double quotes or single quotes to wrap them:

In addition to the above two kinds of comments, there is a special kind of comments, that is, documentation comments. Document comments are mainly used to automatically generate help documents, which have certain requirements for format and location.

If your program may be used by other people, in order to facilitate them and avoid them from viewing your code to get a trial method, you should provide documentation comments and generate documentation for them.

The documentation comment must be the first statement in a package, class, or function. These strings can be automatically extracted by the doc member of the object, and can be used by pydoc. And documentation comments must use three pairs of single or double quotation marks to annotate, can not use #

In order to explain the role of the function better and more clearly, the documentation of the function should follow certain rules:

  • Args: List the name of each parameter, and use a colon and a space after the name to separate the name and description of the parameter. If the description is too long to exceed 80 characters on a single line, use a hanging indent of 2 or 4 spaces
  • Returns: The return value of the function, including the type and specific return value. If there is no return value or return None value, you can leave it alone
  • Raises: The exceptions thrown. Don't throw exceptions and don't write.

Basic architecture of Python code

In the previous several programs, we can basically appreciate some of the characteristics of Python programs.

First of all, in Python code, {} or other obvious signs are not used to limit the beginning and end of the code, but the code relationship is determined according to the indentation of the code: consecutive codes with the same indentation are the same code block, such as functions In the definition.

At the end of a statement, there is no need to use; to end, but directly use line break to indicate the end of the statement.

In addition, Python also has some distinctive writing methods. For example, if a sentence is too long, you can use "\" to split it into multiple lines:

Although in Python it is not necessary to use; as a statement division, but if there are multiple statements in a line, it can be used; separate these statements:

type of data

In the above code, we have defined variables a, b, x, y, etc. It can be seen that in Python, unlike many other programming languages, Python variables do not need to be declared as specific types, but are directly assigned to them. Python will set the type of the variable according to the value.

Although Python variables can be used directly without first declaring the type, it does not mean that Python has no data types. Commonly used data types in Python include:

  • number

  • int (integer)

  • float (floating point)

  • complex (complex number): A complex number consists of a real part and an imaginary part, which can be represented by a + bj, or complex(a,b). The real part a and imaginary part b of the complex number are both floating-point types

  • bool

  • string

  • list

  • tuple

  • set

  • These types of dict (dictionary) , we will talk about them one by one in subsequent courses.


In Python, commonly used operators are provided. Let's take a look at its mathematical operators first.

  • /
  • %: take the remainder
  • //: Divide
  • **:power

It can be seen that the results of operations on integers and floating-point numbers are all floating-point numbers. If you want to convert a floating point number to an integer, you can do this:

Or convert an integer to a floating point number:

The bool type has only two values: True or False. Its arithmetic operations are not, and, or

Built-in function

The so-called built-in functions are functions that have been defined in the Python language itself for us to use directly, such as the print(), abs(), int(), float(), etc. used earlier. We will talk about these functions in appropriate places later.

Earlier we talked about print(), let s take a look at the input.

Use input() for input, which receives a string as the prompt message displayed to the user. After the user inputs, it will be returned to the program in the form of a string.

String type

String is one of the most commonly used data types, it is used to represent a string of immutable characters.
Strings can use double quotes or single quotes to enclose characters

If the string originally contains single or double quotes, you can deal with it in the following ways:

  • If the string contains single quotation marks, use double quotation marks to wrap the string, otherwise, if the string contains double quotation marks, use single quotation marks to wrap the string, for example:

  • If there are both single and double quotation marks in the string, you can escape the single and double quotation marks in the string, that is, add/in front of the single and double quotation marks in the string, for example:

Chinese full-width single and double quotation marks are not affected, that is, Chinese single and double quotation marks will be treated as ordinary characters.

For strings with complex content, you can also use """""" or ``''" to wrap the string. At this time, no matter whether there are single or double quotation marks, it will be handled correctly intact.

Use% placeholders to format strings

Sometimes, we may need to add some uncertain content to the string, for example, according to the user's input, output a greeting:

This approach can achieve our purpose, but it is not optimized for readability and performance. So three ways to format strings have been successively provided in Python. Let's look at the first one: use the placeholder %. If the above code is changed to use% placeholders, it can be modified as follows:

The advantage of this method is that the% placeholder can automatically convert non-string data into a string, and connect it with other parts of the string to form a new string.

Its standard format is:

For other format characters except f, s, d, please see the following example:

The way to specify the name:

This kind of formatted data is slowly abandoned, because its placeholders and values must have a one-to-one correspondence. When there are more placeholders, it is easier to make mistakes.

Use the format() function to format the string

In this way, {} is used as a placeholder, but its advantage is that you can specify the order for it, for example:

You can also add variables:

Consider the following situation: A likes B, but B does not like A

If A and B are pending, use the previous formatting method to define as follows: "%s likes %s, but %s does not like %s" %("A","B","B","A")

The problem with this approach is:

  1. All use %s to specify, the difference between A and B is not visible
  2. A and B are actually repeated once, if they are repeated multiple times, they need to be repeated more times.
    If you use the format() function, it can be written as:

Of course, you can also use the same data type and other settings as% in format():

Specify length and precision:

In addition, after specifying the length, if the corresponding value is insufficient, you can specify the supplementary character (the default is a space, such as the space after the Beishan La above). At this time, it must be used in conjunction with the alignment method:

  • "<": Left aligned
  • "^": align center
  • ">": align right

Use f-string to format the string

The format() method has been significantly improved compared to %, but it is still not flexible enough in some complex situations. E.g:

It can be seen that once there are more parameters, you need to do more useless work when format() is used. In fact, if you can directly correspond to the variables in {}, it will be much more convenient. You can use f-string to change to

Because the content in f-string {} will be calculated at runtime, so you can also directly call functions and use expressions in {}, for example:

For multi-line text, in order to make the code more beautiful and readable, it should be written as follows:

Of course, the above restrictions can also be used in f-string:


Specify alignment:

Numbers with different bases and different representations:

String manipulation

If you want to get a substring from the string, you can get it by str[start:end]. Where start is the start index, end is the end index, but the characters corresponding to the index of end are not included. If you only take a single character, you only need to specify the start parameter.

We often need to manipulate strings, so Python provides a lot of string manipulation functions for us to use.

  • capitalize(): capitalize the first letter of the string
  • title(): Capitalize the first letter of each word in the string
  • lstrip(), rstrip(), strip(): used to remove spaces on the left, right, and left and right sides of the string, respectively
  • It should be noted that none of the above methods will change the original string content, but will generate a new string
  • startswith(prefix, start, end): whether the string starts with a string
  • endswith(suffix, start, end): Whether the string has ended with a string
  • find(s, start, end): Search from left to right for whether the string s is contained in the string, and return the first position found. If not found, return -1
  • rfind(s, start, end): similar to find(), except that it searches from right to left
  • index(s, start, end): similar to find(), but an error will be returned if it is not found
  • rindex(s, start, end): similar to index(), except that it searches from right to left
  • isalnum(): If there is at least one character in the string, and the string consists of numbers and letters, it is true.
  • isalpha(): true if there is at least one character in the string and the string consists of letters
  • isdigit(): Whether it is a number (integer), the decimal point is not counted, only Arabic numerals are supported
  • isnumeric(): Whether it is a number. Supports numbers in local languages, such as Chinese "one thousand three hundred", " ", etc.
  • replace(s1, s2): Replace s1 in the string with s2

Let's look at a comprehensive case.
In the specified string, replace all the letters in the string that are the same as the first letter (except the first character itself)
with another character "@", for example: little, after the replacement becomes litt@e, that
is little All l (the first letter is l) are replaced with @ (except for the first letter itself).
Here is an implementation idea:

list and tuple

Use list or tuple tuple, you can store a series of data, for example, put the names of all students in the class together:
names = ["North Mountain", "Li Si", "Wang Wu"]


A list is an ordered and variable data collection. Variable means that you can add or delete elements to it at any time.
The element can be retrieved from it by index, for example, names[1] will retrieve the second data (the index starts from 0).

  • If the index is out of range (for example, the index is greater than or equal to the number of lists), an error will be reported
  • The index can be a negative number, a negative number means that the data is counted from back to front, and the index of the last element is -1 at this time

The data types of the elements in the list do not have to be the same. You can even use list data as an element of another list. For example:
names = ["North Mountain La","Li Si", ["Leonardo","Dicaprio"], " "], where the third element (index 2) is another list.
At this time, names [2] The value retrieved is the list ["Leonardo", "Dicaprio"]. To get the value of Leonardo, you need to use index 0 on this list ["Leonardo", "Dicaprio"] to get it, so you can get it through names[2][0] get

If you want to take out a certain range of elements from the list, you can use list[start:end] to get it, for example: names[1:3] take out from index 1 to index 3 (not including index 3) The 2 elements.

  • If start is omitted, it means starting from 0
  • If end is omitted, it means to the end of the last element of the list

If you want to create a series of lists with numbers as content, you can combine the list() function and the range() function to create it. For example, create a list containing numbers 0-99:

The function prototype of range():

  • range(stop): 0 starts to count, counts to the end of stop, but does not include stop, for example: range(10), the generated number range is 0-9
  • range(start, stop[, step]): the count starts from start and ends at stop (not including stop), step is the step size, that is, the range of each change, the default is 1, that is, each time it is increased by 1
  • start/stop/step can be any integer
  • "Start <stop" can generate a range containing elements. If stop <start, it will be empty.

List operation function

  • append(element): append an element to the end of the list
  • insert(index, element): Insert an element into the specified index position of the list
  • You can directly assign a value to the specified index element, and replace the old value with the new value: names[idx]= value
  • pop() takes the last element out of the list and deletes the element from the list
  • If you want to delete an element corresponding to an index in the list, you can use del list[idx]
  • extend(seq): append a series after the original list
  • remove(obj): remove the first element matching obj from the list
  • clear(): Clear the entire list
  • count(obj): Count the number of times the element obj appears in the list
  • sort(key= , reverse= ): To sort the list, you can specify the key used for sorting. reverse is used to specify whether to reverse the order.

Let's look at a more complicated list:

the_irishman = [[ Robert , De Niro ], [ Al , Pacino ],
[ Joe , Pesci ], [ Harvey , Keitel ], [ Bobby , Cannavale"]]

Suppose we want to sort it now, should we sort it by first name or last name?

At this time, you need to use the key parameter in the sort() function. A function can be assigned to it through the key. This function restricts whether it should be sorted by first name or last name:


Tuples are similar to lists. The difference is that tuples are immutable, that is, if tuples are initialized, they cannot be changed. Tuples do not have pop()/insert() methods.

It should be noted that the immutable here means that the tuple element cannot be directly changed to another element, but if the tuple element is a mutable object, such as a list, then the content in the list can be changed, but You cannot replace the existing list in the tuple with another list.

Another area of tuples that needs special attention is the definition of tuple data with only one element. Because () is still a symbol used in expressions (used to change the order of operators), if there is only one element, define it as names = ("North Mountain"), at this time () will be used as an expression symbol, here it will Ignored, so the value of names is now the string "North Mountain La" instead of the tuple type. To avoid this situation, you can define the tuple data of a single element like this: names = ("North Mountain",)

You can also use the following methods to create tuples:

Both lists and tuples can be multiplied by an integer n, which means copying n copies of the data in the original list or tuple to generate a new list or tuple:

Between lists and tuples and tuples, you can use "+" to merge the data in two lists or tuples into a new list or tuple

Note that tuple and list cannot be combined.
If you want to take out the elements in the list or tuple one by one, you can take out the elements one by one by

Dictionary type

A dictionary (dict) is a variable container data used to store key-value pairs.

Each key-value pair of the dictionary is separated by a colon (:), and each key-value pair is separated by a comma (,). The entire dictionary is enclosed in curly braces ({}). The format is as follows:

  • d = {key1: value1, key2: value2}
    Note that the key in the dictionary must be unique, that is, there cannot be two pairs of elements with the same key. The value of the corresponding key can be obtained by way of d[key]. If the corresponding key does not exist, an error will be reported.

  • To add data to the dictionary, you can pass

  • d[new_key] = new_value

  • Modify the value corresponding to a key
    -d[key] = new_value

  • Delete the element corresponding to a key

  • del d[key], will delete the key-value pair corresponding to the key, not just delete the value

  • del d, the entire dictionary data will be deleted

In order to avoid the non-unique key, it is required that the key can only use constant data as the key, such as numbers, strings, and tuples. Because the list is variable data, it cannot be used as a key.

Dictionary type operation method

  • items(): Return a traversable (key, value) tuple array as a list
  • keys(): Returns an iterable object containing all keys, which can be converted to a list using list()
  • values(): returns an iterable object containing all values, which can be converted to a list using list()
  • pop(key[,default]): Take out the value of the corresponding key, if it does not exist, use the default value
  • popitem(): Take out the last key-value pair in the dictionary
  • get(key[,default]): Get the value of the corresponding key, if the key does not exist, use the default value

Collection type

A set is an unordered sequence of non-repeating elements.

You can use set() or {} to create a collection:

  • If you use {} to create a collection, pay attention to the difference with the dictionary data type-dictionary data is a key-value pair, and here is a single data
  • If you create an empty collection, you cannot use {}, because the system will first treat it as a dictionary data type. So use set() to create an empty collection
  • If you put duplicate elements in the collection, only one will remain.
    Create a collection from a string:

Create a collection from the list:

Create a set from tuples:

Create a collection from a dictionary, at this time only the key will be taken as the element of the collection:

Collection operation

-add(): Add an element to the set. If the element is already in the set, it will not succeed. The parameter can only be a single element, not a list, tuple or set

-update(seq): Add multiple elements to the set. seq can be a string, tuple, list or another set

-Note: When both add() and update() are strings as parameters, the difference between the two: add() adds the string as a whole, while update() adds individual characters in the string one by one -discard(item): delete the specified element from the collection.

-remove(item): Remove the specified element from the collection. If the element does not exist, an error will be reported.

-pop(): Remove an element from the collection. Because the collection is unordered, there is no guarantee which element is removed

-clear(): clear the entire collection

Set operations

Between collections, collection operations can be performed. The main collection operations are:

  • Intersection: Operate on two sets to generate a new set: only elements in both sets will be placed in the new set

You can use the operator & or the function intersection() to perform the intersection operation

  • Union: Two sets generate a new set, and the elements in both sets will be placed in the new set

You can use the | operator or union() function for union operation

  • Difference: Two sets generate a new set. On the basis of the original set, the elements of both are subtracted to generate a new set.

You can use the-operator or the difference() function to perform subtraction operations

  • Symmetric difference: Two sets generate a new set. The elements in the new set are the elements of the two sets minus the same elements.

You can use the ^ operator or the symmetric_difference() function to perform symmetric difference operation

Other operations:

  • symmetric_difference_update()/intersection_update()/difference_update()/update(): still perform the previous corresponding intersection, union, difference, symmetric difference operations, but update the result of the operation to this set.

  • isdisjoint(): a.isdisjoint(b), whether the two sets a and b have no intersection, return True if there is no intersection

  • issubset(): a.issubset(b), whether a is a subset of b, it returns True

  • issuperset(): a.issuperset(b), whether a is all elements including b, including returns True

Click to follow to learn about Huawei Cloud's fresh technology for the first time~