Python Forum
Question about my code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about my code
#1
Hi, I am struggling to understand the solution to my homework problem and why my code or logic is incorrect compare to the solution of this question. The assignment states "write a for loop that sums the values 1 through end, inclusive. end is a variable that we define for you. So, for example, if we define end to be 6, your code should print out the result:

21

which is 1 + 2 + 3 + 4 + 5 + 6.

For problems such as these, do not include input statements or define variables we will provide for you. Our automating testing will provide values so write your code in the following box assuming these variables are already defined."

Now here is my code:

SumNum = 0
for num in range(0, end):
    SumNum += num
    print(SumNum)
Now, I am not sure why my code is wrong. It's from my understanding that when num iterates through the for loop from 0 to end, the value of each iteration is added to SumNum, and then gets printed out. I thought this is what the assignment is asking for.

But here is the actual solution to this assignment:
SumNum = 0
for num in range(1, end+1):
    SumNum += num
print(SumNum)
What I don't understand in this solution is why the range is starting from 1 instead of 0? Why is the print function outside of the for loop instead of inside the for loop?

I think my code is very similar to the answer, the main difference is that I start from 0 instead of 1. So what is the issue? Any explanation would be greatly appreciated.
Reply


Messages In This Thread
Question about my code - by Than999 - Jun-07-2020, 11:42 PM
RE: Question about my code - by pyzyx3qwerty - Jun-08-2020, 02:06 AM
RE: Question about my code - by snippsat - Jun-08-2020, 03:07 AM
RE: Question about my code - by buran - Jun-08-2020, 03:52 AM
RE: Question about my code - by Emekadavid - Jun-08-2020, 06:28 PM
RE: Question about my code - by jefsummers - Jun-08-2020, 09:09 PM

Forum Jump:

User Panel Messages

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