Python 谁能给我解释一下这个密码吗?

Python 谁能给我解释一下这个密码吗?,python,Python,代码如下: count = 0 phrase = "hello, world" for iteration in range(5): while True: count += len(phrase) break print("Iteration " + str(iteration) + "; count is: " + str(count)) 我对count+=len(短语) 我觉得count+=len(短语)=>count=count+len(

代码如下:

count = 0
phrase = "hello, world"
for iteration in range(5):
    while True:
        count += len(phrase)
        break
    print("Iteration " + str(iteration) + "; count is: " + str(count))
我对
count+=len(短语)

我觉得count
+=len(短语)
=>
count=count+len(短语)


当count
+=1
时,可以理解每次迭代它都会增加1,但在这里它会迭代整个长度,所以我无法得到它背后的逻辑。我请求是否有人能逐行向我解释这段代码中实际发生的事情。谢谢

你对
+=
的直觉是正确的;
+=
运算符表示就地加法,对于不可变值类型,如
int
,它与
count=count+len(短语)
完全相同

循环的外部
运行5次;因此,
count
最后设置为
短语长度的5倍

您可以删除
而True:
循环。它启动一个只迭代一次的循环;
中断
在第一次迭代中结束该循环


在这段代码中,没有任何东西可以遍历
短语的整个长度。只查询它的长度(12)并将其添加到
count
,因此最终值是5乘以12等于60。

您对
+=
的直觉是正确的;
+=
运算符表示就地加法,对于不可变值类型,如
int
,它与
count=count+len(短语)
完全相同

count = 0
phrase = "hello, world"
for iteration in range(5): #iterate 5 times
    while True:
        #count = count + len(phrase)
        count += len(phrase)  # add the length of phrase to current value of count.
        break                 # break out of while loop, while loop 
                              # runs only once for each iteration
    #print the value of current count
    print("Iteration " + str(iteration) + "; count is: " + str(count))
循环的外部
运行5次;因此,
count
最后设置为
短语长度的5倍

您可以删除
而True:
循环。它启动一个只迭代一次的循环;
中断
在第一次迭代中结束该循环

在这段代码中,没有任何东西可以遍历
短语的整个长度。只查询它的长度(12)并将其添加到
count
,因此结束值是5乘以12等于60

count = 0
phrase = "hello, world"
for iteration in range(5): #iterate 5 times
    while True:
        #count = count + len(phrase)
        count += len(phrase)  # add the length of phrase to current value of count.
        break                 # break out of while loop, while loop 
                              # runs only once for each iteration
    #print the value of current count
    print("Iteration " + str(iteration) + "; count is: " + str(count))
因此,简言之,程序将
短语的长度添加到
计数
5次

输出:

Iteration 0; count is: 12   # 0+12
Iteration 1; count is: 24   # 12+12
Iteration 2; count is: 36   # 24+12
Iteration 3; count is: 48   # 36+12
Iteration 4; count is: 60   # 48+12
上述计划大致相当于:

count = 0
phrase = "hello, world"
for iteration in range(5):
    count = count + len(phrase)
    print("Iteration " + str(iteration) + "; count is: " + str(count))
因此,简言之,程序将
短语的长度添加到
计数
5次

输出:

Iteration 0; count is: 12   # 0+12
Iteration 1; count is: 24   # 12+12
Iteration 2; count is: 36   # 24+12
Iteration 3; count is: 48   # 36+12
Iteration 4; count is: 60   # 48+12
上述计划大致相当于:

count = 0
phrase = "hello, world"
for iteration in range(5):
    count = count + len(phrase)
    print("Iteration " + str(iteration) + "; count is: " + str(count))

while True
break
只是混淆。如果将它们删除,结果是相同的。
while True
break
只是模糊处理。如果将它们删除,结果相同。这相当于
count=5*len(“你好,世界”)
。@Ashwini Chaudhary感谢您的详细解释@我也谢谢你!这相当于
count=5*len(“你好,世界”)
…@Ashwini Chaudhary感谢您的详细解释@我也谢谢你!谢谢你的解释!谢谢你的解释!