Python新手在这里 - Python迭代

时间:2017-10-11 03:52:09

标签: python string iteration

Python新手在这里 - 请您解释以下内容

greeting = 'Hello!' 
count = 0  
for letter in greeting:
     count += 1   
  if count % 2 == 0: 
        print(letter) 
    print(letter) 
 print('done')

3 个答案:

答案 0 :(得分:0)

避免缩进错误,我正在解释您的代码所做的事情。

在你的程序中,你初始化了一个名为greeting的变量,值为#34; Hello!"还有一个值为0的计数。

greeting ='您好!' count = 0

此后for循环我们使用了循环问候语,即直到每个单词 Hello!的结尾。但是,如果您想自己检查一下,可以打印这封信。

问候信:      打印(字母)

现在出现问题,你也将count的值递增1,每次循环执行时值增加1。

然后您有条件检查数字是否为偶数计数%2 == 0 ,然后是条件成功时执行的print语句。这意味着偶数位置的字母只会打印出来。

这就是你的程序所做的。

答案 1 :(得分:0)

greeting = 'Hello!' <-- set greeting variable.
count = 0  <-- set count variable.
for letter in greeting: <-- this loop will loop six times because greeting contains of six character.
     count += 1  <-- each times of loop will increase value of count by one.
  if count % 2 == 0: <-- this line will print a index of character that % 2 = 0 (eg. 2%2 = 0, 4%2 = 0, ...)
        print(letter) 
    print(letter) <-- this line will print any index of character of greeting. (ps. this line will error because indentation errors.)
 print('done') <-- print 'done'.
  

所以结果将是这样的:

H
e e
l l
l l l

完成

答案 2 :(得分:0)

greeting = 'Hello!' <-- set greeting variable.
count = 0  <-- set count variable.
for letter in greeting: <-- this loop will loop six times because greeting contains of six character.
     count += 1  <-- each times of loop will increase value of count by one.
     if count % 2 == 0: <-- this line will print a index of character that % 2 = 0 (eg. 2%2 = 0, 4%2 = 0, ...)
        print(letter) 
    print(letter) <-- this line will print any index of character of greeting. (ps. this line will error because indentation errors.)
print('done') <-- print 'done'.

Output