在Python中是否每次都通过循环计算测试条件?
每次都会计算。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
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: