John Szwec:
Why does making 1 change to the following piece of code break it ?
code to identify prime numbers which are user input:
However if i change the line:
for i in range(2, number):
to:: for i in range(2, 7):
now if i enter 3 when prompted for a number it shows as not prime:
The code as it works
number = int(input('Enter a number: '))
is_prime = True
iterating loop from 2 to number-1
for i in range(2, number):
if (number % i) == 0:
is_prime = False
break
if is_prime:
print(f’{number} is prime’)
else:
print(f’{number} is not prime’)
John Szwec:
I’m also confused by the statement made by the instruction describing how the code works
The instruction states:
Now, if is_prime
is True
and unchanged till the end and not divisible by any number from 2 to number -1
, we know the number is prime.
what exactly is the “-1” referring to in that description ?
John Szwec:
From my understanding of what i have learned so far
in this statement “for i in range(2, number):”
-1 does not exist
Alistair Mackay:
range(a, b)
yields a non-inclusive sequence of numbers between a
and b
which means all the numbers between a
and b
but not including b
, i.e. the maximum number is b-1
So if a
= 2 and b
= 7, then range
will give you
2, 3, 4, 5, 6
b -1
= 7 - 1
= 6
John Szwec:
Thank You @Alistair Mackay, now i get it
Dr. Gaurav Sablok:
@John Szwec @Alistair Mackay sometimes, you will also see the range defined as range(2,7,-1)
or range(2,7,1)
so it means that you are including a step in range, indicating -1 will do a reverse range and indicating the 1 will do a plus range. so the third number is called as steps. suppose you want to make a range of only positive steps range(2,10,2
it will start at and will take 2 steps for each iteration. Cheers
Alistair Mackay:
Yup that’s true, but for the purpose of this exercise, we need the exclusive, single increment version, i.e. simplest version
Dr. Gaurav Sablok:
@Alistair Mackay Thank you.Cheers