16. Comprehending Comprehensions. Please take a Look


#1



"My code feels right to me but the error I'm getting is that it prints 15 only instead of three??"


threes_and_fives = [x for x in range(1, 16) if (x * 2) % 3 == 0 and (x*2) % 5 ==0]
print threes_and_fives


#2

write instructions or link of course here


#3

https://www.codecademy.com/courses/python-beginner-en-KAgt5/4/2?curriculum_id=4f89dab3d788890003000096


#4

your problem is

* 2

this not neede.


#5
if (x * 2) % 3 == 0 and (x*2) % 5 ==0

Take another look on the condition you have. As mentioned above by @firstboy000 there's no need to multiply x by two. But there is another bigger problem too. You only add numbers when x divides by both 3 and 5 at the same time. Maybe you ment to print when x divides by three or five (hint hint)


#6

The problem with the code is that it is only printing numbers that are divisible by three and five.
So instead of using (x * 2) % 3 == 0 and (x*2) % 5 == 0 , you would write (x * 2) % 3 == 0 or (x*2) % 5 == 0.:joy:


#7

:laughing::smile: i figured that out, already passed that excecise.


#8

Here's what I came up with, after some trial and errors

threes_and_fives = [x for x in range(1,16) if ((x % 3 == 0) or (x % 5 == 0))]


#9

threes_and_fives=[3,5,6,9,10,12,15]

"this is the simplest answer"


#10
threes_and_fives = [x for x in range(1, 16) if x % 3 == 0 or x % 5 == 0]
print threes_and_fives

Looking back at list comprehensions, this is what I came up with, hope it helps anyone.


#11

threes_and_fives=[3,5,6,9,10,12,15]

worked for me


#12

Please find the code for Comprehending Comprehensions:
threes_and_fives = [x for x in range(1,16) if x%3 == 0 or x%5 ==0]
print threes_and_fives


#13

Most certainly there is a mistake in the instructions : it should be "that are divisible by 3 or 5" instead of "that are evenly divisible by 3 or 5".
The code below is OK:

threesand_fives = [x for x in range(1,16) if (x%3==0) or (x%5==0)]_
print threesand_fives_

while this code is rejected:
threes_and_fives = [x for x in range(1,16) if (x/3.0)%2==0 or (x/5.0)%2==0]
print threes_and_fives


#14

Same exact answer that I came up with nice job sir! :slight_smile:


#15

why can't we put if loop in front???


#16

the if is not a loop but a condition and in list comprehension the loop comes first then the if condition.


#17

Thank you for your kind help! The main key here is actually to type «or» instead of «and».


#18

Use this code.Don't multiply x with 2.This way you are simply increasing the values.Also and as a logical operator will make it sure that the number only gets devided by 3 and 5 both

threes_and_fives = [x for x in range(1,16) if x%3 ==0 or x%5==0]
print threes_and_fives


#19

A post was split to a new topic: 16. Comprehending Comprehensions


#20