Variables in Python

1. Creation and assignment of variables

In Python programs, variables are represented by a variable name, which can be any data type. The variable name must be in uppercase and lowercase English and numbers. A combination with an underscore (_), and cannot start with a number, for example:

a=88

The a here is a variable, representing an integer. Note that Python does not need to declare a data type. = is an assignment statement in Python, the same as in other programming languages, because Python does not need to declare a data type when defining a variable, so any data type can be assigned to a variable, and the same variable can be assigned repeatedly, and it can be different data types.

5d3cd4b4aaf842ca2132b5f7235d49b.png This kind of language whose variable type is not fixed is called a dynamic language, and its counterpart is a static language. In static languages, the variable type must be specified when defining a variable. If the type does not match when assigning a value, an error will be reported. For example, Java is a static language.

2. Variable pointing problem

Let’s take a look at this code and find that the last printed variable b is Hello Python.

adde20adc408455ae1d0cf403c7b3cf.png

This is mainly because variable a initially points to the string Hello Python, b=a creates variable b, and variable b also points to the string Hello Python pointed to by a. , and finally a=123, redirecting variable a to 123, so the final output variable b is the pointer to the Hello Python

variable

3. Multiple variable assignment

Python allows assigning values ​​to multiple variables at the same time. For example:

a = b = c = 1

In the above example, an integer object is created with a value of 1, and three variables are allocated to the same memory space.

Of course, you can also specify multiple variables for multiple objects. For example:

a, b, c = 1, 2, "liangdianshui"

In the above example, two integer objects 1 and 2 are assigned to variables a and b, and the string object "liangdianshui" is assigned to variable c.

Continuing Learning
||
submitReset Code