当前位置:网站首页>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 = 1
This 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.76
Similar 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 = True
Be 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 = 0
The 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 :
边栏推荐
- 2. Template syntax
- 10 smart contract developer tools that miss and lose
- What is the difference between a kill process and a close process- What are the differences between kill process and close process?
- 原生表格-滚动-合并功能
- Implementation of stack
- 4. Data binding
- [effective Objective-C] - block and grand central distribution
- Explore the internal mechanism of modern browsers (I) (original translation)
- 47. Process lock & process pool & Collaboration
- Microservice knowledge sorting - search technology and automatic deployment technology
猜你喜欢
2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
Change deepin to Alibaba image source
第二章:求a,b的最大公约与最小公倍数经典求解,求a,b的最大公约与最小公倍数常规求解,求n个正整数的的最大公约与最小公倍数
2022-07-02 advanced network engineering (XV) routing policy - route policy feature, policy based routing, MQC (modular QoS command line)
Use of aggregate functions
原生表格-滚动-合并功能
Promethus
PR 2021 quick start tutorial, material import and management
FAQs for datawhale learning!
随机推荐
What is the difference between a kill process and a close process- What are the differences between kill process and close process?
Global and Chinese market of charity software 2022-2028: Research Report on technology, participants, trends, market size and share
[raid] [simple DP] mine excavation
February 14-20, 2022 (osgear source code debugging +ue4 video +ogremain source code transcription)
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
第一章:求同吗小数和s(d, n)
BOC protected alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC supplied by Qiyu
Detailed explanation of shuttle unity interworking principle
2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
PR 2021 quick start tutorial, how to create new projects and basic settings of preferences?
Explore the internal mechanism of modern browsers (I) (original translation)
原生表格-滚动-合并功能
Micro service knowledge sorting - cache technology
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
Chapitre 1: le roi de shehan a mal calculé
Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system
第二章:求长方体数组,指定区间内的完全数,改进指定区间内的完全数
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
JMeter connection database
Chapter 1: find the factorial n of n!