Can range use negative numbers?

QuestionsQuestions8 SkillsProPython Control StructuresSep, 08 2025
0320

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()

  1. 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
  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
  3. 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, and step parameters of range().
  • A negative step allows you to create descending sequences.
  • Ensure that the start is greater than the stop when using a negative step.

If you have more questions or need further examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!