Search code examples
pythonstring-formatting

How do I print fibonacci numbers in a column format


I need some help, trying to print in the following format:

00: 0   
01: 1   
02: 1   
03: 2   
04: 3   
05: 5   
06: 8   
07: 13  
08: 21  
09: 34  
10: 55  

My codes:

import math
import time

start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2

def  main():
    num = int(input("How many Fibonacci numbers should I print? "))

    for number in range(0,num+1):
        val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
        print(format(round((val)),'3d'))

main()

Solution

  • def  main():
        stnum = input("How many Fibonacci numbers should I print? ")
        dig = len(stnum)
        num = int(stnum)
    
        for number in range(0,num+1):
            val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
            #print(format(round((val)),'3d'))    
            print(f"{number:0{dig}d}: {val:.0f}")
    

    dig is the number of digits of the amount of Fibonacci numbers: if you ask for 100 Fibonacci numbers, dig is 3. I use formatted string literals (available since python 3.6) to format the output.
    {number:0{dig}d} prints the integer number with dig leading 0.
    {val:.0f} prints a float with no digits after the dot.

    If you have an older version of python and formatted string literals are not available, replace the print statement with this:

    print("{}: {:.0f}".format(str(number).zfill(dig), val))