编写Python程序计算等比数列1+2+4+…+n的和,参考指定代码格式
Got it, let's work through this problem. We need to compute the sum of a geometric series where each term doubles the previous one, starting at 1 and ending at the input value n.
First, a quick pattern check: each term here is a power of 2 (1=2⁰, 2=2¹, 4=2², etc.). The sum of this series up to 2ᵏ is actually 2ᵏ⁺¹ - 1—this is why when the input is 256 (which is 2⁸), the sum is 511 (2⁹ - 1). But let's build the solution following the iterative structure of the sample code you provided.
The Code
n = int(input("Enter n: ")) total = 0 current_term = 1 # Loop through each term until we exceed the input n while current_term <= n: total += current_term current_term *= 2 # Double the term to get the next in the sequence print() print("The sum is: %s" % (total))
How It Works
- We start by grabbing the input
nand initializingtotal(our sum accumulator) to 0. current_termstarts at 1, the first term of the series.- In each loop iteration, we add the current term to our total, then double the term to get the next value in the sequence.
- We stop looping once
current_termgrows larger thann, so we never add terms that exceed the input value.
Example Verification
If you input 256, the loop processes terms 1, 2, 4, 8, 16, 32, 64, 128, 256. Adding these up gives 511, which matches the expected result.
Even if you input a value that's not a perfect power of 2 (like 10), the code works correctly: it sums 1+2+4+8 = 15, since 16 is larger than 10 and gets excluded from the sum.
内容的提问来源于stack exchange,提问作者 Anonymous

