Home > other >  For loop which excludes both start and end of a range
For loop which excludes both start and end of a range

Time:07-25

I need to write an algorithm that can print a range of 2 given numbers from the user and exclude them.

This is the code that I have so far yet this will exclude only the second number.

x = int(input("Input the first number for the range: "))
n = int(input("Input the second number for the range: "))

if (x and n != 0):
    for num in range(x, n):
        print(num)

How can I make it exclude the first number, too?

CodePudding user response:

x = int(input("Input the first number for the range: "))
n = int(input("Input the second number for the range: "))


for num in range(x, n):
    if num == x:
        pass
    else:
        print(num)

try this

i think it is what you are asking for

CodePudding user response:

range can be invoked in 1 of two ways:

range(stop)
range(start, stop, [step])

You need to be aware that the stop value is excluded but start is included.

Therefore, for your use-case it's as simple as:

x = int(input("Input the first number for the range: "))
n = int(input("Input the second number for the range: "))


for num in range(x 1, n):
    print(num)

Note:

Input validation not included

  • Related