Python中遍歷整個列表及注意點(參考書籍Python編程從入門到實踐)


1. 利用for循環遍歷整個列表

magicians = ['alice', 'dsvid', 'carolina']
# 遍歷整個列表
for magician in magicians:
    print(magician)

2. 使得打印結果變得更加有實際意義

for magician in magicians:
    print(magician.title() + ', that was a great trick!')

運行結果:

 
        
Alice, that was a great trick!
Dsvid, that was a great trick!
Carolina, that was a great trick!

 for代碼行后邊縮進的代碼塊都是循環的一部分,繼續增加打印語句:

for magician in magicians:
    print(magician.title() + ', that was a great trick!')
    print("I can't wait to see your next trick, " + magician.title() + "\n")

運行結果:

 

3. 對於for循環后邊的屬於循環模塊的代碼行一定要縮進。

3.1 若沒有縮進:
for magician in magicians:
print(magician.title() + ', that was a great trick!')

運行結果會報錯:

IndentationError: expected an indented block
3.2 若有縮進的,有沒有縮進的:
for magician in magicians:
    print(magician.title() + ', that was a great trick!')
print("I can't wait to see your next trick, " + magician.title() + "\n")

程序運行不會出錯,但是沒有縮進的代碼將在循環結束之后執行一次,只打印出有關列表最后一個元素的信息:

Alice, that was a great trick!
Dsvid, that was a great trick!
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina
3.3 若縮進了本應在循環結束之后執行的代碼,則這些代碼將針對每個元素循環執行一次,程序不會報錯。
 

4. 對於for循環還要注意的一點是——for語句的末尾千萬不要忘了冒號(太容易忘了,太容易忘了,太容易忘了。。。)。

一旦忘記冒號,程序運行就會報錯:
SyntaxError: invalid syntax

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM