+ 2

what is the purpose of using end = ' ' in a print statement?

def fib(n): a,b=0,1 while a<n: print(a, end = ' ') a, b = b, a+b print() >>> fib(100) 0 1 1 2 3 5 8 13 21 34 55 89

22nd May 2018, 4:46 AM
ranjith kumar
ranjith kumar - avatar
3 Answers
+ 3
Using your code for this particular purpose is ok. But if wanted to add a ',' between each numbers the similar to your code is: def fib(n): a,b=0,1 while a<n: print(a, end = ',') a, b = b, a+b print() >>> fib(100) 0,1,1,2,3,5,8,13,21,34,55,89, The last comma doesn't look so good. So there is a better approach: def fib(n): a,b=0,1 nums=[] while a<n: nums.append(a) a, b = b, a+b print(','.join(nums)) >>> fib(100) 0,1,1,2,3,5,8,13,21,34,55,89 So try to learn to use string methods to be more creative. 😊😉😊
22nd May 2018, 12:03 PM
Cyrus Ornob Corraya
Cyrus Ornob Corraya - avatar
+ 16
print() ends all printed text with a newline (\n) by default. "end" is an optional argument that makes print() end the text with something else. Empty quotes means nothing else will be printed (your next text will print on the same line). ' ' will print a space (which is what your code is doing).
22nd May 2018, 5:00 AM
Tamra
Tamra - avatar
+ 2
thanks all...
22nd May 2018, 1:57 PM
ranjith kumar
ranjith kumar - avatar