Abstract: This article introduces the basic syntax and data types of Python.

This article is shared by Huawei Cloud community “Python basic Syntax and data types summary”, originally written by Beishan.

Life is short. I use Python. This article introduces you to the basics of Python syntax and data types.

1. The most complete Python foundation summary

1.1 Write the first program

1.2 Comments in Python

1.3 Basic Structure of Python Code

1.4 Data Types

1.5 the operator

1.6 Built-in Functions

1.7 String Types

1.8 Format strings with % placeholders

1.9 Format a String using the format() function

1.10 Use f-string to format Strings

1.11 String Operations

1.12 the list and the tuple

1.12.1 list

1.12.2 List operation function

1.13 the tuple

1.14 Dictionary Types

1.14.1 Operations on dictionary Types

1.15 Collection Types

1.15.1 Set Operation

1.15.2 Set operation

Write your first program

Hello world is a very simple syntax in Python compared to C and Java. Just print()

Let’s start our first program: Hello World!

It prints a string “Hello World! “. If print() is called multiple times, it looks like this:

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

Print () replaces the default output of print() with a newline by adding end=”” to the output of print() with an empty string.

In addition, print() can accept any argument in addition to a string argument, and can call a function to print out the result of its execution. It can also be an expression that prints the result of running the expression.

Comments in Python

In the previous code, we commented the code with # after the print() statement. This is a very common type of comment: single-line comments.

If you have a multi-line comment, you can enclose it with three pairs of double or single quotation marks:

In addition to the above two types of comments, there is a special type of comment, which is the document comment. Document annotations are mainly used to automatically generate help documents, which have certain formatting and location requirements.

If your program is likely to be used by others, for their convenience and to prevent them from looking at your code for trial methods, provide documentation comments and generate documentation for them.

Documentation comments must be the first statement in a package, class, or function. These strings can be extracted automatically through the doc member of the object and can be used by PyDoc. Document comments must be annotated with three pairs of single or double quotation marks, not #

To better and more clearly explain what a function does, the documentation of a function should follow certain rules:

  • Args: Lists the name of each parameter, followed by a colon and a space to separate the name and description of the parameter. If the description is too long beyond a single line of 80 characters, use two or four Spaces of suspended indentation
  • Returns: The return value of the function, including the type and the circumstances of the specific return value. Do not write if no value is returned or if None is returned
  • Raises: Exceptions thrown by Raises. Do not throw an exception and do not write.

Basic Python code architecture

In the previous few programs, we’ve seen some basic features of Python programs.

First, Python code does not use {} or other obvious flags to limit the beginning and end of code. Instead, code relationships are determined by indentation: contiguous code with the same indentation is the same code block, as defined in a function.

The end of a statement, not needed; Instead, use a newline to indicate the end of the statement.

In addition, Python also has some unique ways of writing it. For example, if a statement is too long, you can use “\” to split it into multiple lines:

Although Python does not use it; As statement splitting, but can be used if there are more than one statement in a line; Separate these statements:

The data type

In the above code, we defined variables A, B, x, y, and so on. As you can see, in Python, unlike many other programming languages, a variable in Python does not need to be declared as a specific type. Instead, a value is assigned to it directly, and Python sets the type of the variable based on the value.

While Python variables can be used without first declaring their types, it’s not that Python doesn’t have data types. Common Python data types include:

  • Number = number

  • Int (integer)

  • Float (float)

  • Complex: The complex number consists of the real and imaginary parts and can be represented by a + BJ, or complex(a,b). The real a and imaginary b parts of the complex number are floating-point

  • bool

  • String (string)

  • List (list)

  • Tuple (tuple)

  • Set

  • Dict types, we’ll cover them all later in the course.

The operator

In Python, common operators are provided. Let’s look at its mathematical operators first.

  • /
  • % : take over
  • / / : divisible
  • * * : power

As you can see, both integer and floating-point operations result in 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:

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

Built-in function

Built-in functions are functions defined by The Python language, such as print(), abs(), int(), float(), and so on. We’re going to talk about all of these functions in appropriate places.

Earlier we talked about print(), so let’s look at the input.

Input uses input(), which receives a string as a prompt to be displayed to the user and is returned to the program as a string.

String type

A string is one of the most common data types and is used to represent an immutable string of characters. Strings can be enclosed in double or single quotation marks

If the string already contains single or double quotation marks, you can do the following:

  • If the string contains single quotes, double quotes are used to enclose the string, and vice versa, if the string contains double quotes, single quotes are used to enclose 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 by adding \ before the single and double quotation marks, for example:

Chinese full-angle single and double quotation marks are not affected, that is, Chinese single and double quotation marks are treated as common characters.

For complex strings, you can also use “””””” or ’’’’’’ to wrap the string, which will be handled correctly regardless of whether there are single or double quotes.

Format the string with the % placeholder

Sometimes, we may need to add something indeterminate to the string, such as an output statement greeting based on user input:

This approach works for our purposes, but it’s not optimized for readability or performance. So there are three ways to format strings in Python. Let’s look at the first one: use the placeholder %. If the above code were changed to use the % placeholder, it could be modified to look like this:

The advantage of this approach is that the % placeholder automatically converts non-string data to a string and concatenates it with the rest of the string to form a new string.

Its standard format is: %[(name)][flags][width].[precision] Typecode

For format characters other than f, S, and d, see the following example:

How to specify name:

This format of data was gradually abandoned because it required a one-to-one correspondence between placeholders and values, which made it more error-prone when there were more placeholders.

Use the format() function to format a string

In this way, {} is used as a placeholder, but it has the advantage of specifying an order, for example:

You can also add variables:

Consider the following case: A likes B, but B doesn’t like A

If A and B to be determined, with the previous way of formatting are defined as follows: “% s % s like, don’t like to % s % s” % (” A “, “B”, “B”, “A”)

The problem with this approach is that:

  1. We can’t tell the difference between A and B
  2. A and B are actually repeated once, and if they are repeated many times, they need to be repeated many more times. If you use the format() function, it can be written as:

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

Specify length and precision:

In addition, after specifying the length, if the corresponding value is insufficient, you can specify the complementary character (default is space, such as the space after the above beishanla), which must be used with the alignment:

  • < : left-aligned
  • ^ : center aligned
  • > : Align them right

Use f-string to format strings

The format() method is a significant improvement over %, but it is still not flexible enough in some complex cases. Such as:

As you can see, once you have a lot of arguments, you have to do a lot of unproductive work using format(). In fact, if you can directly in {}, and variables directly one-to-one correspondence, that is a lot more convenient. You can change it to f-string

Because the contents of {} in f-string are evaluated at runtime, we can also call functions and use expressions directly in {}, for example:

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

Of course, all of the above restrictions can be used in f-strings as well:

Such as:

Specify alignment:

Numbers in different bases and expressions:

String manipulation

To retrieve a substring from a string, use STR [start:end]. Start is the start index, end is the end index, but the characters corresponding to the end index 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 many functions for manipulating strings.

  • Capitalize () : Capitalize the first letter of a 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 sides of a string, respectively
  • Note that these methods do not change the content of the string, but instead generate a new string
  • Startswith (prefix, start, end) : whether the string startswith a string
  • Endswith (suffix, start, end) : indicates whether the string endswith a certain string
  • Find (s, start, end) : Finds the string s from left to right, returning the first position found. If not found, return -1
  • Rfind (s, start, end) : Similar to find() except that it looks from right to left
  • Index (s, start, end) : Similar to find(), but returns an error if not found
  • Rindex (s, start, end) : Similar to index() except that it looks from right to left
  • Isalnum () : True if the string contains at least one character and consists of numbers and letters.
  • Isalpha () : True if there is at least one character in the string and the string consists of letters
  • Isdigit () : Indicates whether it is a digit(integer), not counting the decimal point. Only Arabic digits are supported
  • Isnumeric () : Is there a number? Supports numbers in the local language, for example, “1300” and “eighteen thousand” in Chinese
  • Replace (s1, s2) : Replaces s1 in the string with S2

Let’s look at a composite case. In the specified string, replace all the same characters (except the first character itself) with another character “@”, for example: Replace all l(the first letter is l) in little with @ (except the first letter itself). Here’s how to do it:

The list and a tuple

Using a list or tuple, you can store a series of data, for example, putting the names of all the classmates in a class together: names = [” Beishan la “, “Li Si”, “Wang wu”]

list

A list is an ordered, mutable collection of data, mutable meaning that elements can be added or removed at any time. Elements can be fetched from it by index, for example names[1] will fetch the second data (index starts at 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 negative, which means counting the data from back to front. The index of the last element is now -1

Elements in a list do not have to be of the same data type. You can even use list data as an element of another list. Such as: Names = [” Dicaprio “, “Dicaprio”, “Dicaprio”], with the third element (index 2) for another list, names[2] is the list of [” Leonardo “, “Dicaprio”], To get the value Leonardo, use index 0 on the list [” Leonardo “, “Dicaprio”], so it’s available with names[2][0]

To retrieve a range of elements from a list, use list[start:end]. For example, names[1:3] retrieves two elements starting at index 1 and ending at index 3, excluding index 3.

  • Start If omitted, the value starts from 0
  • End, if omitted, ends at the last element in the list

If you want to create a list of numbers, you can combine the list() and range() functions to create it, for example, to create a list of numbers 0-99:

Range () function prototype:

  • Range (stop) : 0 starts the count and stops the count but does not include stop, for example, range(10). The generated number ranges from 0 to 9
  • Range (start, stop[, step]) : counts from start to stop (stop is not included). Step is the step size, that is, the range of each change. The default is 1, that is, each increment is 1
  • Start, stop, and step can be any integer
  • “Start < stop”, can generate a range containing elements, if stop< start, empty.

List manipulation function

  • Append (Element) : Appends an element to the end of the list
  • Insert (index, element) : Inserts an element into the list at the specified index position
  • You can assign a value directly to the specified index element, replacing the old value with the new value: names[IDx]= value
  • Pop () takes the last element out of the list and removes it from the list
  • To delete an element from an index in a list, use del list[IDx]
  • Extend (seq) : Appends a series to the original list
  • Remove (obj) : Removes the first element from the list that matches obj
  • Clear () : Clears the entire list
  • Count (obj) : Counts the number of occurrences of the element obj in the list
  • Sort (key =… , reverse =…). To sort a list, you can specify a key for sorting. Reverse specifies whether the sequence is reversed.

Let’s look at a more complex 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?

This is where the key argument in sort() comes in. We can give it a function that restricts sorting by first name or last name:

tuple

Tuples are similar to lists, except that tuples are immutable, meaning that if a tuple is initialized, it cannot be changed. Tuples have no pop()/insert() methods.

Note that immutable means that you cannot change the element of a tuple directly into another element. However, if the element of a tuple is a mutable object, such as a list, then the contents of the list can be changed, but you cannot replace the existing list with another list.

Another area of special attention to tuples is the definition of tuple data with only one element. Because () is also the symbol used in expressions (used to change the order of operators), if there is only one element and names = (” Beishandra “), then () is treated as an expression symbol and is ignored, so names is a string beishandra, not a tuple type. To avoid this, you can define the tuple data of a single element like this: names = (” Beishan, “)

You can also create tuples using the following method:

Both a list and a tuple can be multiplied by an integer n to produce a new list or tuple by copying n copies of the data in the original list or tuple:

Between lists and tuples, you can use “+” to combine data from two lists or tuples into a new list or tuple

Note that tuples and lists cannot be combined. To retrieve the elements in a list or tuple one by one, use the for… The in… Fetch elements one by one:

A dictionary type

Dict are mutable containers of data that hold 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 ({}) in the following format:

  • D = {key1: value1, key2: value2} Note that the key in the dictionary must be unique, that is, there cannot be two pairs of the same key elements. You can obtain the value of the corresponding key by using d[key]. If no corresponding key exists, an error message is displayed.

  • To add data to the dictionary, you can pass

  • d[new_key] = new_value

  • Change the value of a key. -D [key] = new_value

  • Deletes the element corresponding to a key

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

  • Del d will delete the entire dictionary data

To avoid unique keys, you must use only unchanging data, such as numbers, strings, and tuples. List cannot be used as a key because it is mutable data.

Dictionary type manipulation methods

  • Items () : Returns a traversable array of (key, value) tuples as a list
  • Keys () : Returns an iterable containing all the keys, which can be converted to a list using list()
  • Values () : Returns an iterable containing all the values, which can be converted to a list using list()
  • Pop (key[,default]) : fetch the corresponding key value. If no key exists, use the default value
  • Popitem () : Retrieves the last key-value pair in the dictionary
  • Get (key[,default]) : retrieves the value of the corresponding key. If the key does not exist, the default value is used

Collection types

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

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

  • If you use {} to create collections, note the difference with dictionary data types — the dictionary data is key-value pairs, whereas the dictionary data is individual data
  • If you create an empty collection, you cannot use {} because the system will treat it as a dictionary data type first. So empty collections are created using set()
  • If you add duplicate elements to the collection, only one will remain. Create a collection from strings:

Create a collection from a list:

Create a collection from a tuple:

Create a collection from a dictionary and only take key as the element of the collection:

Set operations

-add () : Adds an element to the set. If the element is already in the set, it will not succeed. The argument must be a single element and cannot be a list, tuple, or set

– update(seq) : Adds multiple elements to a set. Seq can be a string, a tuple, a list, or another set

– Discard (item) : removes the specified element from the collection. – Discard (item) : Removes the specified element from the collection.

– remove(item) : deletes the specified element from the collection. If the element does not exist, an error is reported.

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

– clear() : clears the collection

Set operations

Between sets, set operations can be performed. The main set operations are as follows:

  • Intersection: The operation of two sets to create a new set. Only elements that are common in both sets are placed in the new set

Intersection operations can be performed using the & operator or the function intersection()

  • Union: Two sets create a new set, and the elements from both sets are placed in the new set

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

  • Difference: Two sets generate a new set. On the basis of the original set, subtract the elements that both have to generate a new set.

You can use the – operator or the difference() function to do the difference set operation

  • 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 for the symmetric difference set operation

Other operations:

  • Symmetric_difference_update ()/ intersection_update()/ intersection_update()/ intersection_update()/ update() : Perform the previous intersection, union, difference and symmetry difference operations, but update the result of the operation to this set.

  • Isdisjoint () : a.isdisJoint (b), whether the sets a and B have no intersection, returns True if there is no intersection

  • Subset () : a subset(b), is a subset of B, yes returns True

  • Issuperset () : a.issuperset(b), whether a contains all elements of B, including returns True

Click to follow, the first time to learn about Huawei cloud fresh technology ~