关于Hetland Python书中interval函数参数与循环的技术疑问
Understanding the
interval Function from Hetland's Python Book Let's break down your questions one by one to clear up the confusion:
1. The Role of the Two start Variables in the If Statement
That line start, stop = 0, start uses Python's simultaneous tuple assignment—a concise way to reassign multiple variables in one go. Here's the play-by-play:
- When you call the function with only one argument (like
interval(10)), thestopparameter defaults toNone, so the if condition triggers. - The right-hand side (
0, start) first evaluates to a tuple containing0and the original value you passed asstart(in this case, 10). - We then assign those values to the left-hand variables: the first
startis the function'sstartvariable being updated to0, andstoptakes the originalstartvalue (10). - That’s why replacing the second
startwith an integer (say 5) makes the list length equal to that integer—stopbecomes 5, so the function generates values from 0 to 4. The secondstartis just capturing your original input to use as the new upper bound.
2. Why the Loop Runs When Passing start=10
Your confusion here stems from missing the variable reassignment that happens before the loop. Let’s walk through calling interval(10) step by step:
- You pass
start=10,stopisNone, so the if block executes:startgets set to 0,stopgets set to 10. - The loop starts with
i = start(now 0), and the condition iswhile 0 < 10—which is absolutely true! - The loop runs, appending 0, 1, 2, ..., 9 to the result list, incrementing
ibystep(1) each time, untilihits 10 (at which point10 <10is false, and the loop stops).
You thought the loop was using the originalstartvalue (10) for the condition, but the if statement already changedstartto 0 before the loop even begins.
内容的提问来源于stack exchange,提问作者Knovolt
相关产品推荐
相关产品推荐

