0

I want to print the numbers in the same line to Fibonacci numbers.

Here is my code:

n = int(input("Enter n: "))
a = 0
b = 1
sum = 1
count = 1
print("Fibonacci numbers= ")
while(count < n):
    print(sum, end = " ")
    count += 1
    a = b
    b = sum
    sum = a + b

The output of this will be: Enter n: 10 Fibonacci numbers=

1 2 3 5 8 13 21 34 55 >

How do I put it like this: Enter n: 10

Fibonacci numbers= 1 2 3 5 8 13 21 34 55

Thanks.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
Ruby
  • 1
  • 1

1 Answers1

1

Solution

python print function would automatically append and new line sign "\n". To change that, just customize the end argument of the print function.

So, you just need

print("Fibonacci numbers= ", end="")

demo with comments.

n = int(input("Enter n: "))  # you input introduces an new line
a = 0
b = 1
sum = 1
count = 1
print("Fibonacci numbers=", end="")  # without new line
while(count < n):
    print(" {}".format(sum), end="") # without new line, use " " instead
    count += 1
    a = b
    b = sum
    sum = a + b
print("")  # only print a new line.
  • Output:

    Enter n: 6
    Fibonacci numbers= 1  2  3  5  8
    
Xin Cheng
  • 1,432
  • 10
  • 17