【发布时间】:2019-09-04 09:35:46
【问题描述】:
我编写了一个程序来评估输入字符串是否是回文。其中一部分是一个 for 循环(代码 A),它使用 range () 函数来定位变量 'a' 中的字符串字符,并创建一个新字符串 'b',它是 'a' 反转。我的 for 循环在代码 A 中运行良好,但我的初始版本(代码 B)并不成功。有什么想法为什么没有为代码 B 中的变量“b”输出变量?是因为我给 range() 函数提供了一个停止值,如果它使用默认的步长值 +1,它将永远无法达到?谢谢!
代码 A - 这行得通:)
def Code_A(a):
b=''
for i in range (len (a)-1,-1,-1):
b+=a[i]
return b
print 'Code A Output: '+ Code_A('abcdefg')
代码 B - 这不起作用:(
def Code_B(a):
b=''
for i in range (len (a)-1,-1):
b+=a[i]
return b
print 'Code B Output: '+ Code_B('abcdefg')
输出
Code A Output: gfedcba
Code B Output:
【问题讨论】:
-
是的,
B不起作用,因为它使用默认步骤1