怎么理解python循环_Python循环 - 帮助我理解

“for语句用于迭代序列的元素(例如字符串,元组或列表)......”

在您的代码示例中, "Lucy" 是字符串 . 字符串是序列 . 组成它的字符(即 "L", "u", "c", "y" )是"elements of a sequence."

我将逐行浏览您的代码以查看它是否有帮助 .

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 = ""

这条线标志着for语句的开始(又名for-loop) . for语句迭代(或"loops over")提供的序列中的每个元素 . 为了遍历序列,必须将其中的每个元素分配给变量 . 这里,该变量是 mysteryChar . 序列的第一个元素(即字符 "L" )被赋值给变量 mysteryChar .

for mysteryChar in mysteryString:

如果它有帮助,你可以考虑到目前发生的事情:

mysteryChar = "L"

这条线做了几件很酷的事情 . 首先,它采用 charCount 的值并将其添加到 mysteryChar 的值 . 其次,它将 charCount 和 mysteryChar 的值分配给 charCount .

charCount = charCount + mysteryChar

还记得在步骤3中,我们将变量 charCount 分配给空字符串吗?

charCount = ""

在第5步执行之后:

charCount = "L"

这条线打印 charCount .

码:

print(charCount)

输出:

L

7.现在,尝试遵循代码 .

码:

charCount = ""

for mysteryChar in mysteryString:

charCount = charCount + mysteryChar

print(charCount)

输出:

L

8.继续循环的下一次迭代 .

码:

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.继续循环的下一次迭代

码:

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,所以这个东西对我来说也是比较新的 . 如果我的解释被误导,欢迎批评/更正 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值