Print a sequence on one line in Python 3

10,052

Solution 1

Judging by your first (working) code, you are probably using Python 2. To use print(n, end=" ") you first have to import the print function from Python 3:

from __future__ import print_function
if n>-6 and n<93:
    while (i > n):
        print(n, end=" ")
        n = n+1
    print()

Alternatively, use the old Python 2 print syntax, with a , after the statement:

if n>-6 and n<93:
    while (i > n):
        print n ,
        n = n+1
    print

Or use " ".join to join the numbers to one string and print that in one go:

print " ".join(str(i) for i in range(n, n+7))

Solution 2

You can use a range using print as a function and specifying the sep arg and unpack with *:

from __future__ import print_function

n = int(raw_input("Enter the start number: "))
i = n + 7

if -6 < n < 93:
    print(*range(n, i ), sep=" ")

Output:

Enter the start number: 12 
12 13 14 15 16 17 18

You are also using python 2 not python 3 in your first code or your print would cause a syntax error so use raw_input and cast to int.

For python 3 just cast input to int and use the same logic:

n = int(input("Enter the start number: "))
i = n + 7

if -6 < n < 93:
    print(*range(n, i ), sep=" ")

Solution 3

You can use a temporary string like so:

if n>-6 and n<93:
temp = ""
while (i > n):
    temp = temp + str(n) + " "
    n = n+1
print(n)
Share:
10,052
Josh Alexandre
Author by

Josh Alexandre

Updated on June 28, 2022

Comments

  • Josh Alexandre
    Josh Alexandre almost 2 years

    I've managed to get the sequencing correct, however I'm unsure how to have it print on the same line. I've got this:

    n = input ("Enter the start number: ")
    i = n+7
    
    if n>-6 and n<93:
        while (i > n):
            print n
            n = n+1
    

    and have tried this:

    n = input ("Enter the start number: ")
    i = n+7
    
    if n>-6 and n<93:
        while (i > n):
            print (n, end=" ")
            n = n+1