Hey everyone, I am just starting to learn iteration in Python. I am stuck on an assignment that my teacher gave me. I am supposed to make a code to display this:
1
-2
3
-4
5
-6
7
-8

So far my code is this:
counter=8
number=9
while counter>0:
print number+counter*-1
counter=counter-1

All it does is put out the numbers 1 through 8. I can get it to do numbers 1 through 8 in all odd also. I just haven't figured out how to make the negatives alternate. Any help would be amazing!

Recommended Answers

All 4 Replies

Please use the Code button to keep indentations in code)
Reply:

normal way is to use for with range

for number in range(1,9):
    # use the last bit of number (even/odd) to get alternation,
    # 0 is considered True (even numbers)
    print -number if (number & 1) else number

You can also use some indicator that switches on and off for print positive or negative.

counter=1
positive = True
while counter < 9:
    if positive:
        print counter
    else:
        print counter * -1
    counter += 1
    positive = not positive     ## switch it
# normal way is to use for with range
for number in range(1,9):
    # use the last bit of number (even/odd) to get alternation,
    # 1 is considered True (odd numbers)
    print number if (number & 1) else -number

Of course 1 is considered True, odd numbers.

for x in [-x*(-1)**x in range(1,9)]:
    print x
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.