通常我們寫程式會有兩種 Debug 的方法:
這篇文章主要會介紹第 2 種,如何使用 IDE 附帶的 Debugger 來為你的程式除錯。我們使用的 IDE 是 Spyder3。
上面這張圖是 Sypder 打開時可能長的樣子。有幾個區塊要特別注意:
通常我們需要 Debug 的時候都是程式最後跑出來的結果不符合我們的預期,或是程式跑到一半出現問題。
所以,Debugger 提供我們以下功能:
接著介紹在 Spyder 中如何操作這些功能。
從左到右的按鈕意義分別為:
def add(a, b):
sum = a + b
return sum
x = 5
y = 3
z = add(x, y)
print(x, '+', y, '=', z)
z = add(x, y)
這行。此時如果按下 Run current line,程式會直接跳到下一行 print
的部分;但如果按 Step into function… 這個按鈕,則會進到 def add(a, b):
的函式中,可以繼續逐行執行函式內的每一行。在上圖中,有三個中斷點(breakpoint),分別在 第 19 行、第 23 行 與 第 26 行。而目前執行到 第 19 行。
中斷點設定方式:在該行的數字上,雙擊滑鼠左鍵,就會出現紅色點點。取消中斷點的方式一樣。
假設依照上圖,目前執行到 第 19 行,那麼如果我按下
此時,你可以在 Variable explorer 看到變數的值:
你可以自己親手用圖中的範例程式碼來測試:
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def calc_add(a, b):
sum = a + b
return sum
def calc_sum(a, b):
sum = 0
for i in range(a, b + 1):
sum = sum + i
return sum
x = 1
y = 100
z = 10 #nonsense, just for debugger tutorial
a = 1 #nonsense, just for debugger tutorial
b = 2 #nonsense, just for debugger tutorial
c = 3 #nonsense, just for debugger tutorial
print(calc_add(x, y))
print(calc_sum(x, y))
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing