[英]Please Help Understand this Code in Python
我正在努力提高我的 python 技能,这让我很困惑。 这是代码:
greeting = 'Hello!'
count = 0
for letter in greeting:
count += 1
if count % 2 == 0:
print(letter)
print(letter)
print('done')
我不明白计数是做什么的。
这个确切的代码将 position 编号为偶数的字母加倍。 count 用于计数字母 position。 条件计数 % 2 == 0 知道哪个 position 除以 2 没有剩余(检查 position 是否为偶数)
让我们注释代码并解释每行的作用,然后检查 output。
# assign the string 'Hello!' to the name greeting
greeting = 'Hello!'
# assign the number 0 to the name count
count = 0
# assign letter to each character in greeting one at a time.
# in the first run of the loop, letter would be 'H', then 'e',
# etc.
for letter in greeting:
# add one to count. count starts at 0, so after this line
# on the first run of the loop, it becomes 1, then 2, etc.
count += 1
# use the modulo operator (%) to get the remainder after
# dividing count by 2, and compare the result to 0. this
# is a standard way of determining if a number is even.
# the condition will evaluate to True at 0, 2, 4, etc.
if count % 2 == 0:
# when count is even, print letter once followed by a
# new line. note that to not print a new line, you can
# write print(letter, end="")
print(letter)
# print letter once followed by a new line regardless of the
# value of count
print(letter)
# print 'done' followed by a new line
print('done')
那么,基于所有这些,我们应该期望 output 是什么? 好吧,我们知道greeting
的每个字符都会在循环的最后一行打印出来。 我们还知道, greeting
的每个偶数字符都会被打印两次,一次在if
块内,一次在循环结束时。 最后,我们知道循环完成后会打印“done”。 因此,我们应该期待以下 output:
H
e
e
l
l
l
o
!
!
done
这很简单,请参见:
greeting = 'Hello!'
在这一行中,您为变量greeting
分配了一个字符串值Hello!
.
count = 0
在这一行中,您为变量count
分配了 integer 值0
。 现在下一个代码是:
for letter in greeting:
count += 1
if count % 2 == 0:
print(letter)
print(letter)
你可能知道字符串是可迭代的。 在了解上述内容之前,请查看此代码:
for letter in greeting:
print(letter)
忘记计数。 在循环的每次迭代中,循环都会打印问候语的每个字符。 所以 output 是:
H
e
l
l
o
!
但是为什么每个字母后面都有一个换行符。 答案是 print 有一个可选参数end
如果上面的代码是这样的:
for letter in greeting:
print(letter, end = '')
那么 output 将是:
Hello!
现在出现了计数项。 这也很简单。 当计数为偶数时,由于两次打印语句,它会在循环中打印两次迭代的字母。 if count % 2 == 0
检查计数是否偶数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.