I've written a code to print a Fibonacci sequence up to a certain value input by the user. I need the output to start a new line after every 4th element.
Here is my code:
number = int(input("Enter a positive number: \n"))
f1, f2 = 0, 1
count = 1
fibonacci = [f1]
while count < number:
fn = f1 f2
f1 = f2
f2 = fn
fibonacci.append(f1)
count = 1
print(fibonacci)
CodePudding user response:
While not changing priginal fibonacci
list, you can print your values like this.
Instead of
print(fibonacci)
you could use this:
for i in range(0, len(fibonacci), 4):
print(fibonacci[i:i 4])
CodePudding user response:
You already have a counter so I guess what you want is that every time it reaches a multiple of 4, use print('\n')
CodePudding user response:
number = int(input("Enter a positive number: "))
def fabronic(n):
if n<=1:
return n
else:
return fabronic(n-1) fabronic(n-2)
count,n=0,0
while n<number:
print(fabronic(n),end=' ')
count =1
if count==4:
print()
count=0
n=n 1
input=Enter a positive number: 15
output=
0 1 1 2
3 5 8 13
21 34 55 89
144 233 377
By using list
n=0
mylist=[]
while n<number:
mylist.append(fabronic(n))
n=n 1
for item in range(0,len(mylist),4):
print(mylist[item:item 4],sep=' ',end='\n')
output=
Enter a positive number: 15
[0, 1, 1, 2]
[3, 5, 8, 13]
[21, 34, 55, 89]
[144, 233, 377]