r/PythonLearning • • 1d ago

Help Request help for a programing assignment

I need to write a program that will calculate the sum of the first n of 1 + 1/2 + 1/4 + ... = lim (n -> ∞) Σ 1/2^k =2 starting at k=0 to n.

Teacher said we could use Σ 1/2^k = 2 - 1/2^(n-1) starting at k=0 to n-1

We have to write it using a loop.

I went back through my notes and figured I needed to use a «for» loop.

My teacher starts all of his programs with def, but when I try to look up more infos online I struggle to find others who are using it.

So, here's what I've tried

def estimate_serie (nb_term) : 
sum = 0
for term in range (1, nb_term + 1) : 
sum=sum + 1/(2 ** term)
return sum
print (estimate_serie(5))
print (estimate_serie(8))
print (estimate_serie(12))

it gave me

0.5

0.5

0.5

Btw I am learning this in french so I might not have translated all of it correctly. I've also only been learning for a month, so if my mistakes seem dumb that might explain why.

3 Upvotes

9 comments sorted by

View all comments

4

u/Due-Mortgage-6854 1d ago

Your return sum must be outside the FOR Loop and your for term in range(1, nb_term + 1) must start from zero giving : for term in range(nb_term + 1)

1

u/Leviathans_ 1d ago

I did the changes you proposed and tried with 1,2,3 instead of 5,8,12 for simpler numbers.
I got 1.5 instead of 1 for 1
1.75 instead of 1.5 for 2
And the same for 3
Sadly, the power went out 😭 so I will be working on this later, but thank you for the help

2

u/Due-Mortgage-6854 1d ago

ahh im really sorry its for term in range(nb_term) not (nb_term+1). I typed in a hurry😅