当前位置:网站首页>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 :
边栏推荐
- [Yu Yue education] basic reference materials of manufacturing technology of Shanghai Jiaotong University
- 2022-06-28 网工进阶(十三)IS-IS-路由过滤、路由汇总、认证、影响ISIS邻居关系建立的因素、其他命令和特性
- PR 2021 quick start tutorial, how to create new projects and basic settings of preferences?
- Chapter 1: recursively find the factorial n of n!
- BOC protected alanine porphyrin compound TAPP ala BOC BOC BOC protected phenylalanine porphyrin compound TAPP Phe BOC Qi Yue supply
- 第二章:求长方体数组,指定区间内的完全数,改进指定区间内的完全数
- 2022 Xinjiang latest construction eight members (standard members) simulated examination questions and answers
- Make a simple text logo with DW
- Day10 ---- 强制登录, token刷新与jwt禁用
- Acquisition and transmission of parameters in automatic testing of JMeter interface
猜你喜欢

PR 2021 quick start tutorial, how to create a new sequence and set parameters?

2022-06-30 网工进阶(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】

Geek Daily: the system of monitoring employees' turnover intention has been deeply convinced off the shelves; The meta universe app of wechat and QQ was actively removed from the shelves; IntelliJ pla

PR 2021 quick start tutorial, material import and management

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

Chapter 2: find the box array, complete number in the specified interval, and improve the complete number in the specified interval

Chapter 1: seek common? Decimal and S (D, n)

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

2022-07-02 advanced network engineering (XV) routing policy - route policy feature, policy based routing, MQC (modular QoS command line)

Nerfplusplus parameter format sorting
随机推荐
Read the paper glodyne global topology preserving dynamic network embedding
第一章:拓广同码小数和s(d, n)
2022-06-30 网工进阶(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
About callback function and hook function
Professional interpretation | how to become an SQL developer
Gym welcomes the first complete environmental document, which makes it easier to get started with intensive learning!
Detailed explanation of shuttle unity interworking principle
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
Global and Chinese markets for medical temperature sensors 2022-2028: Research Report on technology, participants, trends, market size and share
Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520
Chapter 1: find the factorial n of n!
Chapter 1: sum of three factorials, graph point scanning
Strict data sheet of new features of SQLite 3.37.0
Commands related to files and directories
PR 2021 quick start tutorial, how to create a new sequence and set parameters?
Network security Kali penetration learning how to get started with web penetration how to scan based on nmap
2022 - 06 - 30 networker Advanced (XIV) Routing Policy Matching Tool [ACL, IP prefix list] and policy tool [Filter Policy]
4. Data splitting of Flink real-time project
Global and Chinese market of two in one notebook computers 2022-2028: Research Report on technology, participants, trends, market size and share
P5.js development - setting
https://www.njcie.com/python/