Click here to Skip to main content
15,849,129 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Can you please answer my question? I am trying to create a summation function where k runs from 1 to 3. The formula is 2**k/k**2. When I run the code, it prints 2.0 infinitely.

def summation():
    k=1
    result=0
    while True:
        if k>3:
            break
        variable_1=2**k
        variable_2=k**2
        term=variable_1/variable_2
        print (term)
        result+=term
        k=+1
    return result

print(summation())


What I have tried:

I am trying to learn how we keeping adding values to the same variable but I ended up creating an infinite while loop. I have imposed restriction if k>3, break, then while doesn't the loop stop?

I want the to retain print (term) in the code as I want to see what gets printed everytime the value of k changes.
Posted

1 solution

Look closely at your code:
Python
while True:
    ...
    result+=term
    k=+1
     ^^
     ||
return result
That assigns +1 to k
I suspect you wanted this:
Python
while True:
    ...
    result+=term
    k+=1
     ^^
     ||
return result
To be honest, 30 seconds with the debugger would have shown you exactly what the problem was, and you could have fixed it yourself very easily: pdb — The Python Debugger — Python 3.12.0 documentation[^]
It's worth getting into the habit of always testign your code in the debugger - it is the best tool you have, and can make your whole life far, far easier!


Quote:
I am very new to programming. Do you think I can really debug my errors myself?


If you write your own code, you know what it is supposed to do. What the debugger allows you to do is take control of your while it is running and look at variables to see what the hold, to run your code line by line to see where it is going, and to understand what it is actually doing.

Can you do it? Yes, almost certainly. Take the example of your original problem: with the debugger you would have seen that k contained 1 before you executed this line
k=+1
and expected it to contain 2 after - but it didn't, it contained 1 again! That tells you why it's staying in the loop (because k isn't changing at all) and what line of code was causing that. It's pretty simple to spot the actual problem from looking at that!

Try it: run your original code in the debugger and look at what happens.
 
Share this answer
 
v2
Comments
Baziga 15-Oct-23 7:48am    
I will defintily read this. Thank you so much!!
OriginalGriff 15-Oct-23 8:29am    
You're welcome!
OriginalGriff 15-Oct-23 8:38am    
Answer updated.
CPallini 16-Oct-23 2:09am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900