I am relatively new to coding and saw this question on a video. enter image description here
Like for the
for i in range(2, num):
line I understand how it would work when plugging in a number 3 or greater for the variable num
but I do not understand how it would work if it were to be 2.
The code checks if it is a prime number, so if I plug in 2 it would be:
for i in range (2,num-1):
which is
for i in range (2,1):
How would the code still run?
CodePudding user response:
A range(start, stop)
is a half open interval from start
to but exluding stop
. See range for the details. The range may be empty as would be the case for your example of range(2,1)
, note, however there is also a step
argument if you want the range to down instead of up range(2, 1, -1)
which in this case would evaluate to 2
.
CodePudding user response:
The range will be empty and it will simply skip the for loop.
Not much unlike this:
empty_list = []
for item in empty_list:
print("I love pumpkin") # will never run