Yes, the range() function in Python can use negative numbers. You can specify negative values for the start, stop, and step parameters. Here’s how it works:
Using Negative Numbers with range()
-
Negative Start and Stop:
You can create a range that counts down from a negative start to a negative stop.Example:
for i in range(-5, -1): print(i)This will output:
-5 -4 -3 -2 -
Negative Step:
You can also use a negative step to count downwards.Example:
for i in range(5, 0, -1): print(i)This will output:
5 4 3 2 1 -
Negative Start with Positive Stop:
If you use a negative start with a positive stop and a negative step, the range will be empty because it cannot count upwards.Example:
for i in range(-5, 5, -1): # This will not output anything print(i)
Summary
- You can use negative numbers in the
start,stop, andstepparameters ofrange(). - A negative step allows you to create descending sequences.
- Ensure that the
startis greater than thestopwhen using a negative step.
If you have more questions or need further examples, feel free to ask!
