【问题标题】:Loop Counting Scoping In PythonPython中的循环计数范围
【发布时间】:2016-07-14 17:43:17
【问题描述】:

我试图弄清楚这段代码是如何工作的。 i 如何在 for 循环之外访问?

# Palindrome of string
str=raw_input("Enter the string\n")
ln=len(str)
for i in range(ln/2) :
    if(str[ln-i-1]!=str[i]):
        break
if(i==(ln/2)-1):         ## How is i accessible outside the for loop ? 
    print "Palindrome"
else:
    print "Not Palindrome"

【问题讨论】:

  • for 循环没有自己的命名空间。 Short Description of Python Scoping Rules
  • i 是可访问的,因为循环变量以其最后一个值保留在当前范围内,除非您为名称分配其他内容。
  • 为什么?您如何或出于什么目的实施此操作?它的作用过于复杂。 mystr == mystr[::-1]
  • 实际询问您不理解的代码的具体方面做得很好!这让你的问题更容易回答。
  • 旁注:不要使用str作为变量名,因为你会隐藏内置的str

标签: python scope palindrome


【解决方案1】:

这是 Python 的一部分。在 for 循环中声明的变量(包括循环计数器)在完全离开作用域之前不会衰减。

看看这个问题:

Scoping In Python For Loops

来自答案:

for foo in xrange(10):
    bar = 2
print(foo, bar)

上面将打印 (9,2)。

【讨论】:

    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2018-09-15
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多