2016-08-16 79 views
-1
**1** 
count = 0 
phrase = "hello, world" 
for iteration in range(5): 
    index = 0 
    while index < len(phrase): 
     count += 1 
     index += 1 
    print "Iteration " + str(iteration) + "; count is: " + str(count) 


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

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

他们是一个有点奇怪的例子..你运行它们吗?他们在做什么?你期望他们做什么? –

+0

是的,他们基本上统计短语中的字母数,并在每次迭代中打印计数。但我不明白正在应用的概念。我希望你明白我想传达的信息 – PyCoding

回答

0

编号1:有一个count变量存储一个数字,并且短语"hello, world"存储在phrase变量中。 for循环重复5次。在它里面,定义了一个占位符变量index。重复while循环的长度为phrase次,占位符indexcount变量增加1。 for循环的最后一行输出for循环的哪一轮和count变量。

编号2:同样,定义了countphrase变量。重复for循环5次,第一行创建一个无限while循环(一个永远重复)。但是,在count增加了phrase的长度之后,立即break超出while循环(停止它),因此它不会永久持续。最后一行输出与Number 1相同的内容。 (这可能很清楚,因为它们是相同的代码行。)

编号3:countphrase变量再次被定义。循环运行5次。每次count增加phrase的长度,然后运行print语句(与数字1和2相同)。

希望这会有所帮助!

+0

@ Mr.Python:是的,它确实运行了,但不包括传入的数字('range(4)'运行到4)。但是,由于'range()'函数默认从0开始,而不是1,所以循环会从0到4,这是5次重复。 –

相关问题