Python Forum
While loop is terminating too early
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loop is terminating too early
#1
Hello,

I am having trouble returning the correct values for my while loop.

The loop is supposed take in a value n and loop through "num times," if n > 1 then sum that value with the previous n and increment k to continue looping. However, if the n is ever 1 then the sum becomes 1 (sum = 1), but the statement should continuing looping until it has reached num times and then return sum=1.

My is issue is that loop terminates when it reaches 1 and returns 1 instead of completing the loop.

Is there a way to do this?

Thank you.
Reply
#2
(Jun-28-2025, 08:38 PM)jumpsworthnow Wrote: My is issue is that loop terminates when it reaches 1 and returns 1 instead of completing the loop.
Can you post the code? Without the code, the error is very difficult to diagnose.
« We can solve any problem by introducing an extra level of indirection »
Reply
#3
“Agreed with Grenouilles seeing the code would help a lot. From your description, it sounds like your loop might have an early exit when n 1, instead of just updating the sum and continuing. Post your code so we can spot where it’s breaking!”
Reply
#4
Use a separate loop counter
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I'm getting a syntax error very early on in my code and I can't quite figure it out. liloliveoil 1 3,156 Oct-30-2020, 05:03 AM
Last Post: deanhystad
  while not terminating gitiya 1 2,858 Jan-13-2019, 02:35 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020