I wrote a code that can find the multiples of 3 of a given number, but I want to make it so that it will only print out the multiples of 3 in a given range. How can I do that?
Here's my code:
def findMultiples(x):
for x in range(1, x 1):
if x % 3 == 0
print(x)
findMultiples(120)
CodePudding user response:
You don't need to loop through every number to see if it's a multiple of 3. Once you've found one, you can step through multiples only.
def findMultiples(x, y, multiple):
# find the first value that's a multiple
for i in range(x, x multiple):
if i % multiple == 0:
break
# step through the remaining values
for j in range(i, y, multiple):
print(j)
findMultiples(121, 143, 3)
123
126
129
132
135
138
141
CodePudding user response:
def findMultiples(x, y):
for i in range(x, y 1):
if i % 3 == 0 and i % 5 == 0:
print(i)
findMultiples(120, 240)
I still don't sure what do you mean, but I think this is what you want. In your for
loop, you set the wrong loop variable, it should be anything else than x
.
CodePudding user response:
Use another variable name in for loop ("i" for example):
def findMultiples(x):
for i in range(1, x 1):
if i % 3 == 0:
print(i)
findMultiples(120)
CodePudding user response:
You can use filter function
The 1st argument is the function based on which filtering will happen lambda x: x%3==0
returns True or False for an input x. The input x comes from the list [i for i in range(a, b)]
which is the 2nd argument to the filter function.
>>> a = 100
>>> b = 200
>>> print(list(filter( lambda x:x%3==0 , [i for i in range(a, b)])))
[102, 105, 108, 111, 114, 117, 120, 123, 126, 129, 132, 135, 138, 141, 144, 147, 150, 153, 156, 159, 162, 165, 168, 171, 174, 177, 180, 183, 186, 189, 192, 195, 198]