I had to write a program to print the below pattern.
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Now , the code which is given is as :
num = int(input())
for i in range (1,num 1):
for j in range (1 , i 1):
print(j, end = " ")
print()
But I don't understand that how a new line will be started after each loop without using \n . My teacher told that the print() in the last is used to break line . But I don't understand that what is going on .
CodePudding user response:
See this ref
If no objects are given, print() will just write
end
.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
// From above print function signature we know end is just '\n'.
CodePudding user response:
Your teacher is right. By default, print() wraps. That said, you have to modify your code because this not return the output that you need. There are many more optimized ways to do this but we'll base it on what you've done.
Try this
num = int(input())
for i in range(num, 0, -1):
for j in range(1, i 1):
print(j, end=' ')
print()
CodePudding user response:
print()
is a function in python 3.x. It works kinda like System.out.println();
in Java, in that it prints to a new line by default:
>>> print('line 1')
>>> print()
>>> print('line2')
line 1
line 2
You can control this via the end
keyword ('\n'
by default). Example:
>>> print('something', end = ' ')
>>> print('some other thing')
something some other thing
So when someone says print()
is used to break line, it's the same as adding a newline char.
CodePudding user response:
By default, print function has end='\n' as argument. That's why it provides a new line after its' execution. you can change that with anything, like end=' '(this will put an extra space ), end = '.' (this will add a full stop at the end)
the print function bears this Infos
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)