Self-study Python in 20 days with no basic knowledge | Day4 Variables

Hello everyone, my name is Ning Yi.

Later, whether we are building a website or doing data analysis, we will have to process a variety of data, such as names, birthdays, scores, etc.

Variables are the names we give these data.

1. Define variables

For example, if we use variables to define a student's name and grades, we can write it like this.

name = "宁一"
score = 100

In python, variables can be defined directly without declaring the variable type in advance. In this way we define two variables name and score.

Print the variables we defined and the corresponding data will be output.

print(name)
宁一   # 输出

It should be noted here that variables must be defined before using them, otherwise an error will be reported.

For example, let's print out the undefined variable str_name:

print(str_name)
# 报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'str_name' is not defined

2. Variable naming rules

The variable names we defined above can also be given other names. For example, the name variable above can be changed to name1 or str_name.

Variable names can only consist of letters, numbers, and underscores. The following basic rules must be observed:

  • It cannot start with a number, but must start with a uppercase or lowercase letter or an underscore;
  • Variable names are case-sensitive, name and Name are different;
  • It is simple and easy to read. For example, the name variable we defined above can be easily understood by others reading the code as a name. However, if it is named a, although an error will not be reported, it is not very standardized.

Interview questions:

The following variable names are incorrect ()

A、name1

B、1name

C、MINT_1

D、_name

Answer: B, variable names cannot start with numbers.

3. Multiple variable assignment

Python also allows us to assign values ​​to multiple variables at the same time.

For example, if you define three variables score1, score2, and score3 at the same time and assign them a value of 100, you can write them like this:

score1 = score2 = score3 = 100

You can also define multiple variables and assign values ​​separately.

For example, if you define three variables name1, name2, and name3 at the same time and assign them to "Ning Yi", "Ning Er", and "Ning San" respectively, you can write:

name1, name2, name3 = "宁一", "宁儿", "宁散"

Guess you like

Origin blog.csdn.net/shine_a/article/details/126319064