先用for循环累加各项计算等比数列和,首项a=2、公比r=3、项数n=5时,各项为2, 6, 18, 54, 162,总和为242;可封装为geometric_sum(a, r, n)函数,便于重复调用。

在Python中,可以用for循环来计算等比数列的总和。等比数列是指从第二项起,每一项与前一项的比值相等的数列,其通项公式为:
an = a × rn-1
其中,a 是首项,r 是公比,n 是项数。
基本思路
使用 for 循环遍历每一项,将每一项累加到一个变量中,即可得到总和。实例代码:计算等比数列前n项和
下面是一个具体例子,计算首项为 2,公比为 3,前 5 项的和:
# 参数设置
a = 2 # 首项
r = 3 # 公比
n = 5 # 项数
<h1>初始化总和</h1><p>total = 0</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2093" title="md2card"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175679994130360.png" alt="md2card" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2093" title="md2card">md2card</a>
<p>Markdown转知识卡片</p>
</div>
<a href="/ai/2093" title="md2card" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><h1>使用 for 循环计算每一项并累加</h1><p>for i in range(n):
term = a * (r ** i) # 当前项
total += term</p><p>print("等比数列的和为:", total)
输出结果
运行上述代码,输出为:等比数列的和为: 242
对应的数列为:2, 6, 18, 54, 162,它们的和确实是 2 + 6 + 18 + 54 + 162 = 242。可复用函数版本
为了更方便地重复使用,可以将其封装成函数:
def geometric_sum(a, r, n):
total = 0
for i in range(n):
total += a * (r ** i)
return total
<h1>调用示例</h1><p>result = geometric_sum(2, 3, 5)
print("等比数列的和为:", result)
这种方法逻辑清晰,适合初学者理解循环和等比数列的结合应用。虽然数学上有求和公式 Sn = a(1 - rn) / (1 - r)(当 r ≠ 1),但在编程练习中,用 for 循环实现有助于掌握基础语法。
基本上就这些。










