Where does this seemingly irrelevant number come from when using the range() module in Python?
Question:
I am asked to create two input variables (low and high) and output the odd numbers between both. I decided to use range() module and gave 3 to low, and 7 to high, as their values. The program is expected to return only 5, but it returned 5 and 3.
I drop a screenshot of the terminal below.
click here to see
low = int(input("enter the first number: "))
high = int(input("enter the second number: "))
def program(low, high):
numbers = range(low, high, 2)
for n in numbers:
print(n)
program(low, high)
So how could I fix it?
Answers:
A range
includes low
and excludes high
, per the documentation: https://docs.python.org/3/library/stdtypes.html#typesseq-range.
range
is a type, not a module.
The range(low, high, 2)
is such that
low
is included, high
is not included, skip=2
Since you gave low=3
and high=7
, the numbers will be 3
and skip 2 to get 5
(and 7 is not included)
I am asked to create two input variables (low and high) and output the odd numbers between both. I decided to use range() module and gave 3 to low, and 7 to high, as their values. The program is expected to return only 5, but it returned 5 and 3.
I drop a screenshot of the terminal below.
click here to see
low = int(input("enter the first number: "))
high = int(input("enter the second number: "))
def program(low, high):
numbers = range(low, high, 2)
for n in numbers:
print(n)
program(low, high)
So how could I fix it?
A range
includes low
and excludes high
, per the documentation: https://docs.python.org/3/library/stdtypes.html#typesseq-range.
range
is a type, not a module.
The range(low, high, 2)
is such that
low
is included, high
is not included, skip=2
Since you gave low=3
and high=7
, the numbers will be 3
and skip 2 to get 5
(and 7 is not included)