I am working on a function which takes a positive integer N and computes the following sum:
1 - 2 + 3 - 4 + 5 - 6 + .... N.
My professor said we can not use “math formulas” on this, so how could I go about it?
I thought about using a for loop, but I don’t know how or what to write for the print statement. This is what I have so far:
n=int(input("enter N="))
for i in range(1, n+1, 1):
if i % 2 == 0:
# I'm not sure what print statement to write here
I tried print(i= "+" i+1) and just weird stuff like that, but I get errors and am lost after that.
what i have now
n=int(input('enter N='))
total=0
print("sum",)
for i in range(1, n+1, 1):
if i % 2 == 0:
count=count - i
print("-", i)
else:
count=count + i
print("+", i, end=" ")
print("=", total)
#still get errors saying name count not defined and unsupported sperand for +:
First, to accumulate the sum as described, and to do it by looping instead of “using math formulas”, you want to do this:
You should be able to figure out what the ???? are: you need to do something to total for each i, and it’s different for even and odd.
Now, if you want it to print out something like this:
You can print things out along the way like this:
If you want to keep negative and positive totals separately and then add them, as you mentioned in an edit, change
total = 0tontotal, ptotal = 0, 0, then change each of the ???? parts so one works on one total, one on the other.All of the above is for Python 3. If you want to run it in Python 2, you need to turn those
printfunction calls intoprintstatements. For the simple cases where we use the default newline ending, that’s just a matter of removing the parentheses. But when we’re using theend=" ", Python 2’sprintstatement doesn’t take keyword parameters like that, so you instead have to use the “magic comma”, which means to end the printout with a space instead of a newline. So, for example, instead of this:You’d do this:
Again, for Python 3, you don’t have to worry about that. (Also, there are ways to make the exact same code run in both Python 2 and 3—e.g., use
sys.stdout.write—which you may want to read up on if you’re using both languages frequently.)