從Python's Official Documentation - 8.3 The for Statement
「for語句用來遍歷序列的元素(如一個字符串,元組或列表)...」
在你的代碼示例,"Lucy"
是字符串。字符串是序列。構成它的字符(即"L", "u", "c", "y"
)是「序列的元素」。
我將逐行檢查您的代碼,看看它是否有幫助。
1.您將sys.argv[1]
分配給變量mysteryString
。您的sys.argv[1]
是字符串"Lucy"
。
mysteryString = sys.argv[1]
2.程序採用變量mysteryString
,用它格式化字符串,並打印輸出。
print("~ testing with mysteryString = {} ~".format(mysteryString))
Output: ~ testing with mysterString = Lucy ~
3.此行初始化變量charCount
。請注意,它是空的。
charCount = ""
4.此行標記for for語句(又名for循環)的開始。 for語句迭代(或「循環」)提供的序列中的每個元素。爲了遍歷序列,您必須將其中的每個元素分配給一個變量。在這裏,該變量是mysteryChar
。序列的第一個元素(即字符"L"
)被分配給變量mysteryChar
。
for mysteryChar in mysteryString:
如果有幫助,你能想到什麼是在這一點上發生的事情爲:
mysteryChar = "L"
5.該行做了幾件很酷的事情。首先,它的值爲charCount
,並將其添加到值mysteryChar
。其次,它將charCount
和mysteryChar
的值分配給charCount
。
charCount = charCount + mysteryChar
還記得在第3步,我們賦值的變量charCount
爲空字符串?
charCount = ""
步驟5後,執行:
charCount = "L"
6。此行打印charCount
。
代碼:
print(charCount)
輸出:
L
7.Now,嘗試按照代碼。
代碼:
charCount = ""
for mysteryChar in mysteryString:
charCount = charCount + mysteryChar
print(charCount)
輸出:
L
8.Continue到循環的下一次迭代。
代碼:
mysterString = "Lucy"
# Note: Before the second iteration of the loop, charCount = "L"
# This is because in the first iteration of the loop,
# "L" was added & assigned to the variable charCount
charCount = ""
for mysteryChar in mysteryString:
charCount = charCount + mysteryChar
print(charCount)
輸出:
Lu
9.Continue到環路
碼的下一次迭代:
mysterString = "Lucy"
# Note: Before the third iteration of the loop, charCount = "Lu"
# This is because in the second iteration of the loop,
# "u" was added & assigned to the variable charCount
# At that point, charCount = "Lu"
charCount = ""
for mysteryChar in mysteryString:
charCount = charCount + mysteryChar
print(charCount)
輸出:
Luc
10.這是for-loop的所有輸出。
輸出:
L
Lu
Luc
Lucy
問:
「爲什麼它打印字符它的方式」
for循環打印的字符的方式它因爲它會逐個遍歷序列中的每個元素。
第一次迭代輸出:
L
第二次迭代輸出:
Lu
第三次迭代輸出:
Luc
第四次迭代輸出:
Lucy
大約一年前我開始學習python,所以這個東西對我來說也是比較新的。如果我的解釋錯誤,歡迎批評/更正。
如果在循環中執行了'charCount =「」',那麼只會打印當前字符。 – bernie
我建議嘗試可視化你的代碼[here](http://www.pythontutor.com/visualize.html#mode=edit)。 –