Python idle отладка программ

Борьба с багами

Следующий код определяет функцию add_underscores(), принимающую в качестве аргумента строковый объект и возвращающую новую строку – копию слова с каждым символом, окруженным подчеркиванием. Например, add_underscores(«python») вернет «_p_y_t_h_o_n_» .

🐍 Найдите и исправьте ошибки в коде на Python: отладка с IDLE

Запустим. Выполнение останавливается на строке с определением функции.

Нажмите кнопку Go, чтобы выполнить код до точки останова:

🐍 Найдите и исправьте ошибки в коде на Python: отладка с IDLE

Код останавливается перед циклом for в функции add_underscores(). Обратите внимание, что на панели Locals отображаются две локальные переменные – word со значением «hello», и new_word со значением «_»,

Нажмите кнопку Step, чтобы войти в цикл for. Окно отладки изменится, и новая переменная i со значением 0 отобразится на панели Locals:

🐍 Найдите и исправьте ошибки в коде на Python: отладка с IDLE

Переменная i – это счетчик для цикла for, который можно использовать, чтобы отслеживать активную на данный момент итерацию.

Нажмите кнопку Step еще раз и посмотрите на панель Locals – переменная new_word приняла значение «h_»:

🐍 Найдите и исправьте ошибки в коде на Python: отладка с IDLE

Это неправильно т. к. сначала в new_word было значение «_», на второй итерации цикла for в ней должно быть «_h_». Если нажать Step еще несколько раз, то увидим, что в new_word попадает значение e_, затем l_ и так далее.

Шаг 3: Определение ошибки и исправление

Как мы уже выяснили – на каждой итерации цикла new_word перезаписывается следующим символом в строке «hello» и подчеркиванием. Поскольку внутри цикла есть только одна строка кода, проблема должна быть именно там:

Код указывает Python получить следующий символ word, прикрепить подчеркивание и назначить новую строку переменной new_word. Это именно то неверное поведение, которое мы наблюдали.

Чтобы все починить, нужно объединить word[i] + » _» с существующим значением new_word. Нажмите кнопку Quit в окне отладки, но не закрывайте его. Откройте окно редактора и измените строку внутри цикла for на следующую:

new_word = new_word + word[i] + "_" 

Примечание: Если бы вы закрыли отладчик, не нажав кнопку Quit, при повторном открытии окна отладки могла появиться ошибка:

You can only toggle the debugger when idle

Всегда нажимайте кнопку Go или Quit, когда заканчиваете отладку, иначе могут возникнуть проблемы с ее повторным запуском.

Шаг 4: повторение шагов 1-3, пока ошибка не исчезнет

Сохраните изменения в программе и запустите ее снова. В окне отладки нажмите кнопку Go, чтобы выполнить код до точки останова. Понажимайте Step несколько раз и смотрите, что происходит с переменной new_word на каждой итерации – все работает, как положено. Иногда необходимо повторять этот процесс несколько раз, прежде чем исправится ошибка.

Читайте также:  Create an icon html

Альтернативные способы поиска ошибок

Использование отладчика может быть сложным и трудоемким, но это самый надежный способ найти ошибки в коде. Однако отладчики не всегда есть в наличии. В подобных ситуациях можно использовать print debugging для поиска ошибок в коде. PD задействует функцию print() для отображения в консоли текста, указывающего место выполнения программы и состояние переменных.

Например, вместо отладки предыдущего примера можно добавить следующую строку в конец цикла for:

Измененный код будет выглядеть следующим образом:

def add_underscores(word): new_word = "_" for i in range(len(word)): new_word = word[i] + "_" print(f"i = ; new_word = ") return new_word phrase = "hello" print(add_underscores(phrase)) 

Вывод должен выглядеть так:

i = 0; new_word = h_ i = 1; new_word = e_ i = 2; new_word = l_ i = 3; new_word = l_ i = 4; new_word = o_ o_ 

PD работает, но имеет несколько недостатков по сравнению с отладкой дебаггером. Вы должны запускать всю программу каждый раз, когда хотите проверить значения переменных, а также помнить про удаление вызовов функций print().

Один из способов улучшить наш цикл – перебирать символы в word:

def add_underscores(word): new_word = "_" for letter in word: new_word = new_word + letter + "_" return new_word 

Заключение

Теперь вы знаете все об отладке с помощью DLE. Вы можете использовать этот принцип с различными дебагерами.

В статье мы разобрали следующие темы:

  • использование окна управления отладкой;
  • установку точки останова для глубокого понимания работы кода;
  • применение кнопок Step, Go, Over и Out;
  • четырехэтапный процессом выявления и удаления ошибок.

Не останавливайтесь в обучении и практикуйте дебаггинг – это весело!

Источники

Источник

Python idle отладка программ

IDLE has a debugger built into it. It is very useful for stepping through a program and watching the variables change values.

Start IDLE and open this program source file.

In the Shell window, click on the Debug menu option at the top and then on Debugger. You will see a «Debug Control» window like this

Notice that the Shell shows «[DEBUG ON]».

For the debugger to be most useful, you need to set a breakpoint in your source code before you start running the program. A breakpoint is a marker on your code that tells the debugger «run to this point at normal speed, then pause and let the human have control». You can have many of them; in more complex programs you would need them at different places. RIGHT click on a line of your source and choose «set breakpoint».

The background of the line you click on turns yellow to show the line marked with the breakpoint.

Читайте также:  Etoken pro java 72kb

If you don’t put any breakpoints in your source, when you run it with the debugger on, it will pause at the first line of executable code (may be an import statement or a call to main()) but then will run your program normally (i.e. with no pauses).

Now run the program with F5 as usual.

Note that the Debug Control window is opened and that the blue line states that the line «from math import pi» is ready to be executed (the 7 is for line number 7 in the source file).

From this point you can click the Go button near the top of the window. This will make the program run at normal speed until a breakpoint is encountered (or input is requested or the program finishes). You can also use the Step button to step through your code, one line at a time. This button is used quite a lot. If the line being stepped through has a function call, execution will go to the first line of the function definition (you are «stepping into» the function). If the line being stepped through doesn’t have a function call, the line is executed. In either case, then control goes back to the human.

When you execute a line that has input in it, the debugger seems to shut down but it has not. If you bring up the Shell window you can see that the program is waiting for input. Make sure your cursor is in the right place on the window and give it some input and press Enter as usual.

There are several things to note about this picture. The Shell window is in the background, it shows that the user entered 23 and pressed Enter. The Debug Control window shows that execution has moved on to the next line of code. Also, at the bottom of that window there is a pane that says «Locals» and it shows the value of radius to be ’23’. This is useful in several ways. It shows the values of variables as they change, and it shows the types of variables. Note that the value of radius has quotes around it. This means that it is a string value.

Click the Step button again.

Note that the new variable height has been created and has a value of ’14’.

Click the Step button again.

Читайте также:  Open jpg file in php

Notice that there is an error in the run of the program at this point (the yellow bar in the Debug Control window). The interpreter is saying that it cannot multiply «sequence by non-int of type ‘float'». What it means is that the two input variables are of the wrong type to be combined with numeric types. This has to be corrected before any more debugging takes place. This is fixed by using the eval function in the two input statements.

«You can only toggle the debugger when idle» If you get this message in a window when you try to turn the debugger on, try clicking on the Quit button in the Debug Control window. If that does not help, try shutting down the program file and reopening it. If that does not help, shut down Python completely and restart it from scratch.

Note that the bugs in the input statements have been fixed with the addition of «eval». The breakpoint was put in again. Breakpoint locations are not saved with the program; they have to be set again for every debugging session.

Note the type of the Local variables in this image. They don’t have the quotes around the values any more! They are numbers now.

As you step through the program one statement at a time, you can see more variables get values. When we come to the next bug you can see that the variable Pi is not the same as the variable pi, which is defined in the math library. This bug would need to be fixed, then the debugging would continue.

  • setting breakpoints
  • stepping through the source code one line at a time
  • inspecting the values of variables as they change
  • making corrections to the source as bugs are found
  • rerunning the program to make sure the fixes are correct
  • Over means that if the statement to be executed has a function call in it, go off and do the function call without showing any details of the execution or variables, then return and give the human control again, «step over the function»
  • Out assumes you are in some function’s code, finish execution of the function at normal speed, return from the function and then give the human control again, «step out of the function»
  • Quit stops the execution of the entire program

Источник

Оцените статью