current position:Home>Chapter 2: Fundamentals of python-2 variable

Chapter 2: Fundamentals of python-2 variable

2022-01-30 07:08:01 Small horn

Python Variable

The goal is

In this article , You will understand Python Variables and how to use them effectively .

Python What are the variables in

When you develop a program , You need to manage a lot of values . To store values , You can use variables .

stay Python in , A variable is a label , You can assign a value to it . Variables are always associated with values . for example :

message = ' Hello , The world !'

message = ' Bye-bye !'
 Copy code 

Output :

 Hello , The world !
 Bye-bye !
 Copy code 

In this case ,message It's a variable . It holds the string ' Hello , The world !'. The delta function is going to be : Show Hello , The world ! Go to the screen .

The assignment string on the next line Good Bye! To variable message, And print its value to the screen .

Variable message You can save different values at different times . Its value can be changed throughout the program .

Create variables

To define a variable , You can use the following syntax :

 Variable name  =  value 
 Copy code 

= Is the assignment operator . In this grammar , You assign a value to Variable name .

The value can be a number , A string , wait , You can assign values to variables .

Here is a definition called counter The variable of , And number 1 Give it :

counter = 1
 Copy code 

Named variable

When naming variables , Some rules need to be observed . If you don't do that , You get a mistake .

Here are the variable rules you should remember :

  • Variable names can only contain letters 、 Numbers 、 Underline . They can be in letters or underscores (_) start , Not Numbers .
  • Variable names cannot contain spaces . To separate words in variables , You can use underscores , for example sorted_list.
  • Variable names cannot be associated with Python Keywords in 、 Reserved words are the same as built-in functions .

The following guidelines can help you define variable names :

  • Variable names should be concise and descriptive . for example ,active_user Variable ratio au More descriptive .
  • Use underline (_) Separate multiple words in variable names .
  • Avoid using letters l And capital letters O, Because they look like numbers 1 and 0.


  • A variable is a label , You can assign a value to it . The value of a variable can be changed throughout the program .
  • Use Variable name = value Create a variable .
  • Variable names should be as concise and descriptive as possible . Besides , They should abide by Python Variable naming rule .

copyright notice
author[Small horn],Please bring the original link to reprint, thank you.

Random recommended