Reputation: 67
This is basic again and I've searched throughout the website but I can't find anything that is specifically about this.
The problem is to write a function that takes an integer and returns a certain number of multiples for that integer. Then, return a list containing those multiples. For example, if you were to input 2 as your number parameter and 4 as your multiples parameter, your function should return a list containing 2, 4, 6, and 8.
What I have so far:
def multipleList(number, multiples):
mult = range(number, multiples, number)
print mult
A test case would be:
print multipleList(2, 9):
>>> [2, 4, 6, 8, 10, 12, 14, 16, 18]
My answer I get:
>>> [2, 4, 6, 8]
None
I know that range has the format (start, stop, step). But how do you tell it to stop after a certain number of times instead of at a certain number?
Upvotes: 1
Views: 138
Reputation: 1296
Another approach could be the following one
def mult_list(number, limit):
multiples = []
for i in xrange(1, limit+1):
multiples.append( number * i)
return multiples
For example: In [8]: mult_list(2,4) Out[8]: [2, 4, 6, 8]
In addition if I do not want parameters an empty list seems consistent with the regular data type:
In [10]: mult_list(2,0)
Out[10]: []
Upvotes: 0
Reputation: 6828
try range(number, number*multiples+1, number)
instead:
def multipleList(number, multiples):
return list(range(number, number*multiples+1, number))
print(multipleList(2, 9))
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18]
Upvotes: 2
Reputation: 250941
use (number*multiples)+1
as end value in range
:
>>> def multipleList(number, multiples):
mult = range(number, (number*multiples)+1 , number)
return mult
...
>>> print multipleList(2,9)
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> print multipleList(3, 7)
[3, 6, 9, 12, 15, 18, 21]
The default return value of a function is None
, as you're not returning anything in your function so it is going to return None
. Instead of printing mult
you should return it.
>>> def f():pass
>>> print f()
None #default return value
Upvotes: 0