5

for example in this code below the with the end the integers stay on the same line but without the it does not.

num = 5
for i in range(1, num +1):
  for j in range(num, i-1, -1):
  print(j, end="")
print()
5
  • 7
    help(print) not working? Commented Dec 13, 2015 at 23:05
  • 4
    This is unrelated to the for loop... Commented Dec 13, 2015 at 23:06
  • 5
    The question contains the answer! Commented Dec 13, 2015 at 23:07
  • I'm voting to close this question as off-topic because really, stack overflow is better than that. Commented Dec 13, 2015 at 23:33
  • For what it's worth, although you can do print("hello world!") in Python2, print("hello world!", end="") throws a SyntaxError. Commented Dec 14, 2015 at 0:15

2 Answers 2

6

The end statement for printing in Python allows the programmer to define a custom ending character for each print call other than the default \n

For instance, if you have a function that is to print all values within a list on the same line, you do:

def value(l):
    for items in l:
        print(l, end=' ')

So if the list argued to this function contains the values [1, 2, 3, 4], it will print them in this manner: 1 2 3 4. If this new ending character parameter was not defined they would be printed:

1
2
3
4

The same principle applies for ANY value you provide for the end option.

Sign up to request clarification or add additional context in comments.

Comments

3

In Python 3, the default ist end='\n' for the print function which is a newline after the string is printed.

To suppress this newline, one can set end='' so that the next print starts in the same line.

This is unrelated to the for loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.