当前位置:网站首页>2.1 use of variables
2.1 use of variables
2022-07-03 19:59:00 【leeshuqing】
The use of variables is like naming you . In data analysis , We need to process a lot of data , But the data itself is not easy to remember , And there are a lot of the same data , For example, two identical height data . So for the convenience of , We can give these different data different names .

stay Python In language , The variable definition method is very simple , Is the variable name plus the initial value assigned to .
num = 1This means that a variable is defined , The name is num, Its initial value is 1. As you can imagine , We put 1 This integer is put into a called num Drawers . Relative to variables , This 1 We call it a constant . therefore , The initial value of variables can generally be set through constants .

Many beginners feel very twisted , I think why the variable assignment uses the equal sign ? These are actually habits , Some computer languages adopt such as “:=” Methods such as . This is why you need to practice more , You will get used to it after more practice .
It is called constant , Because 1 Cannot be changed , If it changes , That becomes another constant , Unlike variables , Different values can be stored as needed .
num = 1
print(num)
num = 2
print(num)
The operation interface is :

The second output of the program is 2, Express num The value of the variable has been assigned to 2 Has been changed , The original 1 Has been lost , The value of the variable has changed .
Another example is that we define two heights :
height1 = 1.80
height2 = 1.76Similar to just now , Just this time we put a decimal into the variable . Decimals are sometimes called floating point numbers , The reason is English decimal float It also means floating .
ad locum , Although there are all kinds of data , But in Python There are not many common types of data in , Except integers and decimals , Another common one is character type , Also called string . We have also explained to you before :
name = ' College students' 'Please note that , String constants need to be preceded by single quotation marks or double quotation marks , Otherwise, and variable name ( The variable name can be regarded as a string without single quotation marks , stay Python It only indicates special purposes such as variable name and function name ) It's hard to distinguish , And then there are problems .
There are also Booleans , That is, the variables represented by true and false .
isStudent = TrueBe careful , there True It must be written strictly in case , Said really , Use False Said the false . These special names represent the two constants true and false .
Many students like to use Chinese input , But almost all computer languages stipulate that except variable names and string constants , All symbols need to use English half width characters , Please pay attention to switching input methods in time . For example, the equals sign here is actually Chinese full angle , Run prompt illegal characters :

At the same time, pay attention to the difference between case !
num = 0
print(NUM)
The operation interface is :

The error prompt says NUM No definition (not defined), Because uppercase and lowercase are treated as different variable names .
There is also a common beginner's mistake , Just use it first ( Read ) Variable , Then define ( Or the variable has not been assigned at all )
print(num)
num = 0The operation interface is :

At this time, the running error still indicates num No definition . It makes sense , If possible , Excuse me, the first line num What is the value ? After all, it has not been assigned . therefore , Variables can only be used if they are created first , Not yet created , Of course not . General creation , In fact, it's assignment , That is, assign values first and then , Can be used . It's like saving money before withdrawing it .
Variable names cannot be arbitrarily named , It is generally recommended to use letters 、 Numbers and underscores , At the same time, don't start with a number . in addition , Some special names are in Python It has a special purpose , We call it keyword or reserved word ( Later, we will continue to contact ), Don't use them as variable names , Such as :

For example, there is a problem with this code ,for Cannot be the name of a variable :

The previous article has explained when to define variables , If you need to use a data repeatedly , Or if you need to use the same data in different places , Then you should define variables , And save this data .
Let's do an exercise , Let the user enter two numbers , Add it up and output :
num1 = input()
num2 = input()
print(num1 + num2)
The reason why two variables are defined here , Just to store two different inputs . In the operation interface , I have entered 1 and 2 Two figures :

But do you think there is a problem ? Actually , This is not a mistake . By default ,input Only strings can be entered , For Strings , The plus sign means connection , Of course 1+2=12.
In order to be able to calculate integers in a real sense , We have to convert data types :
num1 = input()
num2 = input()
print(int(num1) + int(num2))Here we use int function , It means converting a string to an integer . Here we notice that we put num1 and num2 We separate int In parentheses after the function .
Function represents a function , Generally, if there is nothing in parentheses , Its functions are often fixed . But if you pass data inside , As an argument to a function , The function will show different results according to the different parameter data passed . For example, the string passed in can be converted to the corresponding integer . The data in parentheses can be variables , It can also be a constant .
Many functions have parameters , such as :
num1 = input(' please enter an integer 1:')
num2 = input(' please enter an integer 2:')
print(int(num1) + int(num2))
At this time input With string parameters , This prompt message can be automatically displayed before input , better . The operation interface is :

Actually , At this time print Functions also have parameters , Is the sum of two integers , So the parameters are different every time , The output results are different .
Let's put it another way :
num1 = int(input(' please enter an integer 1:'))
num2 = int(input(' please enter an integer 2:'))
print(num1 + num2)This effect is actually the same , But there are also differences . Notice that , here int The function is to input The function inputs the string obtained as its own parameter , The return is the corresponding integer , therefore ,num1 and num2 It always stores integers .
In the code just now ,num1 and num2 It's always a string , It is not temporarily converted to an integer until output . therefore , The difference between the two is mainly reflected in the different data types of variables . You must always pay attention to the data type of variables . meanwhile , For questions like this , Since we want to num1 and num2 Express integer , It is better to convert it to an integer immediately after accepting the input , This can avoid many unnecessary temporary data conversion later .
Of course , It is also possible to write in a separate way :
num1 = input(' please enter an integer 1:')
num1 = int(num1)
num2 = input(' please enter an integer 2:')
num2 = int(num2)
print(num1 + num2)here , First line num1 It's a string , But the second line becomes an integer . No problem with that ,Python Variables are very flexible , What to store , What kind of variable is .
Of course , The definition of variables can also be flexibly selected according to needs :
num1 = int(input(' please enter an integer 1:'))
num1 = num1 + int(input(' please enter an integer 2:'))
print(num1)This code defines only one variable , It realizes the same function as just now . The key here is the second line . First , We must not understand the assignment method of adopting the equal sign according to the equality judgment of Traditional Mathematics , It's just an assignment mark , The second line means to num1 out , At this point, it should be the result of converting an integer after the first input , Then let the user input a string and convert it to an integer , Add the two together , And put it back in again num1 in , obviously ,num1 The final integer addition result is still saved .
But because we only use one variable , Therefore, the integer entered for the first time is lost after accumulation , So this also reflects the value of variable definition again , If you still need to use two different input data later , Then you should create variables separately to save .
For multiple variables , We can also use some simpler assignment methods :
num1, num2 = 1, 2
print(num1, num2)It is equivalent to :
num1 = 1
num2 = 2
print(num1, num2)
For num1 and num2 Assignment , Is to assign two constants to two variables respectively ,print The output of the function using commas also means that two variables are output , Default space separation .
Sometimes some interesting functions can be realized by using this writing method :
num1, num2 = 1, 2
num1, num2 = num2, num1
print(num1, num2)The operation interface is :

Output is 2 1, Using this method, the exchange between the values of different variables can be realized .
Of course, for the exchange of variable values , We can also use other variable transfer methods to achieve :
num1, num2 = 1, 2
num3 = num1
num1 = num2
num2 = num3
print(num1, num2)The output is 2 1. You can think about the specific numerical exchange process by yourself . Here is a diagram , You can think about it yourself :

Supporting learning resources 、 MOOC video :
边栏推荐
- BOC protected phenylalanine zinc porphyrin (Zn · TAPP Phe BOC) / iron porphyrin (Fe · TAPP Phe BOC) / nickel porphyrin (Ni · TAPP Phe BOC) / manganese porphyrin (Mn · TAPP Phe BOC) Qiyue Keke
- 02 -- QT OpenGL drawing triangle
- Ae/pr/fcpx super visual effects plug-in package fxfactory
- Day11 - my page, user information acquisition, modification and channel interface
- Cross compile opencv with contrib
- Native table - scroll - merge function
- Chapter 20: y= sin (x) /x, rambling coordinate system calculation, y= sin (x) /x with profile graphics, Olympic rings, ball rolling and bouncing, water display, rectangular optimization cutting, R que
- Virtual machine installation deepin system
- Derivation of decision tree theory
- 第一章: 舍罕王失算
猜你喜欢

Point cloud data denoising

第一章:求同吗小数和s(d, n)

Ae/pr/fcpx super visual effects plug-in package fxfactory

CMD implements the language conversion of locale non Unicode programs

Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation

Chapter 1: seek common? Decimal and S (D, n)
![Chapter 2: find the number of daffodils based on decomposition, find the number of daffodils based on combination, find the conformal number in [x, y], explore the n-bit conformal number, recursively](/img/c5/0081689817700770f6210d50ec4e1f.png)
Chapter 2: find the number of daffodils based on decomposition, find the number of daffodils based on combination, find the conformal number in [x, y], explore the n-bit conformal number, recursively

2022-06-25 advanced network engineering (XI) IS-IS synchronization process of three tables (neighbor table, routing table, link state database table), LSP, cSNP, psnp, LSP

Make a simple text logo with DW

Chapter 1: sum of three factorials, graph point scanning
随机推荐
CMD implements the language conversion of locale non Unicode programs
Day10 -- forced login, token refresh and JWT disable
PR notes:
unittest框架基本使用
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
About unregistered transfer login page
6. Data agent object Defineproperty method
Acquisition and transmission of parameters in automatic testing of JMeter interface
Cross compile opencv with contrib
Rad+xray vulnerability scanning tool
2022-07-02 网工进阶(十五)路由策略-Route-Policy特性、策略路由(Policy-Based Routing)、MQC(模块化QoS命令行)
2022-06-28 advanced network engineering (XIII) IS-IS route filtering, route summary, authentication, factors affecting the establishment of Isis neighbor relations, other commands and characteristics
Nerfplusplus parameter format sorting
Typora charges, WTF? Still need support
2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
BOC protected alanine porphyrin compound TAPP ala BOC BOC BOC protected phenylalanine porphyrin compound TAPP Phe BOC Qi Yue supply
Point cloud data denoising
Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
交叉编译Opencv带Contrib
Unittest framework is basically used
https://www.njcie.com/python/