1 pets = ['dog','cat','dog','goldfish','cat','rabbit','cat'] 2 print(pets) 3 for pet in pets: 4 print(pet) 5 #------------------------------------------ 6 pets = ['dog','cat','dog','goldfish','cat','rabbit','cat'] 7 print(pets) 8 while pet in pets: 9 print(pet)
上述代碼都想打印列表中的所有元素:
1-4行的代碼,采用for結構進行打印,無問題
6-9行代碼,采用while結構進行打印卻會報錯。報錯的原因是pet未定義
c語言中for循環和while的作用可以完全一樣。但在Python中,卻不同,第六行代碼顯示 pet未定義,思考while執行的邏輯,我們可以得出結論:while更強調:while a ,如果a 邏輯正確,則循環執行下列語句,因此,while的核心在於:while a ,其中a=True.則下列語句在a=True的條件下循環執行。
因此,pet是未被定義的“變量",因此無法判斷邏輯的正確性。因此while 后面跟的語句,一定是邏輯可判斷True或者False的才能執行。
