[英]How to run a selective part of the Python script individually from .py file in IDLE
我剛剛開始使用Python,最近我想到了一個問題。 當我使用Python腳本保存代碼並運行代碼時,直接從腳本開始,它將始終在腳本中運行整個代碼。 我想知道是否還有其他選擇,我只能在其中運行代碼的一部分。 假設我們有以下代碼,並且我想運行代碼直到打印位於第六行的thisdict 。 但是,當我嘗試從IDLE腳本中運行此代碼時,它將運行整個代碼。 因此,請讓我知道是否還有其他解決方案可以運行整個腳本中的選擇性代碼。
thisdict={
"brand" : "Ford",
"model" : "Mustang",
"year" : 1964
}
print thisdict
#Tracing the model using the index/key named "model"
print "Model of the car:", thisdict.get("model")
#Changing the "year" to 2018 and re-printing the dictionary
thisdict["year"]=2018
print thisdict
#Print both keys and values from the dictionar
for x,y in thisdict.items():
print x,y
#Add a key and value to the dictionary
thisdict["color"]="red"
print thisdict
#To delete a keyword from the dictionary
del thisdict["color"]
print thisdict
#OR
thisdict.pop("model")
print thisdict
#To remove the last item from the dictionary
thisdict.popitem()
print thisdict
#Dist constructore for creating a dictionary
thisdict=dict(brand="Ford",model="Mustang", year=1964)
print thisdict
對於Python初學者來說,這是一個奇怪的普遍問題! 有很多修復程序。
首先,最明顯的是只注釋掉您不想運行的所有內容。 只要在您不想運行的任何行之前加上“#”,它就不會運行。 大多數編輯器允許您一次自動注釋掉整個塊。
第二種方法(更好的做法)是開始使用函數。 假設您有以下代碼:
print("HERE 1")
print("HERE 2")
有時您想同時運行兩條線,但有時您只想運行其中一條。 然后嘗試將它們置於不同的功能中。
def print_1():
print("HERE 1")
def print_2():
print("HERE 2")
現在,您只需要輸入命令(不帶縮進),即可調用所需的函數:
print_1()
您可以在函數下放置任意多的代碼。 也是僅供參考,這對您可能並不重要,但是要知道,直接運行腳本時調用函數的最佳方法是這樣的:
if __name__=="__main__":
print_1()
但是,您現在可以只編寫print_1(),而無需if名稱是主要內容。 如果您開始從其他地方導入模塊,則將是相關的。
然后,您也可以使用第三個技巧,有時我仍然在復雜的情況下執行此操作,即我不知道控制權在哪里,只想殺死程序,是這樣的:
import sys
sys.exit(0)
它將停止程序在任何地方運行。
另一種選擇是在代碼的頂部使用布爾值。
whole_program = True # or False
print("here 1")
a = 1+3
print("here 2")
if whole_program:
print("here 3")
print("something else")
else:
pass
如果您只是編寫腳本,則另一個選擇是使用Jupter筆記本,它非常適合隔離要運行的代碼部分。
哦,當然,Python是一種解釋語言。 因此,您總是可以一次直接在控制台中一次運行一個命令!
最終,您應該開始學習使用函數,然后學習類,因為這些是控制程序流所需要使用的基本結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.