0

Python conditional. Can you please help me to solve this problem below?

I have got this problem from sololearn (print all number in range 1 to 100 exclusively if the number is divisible by 3: for i in range(1,100,...?...): if i % 3 == 0: print(i) I guess the correct answer can be obtained if an only if the step incremental is 1. What do you think? If we choose other number for the value of step, for example 0, 2,3,4,5 etc then it won't include all number which is multiplication of 3 or divisible by 3. Tjank you for your feedback.

4th Nov 2024, 1:49 AM
Oliver Pasaribu
Oliver Pasaribu - avatar
4 odpowiedzi
+ 3
Wouldn't this yield the same thing, but more efficiently? for i in range(3, 100, 3): print(i)
4th Nov 2024, 3:13 AM
Jerry Hobby
Jerry Hobby - avatar
+ 3
Jerry Hobby is right. Don't start with 1, start with 3, and use step=3 generator expression version: print(*(i for i in range(3,100,3)),sep='\n')
4th Nov 2024, 3:53 AM
Bob_Li
Bob_Li - avatar
+ 3
Oliver Pasaribu as stated just this will print all numbers between 1 and 100 that are multiples of 3 or divisible by 3 print(*list(range(3,100,3)))
4th Nov 2024, 5:41 AM
BroFar
BroFar - avatar
+ 3
"slaps own forehead with superfluous generator expression.."😅 BroFar omg, yes, that is the Pythonic way. but... range is a generator, so even shorter: print(*range(3,100,3)) or if the numbers have to be on new lines print(*range(3,100,3), sep='\n')
4th Nov 2024, 6:00 AM
Bob_Li
Bob_Li - avatar