当前位置:网站首页>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/825293
https://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 :
边栏推荐
- 5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
- 2022-07-02 advanced network engineering (XV) routing policy - route policy feature, policy based routing, MQC (modular QoS command line)
- Ruby replaces gem Alibaba image
- Gym welcomes the first complete environmental document, which makes it easier to get started with intensive learning!
- Cross compile opencv with contrib
- 2022-06-27 网工进阶(十二)IS-IS-开销类型、开销计算、LSP的处理机制、路由撤销、路由渗透
- Utilisation de base du cadre unitest
- Bright purple crystal meso tetra (4-aminophenyl) porphyrin tapp/tapppt/tappco/tappcd/tappzn/tapppd/tappcu/tappni/tappfe/tappmn metal complex - supplied by Qiyue
- Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
- How to check the permission to write to a directory or file- How do you check for permissions to write to a directory or file?
猜你喜欢

10 smart contract developer tools that miss and lose

Promethus

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

Commands related to files and directories

01 - QT OpenGL display OpenGL window

The 15 year old interviewer will teach you four unique skills that you must pass the interview

05 -- QT OpenGL draw cube uniform

Upgrade PIP and install Libraries

44. Concurrent programming theory

2022-06-27 advanced network engineering (XII) IS-IS overhead type, overhead calculation, LSP processing mechanism, route revocation, route penetration
随机推荐
44. Concurrent programming theory
Day10 -- forced login, token refresh and JWT disable
Chapitre 1: le roi de shehan a mal calculé
P5.js development - setting
PR 2021 quick start tutorial, how to create new projects and basic settings of preferences?
第一章:简化同码小数和s(d, n)
第二十章:y= sin(x)/x,漫步坐标系计算,y= sin(x)/x 带廓幅图形,奥运五环,小球滚动与弹跳,流水显示,矩形优化裁剪,r个皇后全控nxn棋盘
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
第一章:递归求n的阶乘n!
Detailed explanation of shuttle unity interworking principle
2022 - 06 - 30 networker Advanced (XIV) Routing Policy Matching Tool [ACL, IP prefix list] and policy tool [Filter Policy]
IPv6 experiment
FAQs for datawhale learning!
Phpstudy set LAN access
Global and Chinese market of electrolyte analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
Chapter 1: seek common? Decimal and S (D, n)
2022-07-02 advanced network engineering (XV) routing policy - route policy feature, policy based routing, MQC (modular QoS command line)
第二章:基于分解的求水仙花数,基于组合的求水仙花数, 兰德尔数,求[x,y]内的守形数,探求n位守形数,递推探索n位逐位整除数
Use of aggregate functions
Derivation of decision tree theory