Reputation: 557
I was trying to define a simple function to find the range between two floats, and this is what I got:
def item(number, terminator, step):
while number < terminator:
return (number)
number += step
item(1.00, 1.12, 0.01)
The console doesn't print any errors, it doesn't print None
, it just doesn't do anything. It runs the program and does nothing. I am very confused. What is wrong with my code?
Upvotes: 0
Views: 74
Reputation: 1121554
There are two things wrong:
You are not printing anything. The item()
function returns and you ignored the return value. The Python interactive interpreter echoes almost everything you do but a regular script requires you to explicitly print.
You are returning the first value of the range. return
ends a function.
You could build a list of values first, and return that, then print the result:
def item(number, terminator, step):
items = []
while number < terminator:
items.append(number)
number += step
return items
print(item(1.00, 1.12, 0.01))
Demo:
>>> def item(number, terminator, step):
... items = []
... while number < terminator:
... items.append(number)
... number += step
... return items
...
>>> print(item(1.00, 1.12, 0.01))
[1.0, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09, 1.1, 1.11]
Alternatively, use yield
instead of return
to turn your function into a generator, and loop over the results:
def item(number, terminator, step):
while number < terminator:
yield number
number += step
for value in item(1.00, 1.12, 0.01):
print(value)
which produces:
>>> def item(number, terminator, step):
... while number < terminator:
... yield number
... number += step
...
>>> for value in item(1.00, 1.12, 0.01):
... print(value)
...
1.0
1.01
1.02
1.03
1.04
1.05
1.06
1.07
1.08
1.09
1.1
1.11
Upvotes: 2