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.
1# Take n as input2n = int(input("Enter n: "))34# Print alternating5for 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
Visit positive integers through n.
- 2
Print -i for even i and i otherwise.
- 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.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum