144k views
0 votes
Write a for loop that prints the numbers from firstnumber to 0. For example, if the input is -3, the output should be -3 -2 -1 0.

1 Answer

2 votes

Final answer:

To print numbers from a given first number to 0, use a for loop in Python with an appropriate range, considering both positive and negative inputs. The loop stops before 0, and then 0 is printed explicitly at the end.

Step-by-step explanation:

To print the numbers from firstnumber to 0 using a for loop, you can use the following Python code as an example:

firstnumber = int(input('Enter the first number: '))
for i in range(firstnumber, 1 if firstnumber > 0 else -1, 1 if firstnumber < 0 else -1):
print(i, end=' ')
print(0)

This code first asks for the firstnumber, then iterates from the firstnumber towards 0, adjusting the step to be positive if the firstnumber is negative and vice versa. It ends by printing 0 outside the loop to include it in the output, regardless of where the firstnumber starts. If firstnumber is -3, the output of the for loop will be '-3 -2 -1 0' as requested.

User Fasth
by
8.5k points