-3

I am working on a problem in Python and don't understand the answer.

for number in range(1, 10): if number % 2 == 0: print(number)

The answer to this problem is 2,4,6,8

Can anyone explain this answer?

JLT
  • 1
  • What about it do you not understand? Do you know what the `%` operator does? – Guy Incognito Dec 10 '20 at 22:11
  • The `%` is called the modulo operator. [This answer](https://stackoverflow.com/a/4432235/11838196) provides a good explanation. – srk Dec 10 '20 at 22:12

1 Answers1

0

range is a function in python which generates a sequence of integers, for example:

r=range(3)

returns a iterable object range(0,3) which generates sequence of integers from 0 to 3-1(2),inorder for you to see the elements in it , you can loop through it:

for i in r:
     print(i)
#prints number from 0 to 3-1

Or, wrap it in a list:

list(range(3)) //returns [0,1,2]

range can take 3 params as input start,end and optionally step.The parameters start and end are basically lower and upper bounds to the sequence.In the above example since we have given only one integer range considers start as 0 and end as 3. This function range(start,end,[step]) generates integers in the following manner: start,start+1....end-1 considering the above example 0,0+1...3-1

if you give both the start and the end params to the range, the function generates integers from start upto but not including end, Example:

for i in range(3,8):print(i) #prints numbers from 3 to 8-1

if you give the third parameter which is the step(which is usually 1 by default), then range adds that number to the sequence :

list(range(3,8)) or list(range(3,8,1)) # will return [3,4,5,6,7],sequence generation will be like:3,3+1,(3+1)+1...

list(range(3,8,2)) #returns [3,5,7];3,3+2,(3+2)+2....

So , coming to your question now :

for number in range(1, 10): if number % 2 == 0: print(number)

In the above code you are basically telling python to loop over the sequence of integeres between 1 to 9 and print the numbers which are divisible by 2,which prints 2,4,6,8.

Hope this helped you :)

konem
  • 1
  • 1