当前位置:网站首页>1.5 learn to find mistakes first
1.5 learn to find mistakes first
2022-07-03 19:59:00 【leeshuqing】
Many beginners often think that writing code is the most difficult and can best reflect the ability to write code . Actually , That's not true . From experience , To complete a correct code function , For example, a data analysis task , Writing and editing code is often just the first step , However, due to lack of experience and some unpredictable data processing problems , It is often difficult to ensure that the written code can run correctly . At this time , We need to debug the code . This ability is very critical , It is also a skill that many beginners cannot learn directly from books .
So how to master this ability ?
First of all , We need to be familiar with the debugging functions provided by the editor , This is the most basic .
Let's take an example :
str = input()
str = str.upper()
print(Str)
Usually if there is an obvious problem , Code editor such as PyCharm There will be hints. , For example, you will notice at this time Str There is a red wavy line below . This usually indicates a problem .
And after running , The editor will also prompt specific error messages , For example, this shows Str No definition (not defined).
Didn't we define ? as a result of Python Case sensitive , It thinks Str and str It's not a variable , Of course, it will prompt that there is no definition .
But sometimes the error prompt is not obvious . For example, we want to change the input characters into uppercase and lowercase , Connect them together and output them together , Let's have a try :
str = input()
str = str.upper()
str = str.lower()
print(str + str)
But the running result is not correct , Only two words with lowercase characters are output here .
For characters , The plus sign indicates connection , So the code means to splice the upper case conversion and the lower case conversion ,lower Represents lowercase conversion . Now this kind of mistake is different from the mistake just now , It is a logical error , That is to say, the code is not incorrect , It doesn't reflect your functional requirements , It has other functions .
So how to deal with it ? The key to debugging and resolving code errors is to find the wrong location , This is the second secret we should keep in mind . This sentence can be well understood in learning .
So how do we know what went wrong ? Let's have a try .
The simpler way is to increase the output , You can try to output the value of the variable in some key positions , See if the values of these variables are your own expectations . We added two lines of output ,
str = input()
str = str.upper()
print(str)
str = str.lower()
print(str)
print(str + str)
Run as :
We can see that it is the result we want . Then we can basically conclude that the problem should be in the last line . When you notice this place , You may have noticed str At this time, all characters are lowercase , You can also infer the last one from the result in turn print One of the first str In fact, it is not the original uppercase character . The reason is that the first upper case conversion has been lost due to the second lower case conversion , After all, a variable cannot hold multiple values .
Then we will use two variables .
str = input()
str1 = str.upper()
print(str1)
str2 = str.lower()
print(str2)
print(str1 + str2)
ad locum , We are not afraid of trouble , We have established str1 and str2, Store upper case and lower case characters respectively . Here also illustrates a problem , The definition of variables is based on needs , If you need to store a value , And continue to use it in other subsequent places , Then it's time to define variables .
But this kind of writing is not very good , After more code , It's hard for us to remember str1 and str2 Which one is capital 、 Which one is lowercase . Therefore, it is better to see the name and know the meaning .
str = input()
strUppr = str.upper()
print(strUppr)
strLwr = str.lower()
print(strLwr)
print(strUppr + strLwr)
The variable name here is a common method we take , First use multiple word combinations , Pinyin is sometimes a good choice , Make the meaning of the name more clear , At the same time, in order to save unnecessary input , We made some abbreviations for all the words , such as Upper Turned into Uppr etc. .
The rule here is to keep the first letter unchanged , The vowels in the letters after the word are omitted . At the same time, these two words generally start with the second capital , Form an effect of high in the middle and low at both ends , Like a camel's hump , Therefore, it is also called camel nomenclature .
In addition to the increase we just mentioned print The function of output variables , In fact, we can also use the second more convenient breakpoint function . It's easy , Click directly in front of the code line that needs to add a breakpoint , You will see many red circles , Represents a breakpoint . Click again on the , The breakpoint will disappear .
So what is a breakpoint ? We will know by running . however , This operation cannot be the same as before , Instead, you should choose Debug.
This word means looking for the wrong , Interested students can go online to understand the past and present lives of this word , It has something to do with a bug decades ago .
https://baike.baidu.com/item/DEBUG/825293https://baike.baidu.com/item/DEBUG/825293 Still the same as before , The first commissioning run requires clicking Exec Options .
The first run is still waiting for our input , We still enter one try.
After the return confirmation , The previous code will run to the end all at once , It's all over , But at this time, after inputting , You will find that the code will stop at this breakpoint , in other words , The last line of statements after the breakpoint will not be executed for the time being , The code is interrupted here .
This is the time PyCharm A... Will appear below Debugger Panes , You can carefully observe the value of each variable , The variable and its current value will be displayed at the bottom right , Based on this, we can observe whether it meets the expectations , Just like before print Same output , It's just simpler . Careful observation shows that , At this time str Only one value , That is, lowercase “try”, uppercase “try” No more , Therefore, the last line of statements cannot output both upper and lower case str A variable's value .
Continue to click on the left side of the screen “ Continue the process ” Button , You can continue to run , Finally, all operations are finished .
Click here “Debugger” Pane to console (“Console”) Panes , You can see the final result .
Above, we introduced the basic debugging methods , Then the third important method is to put prevention first , After all, the cure is better than the cure !
For example, it is suggested that you should not write all the code in one brain , It's best to write a function , Just test it in time , This makes it easier to locate in time , Eliminate errors in time .
in addition , The writing of code itself is also very important , Good code writing habits and standardized usage are the basis for enhancing code readability , Thus, it is also helpful for code understanding and error troubleshooting . The common way here is to add necessary code comments . Comments are additional instructions that do not participate in code execution , Only code editors can read and understand the functions of the code .
The most critical one is that the ability to debug code must be exercised and learned from practice , Don't be afraid of trouble , This ability is forged bit by bit in this way , You may think how much time is wasted , But in the process , You will find that many of your problems are not clear , Little by little , And the more skilled you are , The faster you can locate errors .
Many readers like to ask others immediately when they encounter problems , No problem with that , But we suggest you check yourself first , Don't waste an opportunity to learn to debug code from practice . In a word , The ability to find errors in programming is and even more important than programming ability itself , And precisely this part must be mastered through practice .
Supporting learning resources 、 MOOC video :
边栏推荐
- Make a simple text logo with DW
- Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520
- Meso tetra [P - (p-n-carbazole benzylidene imino)] phenylporphyrin (tcipp) /eu (tcipp) [pc( α- 2-oc8h17) 4] and euh (tcipp) [pc (a-2-oc8h17) 4] supplied by Qiyue
- Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
- 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
- Chapter 1: drinking soft drinks, step tariff calculation, step tariff calculation function, personal income tax, solving square root inequality, simplifying solving square root inequality, solving dem
- Global and Chinese markets for medical temperature sensors 2022-2028: Research Report on technology, participants, trends, market size and share
- NFT without IPFs and completely on the chain?
- MPLS configuration
- 04 -- QT OpenGL two sets of shaders draw two triangles
猜你喜欢
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
Chapter 1: seek common? Decimal and S (D, n)
02 -- QT OpenGL drawing triangle
2022 Xinjiang latest road transportation safety officer simulation examination questions and answers
Kubernetes cluster builds efk log collection platform
03 -- QT OpenGL EBO draw triangle
Exercises of function recursion
BOC protected tryptophan zinc porphyrin (Zn · TAPP Trp BOC) / copper porphyrin (Cu · TAPP Trp BOC) / cobalt porphyrin (cobalt · TAPP Trp BOC) / iron porphyrin (Fe · TAPP Trp BOC) / Qiyue supply
Chapter 1: extend the same code decimal sum s (D, n)
Chapter 1: find the factorial n of n!
随机推荐
第一章:简化同码小数和s(d, n)
Today's work summary and plan: February 14, 2022
第二十章:y= sin(x)/x,漫步坐标系计算,y= sin(x)/x 带廓幅图形,奥运五环,小球滚动与弹跳,流水显示,矩形优化裁剪,r个皇后全控nxn棋盘
Nacos usage of micro services
Microservice framework - frequently asked questions
Read the paper glodyne global topology preserving dynamic network embedding
[raid] [simple DP] mine excavation
The 15 year old interviewer will teach you four unique skills that you must pass the interview
About callback function and hook function
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
HCIA-USG Security Policy
Kubernetes cluster builds efk log collection platform
Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
Bright purple crystal meso tetra (4-aminophenyl) porphyrin tapp/tapppt/tappco/tappcd/tappzn/tapppd/tappcu/tappni/tappfe/tappmn metal complex - supplied by Qiyue
2. Template syntax
NFT without IPFs and completely on the chain?
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
5. MVVM model
Exercises of function recursion
Typora charges, WTF? Still need support