Python 3 Quick Start 1 - Data Types and Variables

This article assumes that you already have an object-oriented programming language base, such as Java, and you want to quickly understand and use the Python language. In this paper, the key grammar, data structure and usage are explained in detail, and some difficult points are illustrated so that you can get started quickly. Some of the more biased points of knowledge will be re-queried after you get started. Official Documents That's fine. Don't grab your beard and eyebrows when you study. Also, be sure to follow the example and write more code manually. When learning a new language, we recommend that you brush the leetcode at the same time. First, you can quickly familiarize yourself with the use of the new language, and second, you can lay a foundation for future job hunting. It is recommended that you brush the leetcode directly on the web, as you will typically be asked to write code directly on the web during an interview. The leetcode brush path can be brushed in the way I recommend. In the following code, lines beginning with >> and... Are part of the code in interactive mode, >? The first row is the input in interactive mode, and the other rows are the output. Use #to turn on line comments in python code.

Introduction to Python

As a scripting language, Python can be written and executed interactively on the command line or in a *.py file and executed through an interpreter. The former is suitable for use in the validation phase, and the latter is more suitable for project writing. (Jupyter is preferred for validation, where the sequential execution of code can be artificially divided into adjacent code blocks at the time of writing, where the code blocks can be executed manually in sequence, and when an error occurs in a particular code block, there is no need to repeat the execution after the error block has been modified, only from the code block where it was modified and then executed.)

During the learning process, you can view the official documents of methods, objects, etc. through the help() function. For example, you can view the official documents of the print function:

>>> help(print)
Help on built-in function print in module builtins:
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

Basic Input and Output

Output: print() function:

>>> print("sum( a + b ):", 10 + 20)
sum( a + b ): 30

As mentioned above, the print function splits the previous string and the subsequent calculation into a string with spaces. You can also specify the SEP ='\n'parameter to splice it with line breaks as follows:

>>> print("sum( a + b ): ", 10 + 20, sep = "\n")
sum( a + b ): 

Input: input() function, which treats all read data as strings by default:

>>> a = input()
>>> print(a)
>>> print(type(a))
>? 123
<class 'str'="">

Data types and variables

Numeric ( immutable )

int   # integer
float # float
bool  # Boolean
complex  # Complex number, query documents when needed, do not explain here

As a dynamic language, Python does not need to specify a data type when defining variables, and the interpreter will deduce the variable type on its own at execution time. In the Python Console tab of Pycharm (which you will see after you set up the project, in the bottom line of the interface), you can display the type of variable in real time:

Dividing in Python returns floating-point numbers by default, using a double-slash division //which discards the part after the decimal point:

>>> a = 3       # Click shift+enter in interactive mode to write multiple lines of code
... b = 4
... print(a/b) 
0.75            # /Division returns floating point number

>>> print(a//b)
0               # //Division to discard decimal part

>>> a = 3.0
... b = 4.0
... print(a/b)

>>> print(a//b)

The Python language uses ** to denote power calculations, such as the third power of 2 written as: 2 ** 3:

>>> print(2 ** 3)

The bool types in the Python language are classified as True and False (case-sensitive). The bool type is a subclass of the int type, and True equals 1 on the value and False equals 0 on the value:

>>> True == 1
>>> False == 0
>>> issubclass(bool, int)

Tip: Numeric types in Python are reference types, not value types.

String type ( immutable )

str   # String type

What is captured in Python by''or'' represents a string that is as immutable as a character in Java. immutable ) Type. As follows:

Python strings are powerful because they support subscript access and slicing. By subscript access, we can get a character in the string directly (actually a string consisting of only one character), which starts on the right when the subscript is negative:

By slicing, we can get any substring of a string, and the slice is represented by an interval, such as [0: len] to get the substring of subscript 0 - len-1, which is left closed and right open. In addition, [:3] is equal to [0:3], [3:] is equal to [3: len]. Because each slicing operation returns a new string.

>>> a = 'python'

>>> print(a[:3])
>>> print(a[0: 3])

>>> print(a[3:])
>>> print(a[3: len(a)])

>>> print(a[:-3])  # Substring represented by the third last character from the beginning (also left-closed right-open)
>>> print(a[-3:])

Python also supports multi-line strings and queries the document as needed.

List type ( mutable)

list  # list

Lists in Python are a bit like the implementation of the list interface in Java (ArryList or LinkedList), which is an advanced data structure, except that lists in Python can store different types of data, but are not typically used in this way. Lists also support slicing and are mutable. mutable ) Type. Lists are represented by brackets enclosing comma-separated elements such as: [1, 2, 3].

Since lists are variable types, we can modify lists:

>>> a = ['p', 'y', 't', 'h', 'o', 'n']
>>> a[1] = 'i'                  # Point the element (reference) in subscript 1 to the string'i'
>>> print(a)
['p', 'i', 't', 'h', 'o', 'n']  # The string object pointed to by the second element (reference) changes from'y'to'i'

The new list returned by the slicing operation of the list is a shallow copy of the original list. Shallow copy is a way of copying objects. Since there are only reference types in Python, a shallow copy of the reference type is illustrated below with the list type as an example. The following is a diagram of List a in memory:

The variable a is a reference (address) that points to a list object in memory. Each element (reference) in the list object points to an int object in memory. When slicing a as follows:

>>> a = [1, 2, 3, 4]
>>> b = a[:2]  # 1. b Obtain a shallow copy of the first two elements of a by slicing
>>> print(a)
... print(b)
[1, 2, 3, 4]
[1, 2]
>>> b[0] = 6   # 2. Modify b[0]
>>> print(a)
... print(b) 
[1, 2, 3, 4]   # Modifying b[0] does not affect a, why?
[6, 2]

When b = a[:2] is executed, a new list object is generated in memory and b points to the new list object, with the following memory changes:

When executing b[0] = 6, the memory changes as follows:

It is easy to see from the figure above that modifying b does not affect a in this case. Then look down:

>>> a = [1, 2, 3, [0, 0]]
>>> b = a[-2:]     # b Obtain a shallow copy of the last two elements of a by slicing
>>> print(a)
... print(b)
[1, 2, 3, [0, 0]]
[3, [0, 0]]
>>> b[1][0] = 6    # Modify b[1][0]
>>> print(a)
... print(b)
[1, 2, 3, [6, 0]]  # Modifying b[1][0] affected a
[3, [6, 0]]

When executing b = a[-2:], the memory changes as follows:

When executing b[1][0] = 6, the memory changes as follows:

As you can easily see from the figure above, since a[3] and b[1] point to the same list in memory, modifying B through b[1][0] affects a at the same time.

We can also modify the list by slicing:

>>> a = [1, 2, 3]
>>> a[1: 3] = [6, 6]  # Modify the last two elements in a; Will there be an error if this is a[1:3] = [6, 6, 6]? Try it by hand
>>> print(a)
[1, 6, 6]

>>> a[:] = []         # Empty a
>>> print(a)

In addition, lists support merging and nesting:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b           # merge
>>> print(c)
[1, 2, 3, 4, 5, 6]

>>> d = [a, b]          # nesting
>>> print(d)
[[1, 2, 3], [4, 5, 6]] 

Finally, the list provides a series of membership methods:

  • list.append(x)
    Add an element at the end of the list, equivalent to a[len(a):] = [x].

    >>> a = ['wjz']
    >>> a.append('lsl')
    >>> print(a)
    ['wjz', 'lsl']
  • list.extend(iterable)
    Expand the list with elements of iterative objects. Equivalent to a[len(a):] = iterable.

    >>> a = [1, 2, 3]
    ... b = [4, 5, 6]
    ... a.extend(b)
    ... print(a)
    [1, 2, 3, 4, 5, 6]
  • list.insert(i, x)
    Inserts an element at a specified location. The first parameter is the index of the inserted element, so a.insert(0, x) inserts the element at the beginning of the list, and a.insert(len(a), x) is equivalent to a.append(x).

  • list.remove(x)
    Remove the first element with the value x from the list. Trigger when the specified element is not found ValueError Exception.

  • list.pop([i])
    Deletes the element at the specified location in the list and returns the deleted element. When No location is specified, a.pop() deletes and returns the last element of the list. (Square brackets around i in the method signature indicate that the parameter is optional and do not require input brackets. This representation is common in Python reference libraries).

    >>> a = [1, 2, 3]
    >>> a.pop()   # The default is pop(-1), which is the first to last
    >>> print(a)
    [1, 2]
    >>> a.pop(0)  # Delete the first
    >>> print(a)
  • list.clear()
    Delete all elements in the list, equivalent to del a[:]; The del statement can delete a variable or list elements by slice.

    # Delete variable
    >>> a = [1, 2, 3]
    ... b = a
    ... del a
    ... print(a)  # Delete variable a before accessing a, error: undefined
    Traceback (most recent call last):
      File "<input>", line 4, in <module>
    NameError: name 'a' is not defined
    >>> print(b)  # b Reference to the list object still exists, indicating that del just deleted the reference a
    [1, 2, 3]
    # del deletes list elements by slicing
    >>> a = [1, 2, 3]
    ... del a[:2]
    ... print(a)
  • list.index(x[, start[, end]])
    Returns the zero-base index of the first element in the list with the value x. Trigger when the specified element is not found ValueError Exception. The optional parameters start and end are slice symbols that restrict the search to a specific subsequence of the list. The index returned is calculated relative to the start of the entire sequence, not the start parameter.

    >>> a = [1, 2, 3, 4, 5]
    ... print(a.index(3))
    2  # Subscript of 3 in a is 2
    >>> a = [1, 2, 3, 4, 5]
    ... print(a.index(3, 2, len(a)))  # Find 3 starting with the third element
  • list.count(x)
    Returns the number of occurrences of element x in the list.

  • list.sort(*, key=None, reverse=False)
    Sort the elements in the list in place (for custom sort parameters, see sorted() ). This method is ignored and explained in Introduction 2.

  • list.reverse()
    Flip the elements in the list.

  • list.copy()
    Returns a shallow copy of the list. Equivalent to a[:].

Tuple type ( immutable )

tuple  # tuple

Tuples are similar to lists, but tuple s are immutable types. Tuples are usually used to contain heterogeneous elements (of different types) and lists are usually used to contain homogeneous elements. Tuples are represented by parentheses enclosing several comma-separated elements, such as (1, 2, 3). Tuples also support slicing, subscript (index) access.

Define a tuple:

>>> a = (1, 2, 3)
>>> b = 1, 2, 3  # Omitting parentheses when defining is okay, but not recommended
>>> print(a, b)
(1, 2, 3) (1, 2, 3)

# Define an empty tuple
>>> a = ()
... print(a)

# Define a tuple with only one element
>>> a = (1,)
... print(type(a))
... print(a)
<class 'tuple'="">

# No comma a a is an int variable with a value of 1
>>> a = (1)
... print(type(a))
... print(a)
<class 'int'="">

The immutability of a tuple means that the direction of each element (reference) in the tuple cannot be changed, for example, a = (1, 2, 3, 4):

The four points circled by the ellipse in the figure above cannot be modified, but if the element (reference) in the tuple points to a mutable type that cannot be modified, the mutable type itself can be modified, for example, a = ([1, 2], [3, 4]):

The point circled by a red ellipse in the figure above cannot be modified, while the point circled by a blue ellipse can be modified:

>>> a = (1, 2, 3, 4)
>>> a[0] = 6  # Cannot modify the direction of a[0]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> a = ([1, 2], [3, 4])
>>> a[0] = [6, 6]  # Cannot modify the direction of a[0]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a[0][0] = 6    # a[0] points to a list that can be modified
>>> print(a)
([6, 2], [3, 4])

Collection type ( mutable)

set  # Collection Type

Collections are unordered containers that hold no duplicate elements.

Definition set:

# Define a set by curly brackets
>>> a = {1, 2, 3, 2}
... print(a)
{1, 2, 3}  # Duplicate removal

# Define a set through the set() function. Only one parameter can be passed in, and it is of iterative type.
# Each element of an iterative type is taken out as a set element
>>> set("123 4")  # Incoming String
{'3', ' ', '2', '4', '1'}
>>> set(["1", "2", "3"])  # Incoming list
{'3', '1', '2'}

# Defining an empty collection can only use the set() function
>>> a = set()
... print(type(a))
... print(a)
<class 'set'="">

# {} represents an empty dictionary
>>> a = {}
... print(type(a))
... print(a)
<class 'dict'="">

Dictionary type ( mutable)

dict  # Dictionaries

Dictionary types are mutable, similar to Map s in Java. Dictionary types store key-value pairs, and keywords are usually strings or numbers, or any other mutable type. Tuples that directly or indirectly contain mutable objects cannot be used as keywords.

Create a dictionary:

# Create an empty dictionary
>>> a = {}
>>> print(a)
>>> a = dict()
>>> print(a)

# Common Creation Styles
# Declare key-value pairs directly in curly brackets
>>> a = {"chengdu": "A", "mianyang": "B", "guangyuan": "C"}
>>> print(a)
{'chengdu': 'A', 'mianyang': 'B', 'guangyuan': 'C'}

# Call dict function by keyword argument
>>> a = dict(chengdu="A", mianyang="B", guangyuan="C")
>>> print(a)
{'chengdu': 'A', 'mianyang': 'B', 'guangyuan': 'C'}

# The sequence of incoming key-value pairs in the constructor
>>> a = dict((("chengdu", "A"), ("mianyang", "B"), ("guangyuan", "C")))
>>> print(a)
{'chengdu': 'A', 'mianyang': 'B', 'guangyuan': 'C'}

>>> a = dict([("chengdu", "A"), ("mianyang", "B"), ("guangyuan", "C")])
>>> print(a)
{'chengdu': 'A', 'mianyang': 'B', 'guangyuan': 'C'}

>>> a = dict([["chengdu", "A"], ["mianyang", "B"], ["guangyuan", "C"]])
>>> print(a)
{'chengdu': 'A', 'mianyang': 'B', 'guangyuan': 'C'}

Add or delete dictionaries:

>>> a = dict([["chengdu", "A"], ["mianyang", "B"], ["guangyuan", "C"]])
>>> a["zigong"] = "C"  # Assigning a value to a key that does not exist adds a new key-value pair
... print(a)
{'chengdu': 'A', 'mianyang': 'B', 'guangyuan': 'C', 'zigong': 'C'}

>>> del a["zigong"]    # Delete key-value pairs with key "zigong"
... print(a)
{'chengdu': 'A', 'mianyang': 'B', 'guangyuan': 'C'}

>>> a["guangyuan"] = "F"  # Assigning a value to an existing key modifies an existing key-value pair
... print(a)
{'chengdu': 'A', 'mianyang': 'B', 'guangyuan': 'F'}

Commonly used advanced data structures


The stack's feature is LIFO, which is very easy to implement using list s; append(e) is used to add elements to the top of the stack, and pop() is used to pop out the top elements:

>>> stack = [1, 2, 3]
>>> stack.append(4)  # 4 on stack
... print(stack)
[1, 2, 3, 4]

>>> stack.pop()  # 4 Out of Stack
... stack.pop()  # 3 Out of Stack
... print(stack)
[1, 2]


Queues are first-in-first-out and can be queued using lists, even if append(e) is used to end the queue and pop(0) is used to queue the header elements. However, pop(0) is a time-consuming operation (other elements must move one bit forward), so lists are not recommended.

Enabling the best use of queues collections.deque Can quickly add or remove elements from both ends (double-ended queue):

  • append(): Enter the team from the right
  • appendleft(): Enter the team from the left
  • popleft(): queue from left
  • pop(): queue from right
>>> from collections import deque
... myDeque = deque([1, 2, 3])
... print(myDeque)
... myDeque.append(4)  # 4 Enter the End of the Team
... print(myDeque)
... myDeque.popleft()  # 1 Out of the Team
... print(myDeque)
deque([1, 2, 3])
deque([1, 2, 3, 4])
deque([2, 3, 4])

Tags: Python Deep Learning

Posted on Wed, 01 Dec 2021 15:10:37 -0500 by Cynix