当前位置:网站首页>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 :
边栏推荐
- Leetcode daily question solution: 540 A single element in an ordered array
- Find a line in a file and remove it
- Global and Chinese markets of polyimide tubes for electronics 2022-2028: Research Report on technology, participants, trends, market size and share
- 第一章:递归求n的阶乘n!
- 7. Data broker presentation
- Utilisation de base du cadre unitest
- Class loading process
- Global and Chinese market of liquid antifreeze 2022-2028: Research Report on technology, participants, trends, market size and share
- 第一章: 舍罕王失算
- 2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
猜你喜欢

FPGA 学习笔记:Vivado 2019.1 工程创建

第一章:求奇因数代数和,求同吗小数和s(d, n),简化同码小数和s(d, n),拓广同码小数和s(d, n)

2022 Xinjiang latest construction eight members (standard members) simulated examination questions and answers

Xctf attack and defense world crypto master advanced area olddriver

FPGA learning notes: vivado 2019.1 project creation

Acquisition and transmission of parameters in automatic testing of JMeter interface

IPv6 experiment

原生表格-滚动-合并功能

Part 28 supplement (XXVIII) busyindicator (waiting for elements)

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
随机推荐
Pat grade B 1009 is ironic (20 points)
PR 2021 quick start tutorial, how to create new projects and basic settings of preferences?
5. MVVM model
Popularize the basics of IP routing
Use of aggregate functions
第一章:递归求n的阶乘n!
Global and Chinese market of liquid antifreeze 2022-2028: Research Report on technology, participants, trends, market size and share
Chapitre 1: le roi de shehan a mal calculé
BOC protected amino acid porphyrins TAPP ala BOC, TAPP Phe BOC, TAPP Trp BOC, Zn · TAPP ala BOC, Zn · TAPP Phe BOC, Zn · TAPP Trp BOC Qiyue
Chapter 1: extend the same code decimal sum s (D, n)
QT tutorial: signal and slot mechanism
Point cloud data denoising
Global and Chinese market of charity software 2022-2028: Research Report on technology, participants, trends, market size and share
Part 28 supplement (XXVIII) busyindicator (waiting for elements)
Teach you how to quickly recover data by deleting recycle bin files by mistake
Day11 ---- 我的页面, 用户信息获取修改与频道接口
Nacos usage of micro services
IPv6 experiment
About unregistered transfer login page
2022-06-30 网工进阶(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
https://www.njcie.com/python/