pycharm常用debug按鈕:
Show Execution Point(Alt + F10):跳轉到代碼執行位置
Step Over(F8):執行當前代碼,但是不會進入函數
Step into(F7):執行當前代碼,會進入函數(包括源碼)
Step Into my Code(Alt + shift + F7):執行當前代碼,會進入函數(僅包括自己寫的代碼)
Step out(shift + F8):跳出函數體
例子:
玩家輸入剪刀石頭布與機器人PK,自動輸出結果
兩個函數,mian執行函數,computer電腦函數,源碼如下:
main.py
from computer import Robot,Calculate if __name__ == '__main__': person_put = int(input("請輸入1=剪刀, 2=石頭, 3=布\n")) robot = Robot() robot_put = robot.run() calculate = Calculate(person_put,robot_put) result = calculate.result() print("robot is %d, result is %s" %(robot_put,result))
computer.py
import random class Robot(object): def __init__(self): self.robot_putlist = [1,2,3] #1=剪刀,2=石頭,3=布 def run(self): return random.choice(self.robot_putlist) class Calculate(object): def __init__(self,person_put,robot_put): self.person_put = person_put self.robot_put = robot_put def result(self): if (self.person_put == 1 and self.robot_put == 1) or ( self.person_put == 2 and self.robot_put == 2) or ( self.person_put == 3 and self.robot_put == 3): return "draw" elif (self.person_put == 1 and self.robot_put == 2) or ( self.person_put == 2 and self.robot_put == 3) or ( self.person_put == 3 and self.robot_put == 1): return "lose" elif (self.person_put == 1 and self.robot_put == 3) or ( self.person_put == 2 and self.robot_put == 1) or ( self.person_put == 3 and self.robot_put == 2): return "win" else: return "null"
debug步驟:
1.debug前打斷點,點擊代碼左側,生成紅點
2. debug代碼,右鍵main.py空白處,或者if __name__ == "main"旁邊的小三角形
3. debug后,代碼會執行到斷點處,因為前一句是input,所有需要先在控制台輸入
此時斷點行顯示藍色,藍色代表未執行,處於當前位置
4.1 這時可以進行調試,如F7,則執行此代碼,並進入函數
4.2 也可以使用F7,不進入函數,直接獲取返回結果,到下一句代碼處
5. 依次執行后,也可以在控制台variables查看變量的變化