Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中是否每次都通过循环计算测试条件?_Python_Compiler Construction - Fatal编程技术网

在Python中是否每次都通过循环计算测试条件?

在Python中是否每次都通过循环计算测试条件?,python,compiler-construction,Python,Compiler Construction,每次都会计算。Python不知道str(n)每次都会返回相同的内容。在编译时,据它所知,可以使用 # returns sum of individual digits in n (correct implementation) def digit_sum(n): running_sum = 0 for _ in xrange(len(str(n))): rightmost = n % 10 # value of right-most digit runni

每次都会计算。Python不知道
str(n)
每次都会返回相同的内容。在编译时,据它所知,可以使用

# returns sum of individual digits in n (correct implementation)
def digit_sum(n):
  running_sum = 0
  for _ in xrange(len(str(n))):
    rightmost = n % 10         # value of right-most digit
    running_sum += rightmost
    n = n // 10                # strip right-most digit
  return running_sum
虽然在时使用
会更简单:

for _ in xrange(len(str(n))):

只要
n!=0

这应该很容易测试。我当然希望每次都对它求值,否则很多循环都无法正确编写。为什么每次都要创建一个
范围
?是的,在CPython中每次都会对它求值。但是为什么要将整数与
range()
?(在Python2中总是如此。)@JonathonReinhart:数据流分析可以确定条件的某些部分不受循环体的影响。(撇开指针别名和并发问题不谈。)
class IAmABadPersonWhoWantsPeopleToHaveABadTime(int):
    def __str__(self):
        if random.random() < 0.1:
            raise SyntaxError
        return super(IAmABadPersonWhoWantsPeopleToHaveABadTime, self).__str__()
for _ in xrange(len(str(n))):
while n: