0

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!

4
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by cghtkh
0

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

Edited by Reverend Jim: Fixed formatting

0

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

Edited by woooee: n/a

0
# 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.

Edited by pyTony: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.