0

I would like to assign the result of this function in a variable as a string

def fib(n): 
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

fib(100)

...prints from 1 to 89

I would like to assign the output to x as in the example:

x = fib(100) 
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Instead of `print`, use `return`. – Irfan434 Jun 11 '17 at 13:07
  • There is a difference between *printing* and *returning*... – Willem Van Onsem Jun 11 '17 at 13:07
  • Irfan434 is correct, however you may also need to put all the numbers into a string as they're generated, then return the string. On which point, are you wanting to return a list of numbers or a string? – Jack Parkinson Jun 11 '17 at 13:08
  • so after the function runs i want to return the output as a string – Ionut Zamfir Jun 11 '17 at 13:17
  • When defining a function, consider that it is far easier to create a string from whatever the function returns than it is to extract anything from a pre-made string. Also, defer things like printing as long as possible. – chepner Jun 11 '17 at 13:37
  • so, in this example how do i do this? – Ionut Zamfir Jun 11 '17 at 14:06
  • In this example, at the start of the function you should define an empty string: ```output = ""```. Then, instead of printing the character, you want to add it to the string, so instead of ```print(a, end=' ')``` you want ```output += a + " "``` (you need to add a space there as well, so that all the numbers are separated.) And finally, instead of ```print()``` at the end, you want to return the output, so do ```return output``` – Jack Parkinson Jun 11 '17 at 14:46

0 Answers0