Josh Alexandre
Josh Alexandre

Reputation: 127

Print a sequence on one line in Python 3

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

Upvotes: 3

Views: 14901

Answers (4)

Pankaj Kumar
Pankaj Kumar

Reputation: 1

this is coaded in java. the two nested loop are just to print the pattern and stop varialbe is used to terminate loop when we get the required sequence of integer.

import java.io.*;
import java.util.Scanner;

public class PartOfArray {
    
    public static void main(String args[])
    {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int stop =1;   // stop variable 
     /*nested loops to print pattern */    
    for(int i= 1 ; i <= n    ; i++)
    {
        for(int j = 1 ; j<=i ; j++)
        {
            if (stop > n){ break;} //condation when we print the required no of elements
            System.out.print(i+ " ");
            stop++;
        } 
    } 
    
    }
}

Upvotes: -2

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

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=" ")

Upvotes: 4

Trev Davies
Trev Davies

Reputation: 391

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)

Upvotes: 2

tobias_k
tobias_k

Reputation: 82899

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))

Upvotes: 5

Related Questions