Reputation: 1
I am trying to create a function in Python. This function should be able to create a list of whole numbers less than or equal to the number provided. I've created an empty list, a variable called y
and a while loop. In this while loop, as long as y <= x
, the results of the subsequent equations are appended to the empty list, and y
increments by 1
. However, when I call this function, I get a list with only one element. How can I fix this?
def fff(x):
numbers = []
y = 2
while(y <= x):
x = x - (x - y)
numbers.append(x)
y += 1
return numbers
>>> fff(10)
[2]
Upvotes: 0
Views: 82
Reputation: 180540
If you are trying to mimic the range function then this is how you would do it:
def fff(x):
numbers = []
y = 1
while(y <= x):
numbers.append(y)
y += 1
return numbers
Upvotes: 0
Reputation: 2182
If you look at this line x = x - (x - y)
and think of your inputs, you will see the problem. if x initially equals 10, then x - (x - y) equals 2, and y will equal 3, therefore breaking out of your loop.
Upvotes: 2
Reputation: 83421
That function already exists, more or less.
Python 2
def fff(x):
return range(1,x+1)
Python 3
def fff(x):
return list(range(1,x+1))
Upvotes: 4