Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Print Alternating Numbers

Print positive odd values and negative even values through n. Students trace parity-based output choices without changing the loop's ascending control value.

BeginnerPhase 2 - Level 1: Basic LoopingExample 14 of 14
print-alternating-numbers.py
1# Take n as input
2n = int(input("Enter n: "))
3
4# Print alternating
5for i in range(1, n + 1):
6 if i % 2 == 0:
7 print(-i, end=" ")
8 else:
9 print(i, end=" ")
10print()

Output

Enter n: 5
1 -2 3 -4 5

In this one

  • Choose a sign by parity
  • Keep the loop variable ascending
  • Format a number sequence

How it works

  1. 1

    Visit positive integers through n.

  2. 2

    Print -i for even i and i otherwise.

  3. 3

    End the shared line after the loop.

Edge cases

What happens for n = 0?

What happens for n = 0?

No numeric values print; only the final newline is produced.

Are odd terms negated?

Are odd terms negated?

No. Only the even branch prints -i.

What's going on

The loop variable i always rises from one through n. The sign of the printed value changes according to whether i is even.

For n equal to five, output is 1 -2 3 -4 5. Printing -i does not change i or make the loop run backward. end keeps the values on one line, and the final print adds the newline.

What happens for n = 0? No numeric values print; only the final newline is produced.

Are odd terms negated? No. Only the even branch prints -i.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is printed when i = 6?

Pick an answer to check it.

Question 2

What happens for n = 0?

Pick an answer to check it.

Questions people ask

What happens for n = 0?

No numeric values print; only the final newline is produced.

Are odd terms negated?

No. Only the even branch prints -i.

What is printed when i = 6?

-6.