Python Forum

Full Version: Printing sequence of numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello

I am trying to print a print the folliwing

123...n

So, for example, if n = 5, we would print 12345

I played around and Googled, and wrote this

for i in range(1,n):
print (i, end="")

This printed 12, so I changed to:

for i in range(1,n+1):
print (i, end="")

Which seemed to work.

My questions.

1. Why do I need to add n+1 rather than just n
2. In order to get the sequence up to n added, I had to write the end="" bit. I understand in Python 2, this would have been print(i), which makes more sense

Can someone explain how the end="" works?
Python interactive interpreter's built-in help is always your friend:

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
Use Q-key to exit help.

You can have implicit answer regarding n+1 by using help(range): '/../ Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. /../'

More explicit answer is that Python uses zero based indexing. Why? You can read Guido van Rossum's Why Python uses 0-based indexing or E.W.Dijkstra Why numbering should start at zero (not Python specific).