Python Forum
Printing sequence of numbers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Printing sequence of numbers
#1
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?
Reply
#2
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).
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,427 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  How can I found how many numbers are there in a Collatz Sequence that I found? cananb 5 3,777 Nov-23-2020, 05:15 PM
Last Post: cananb
  Convert list of numbers to string of numbers kam_uk 5 3,018 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  Printing a number sequence not working properly deepsen 6 3,025 Oct-12-2019, 07:43 PM
Last Post: deepsen
  Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 4,112 Dec-05-2017, 09:48 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020