Python 3中如何在一行上打印一个序列

3

我已经成功地进行了排序,但是我不确定如何将其打印在同一行上。我的代码如下:

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

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

我尝试过以下方法:

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

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

2
一旦您将输入转换为 int,此代码即可正常工作。那么,到底哪些方面没有达到您的期望呢? - idjaw
4个回答

5

从你的第一段(可用)代码来看,你可能使用的是Python 2。要使用print(n, end=" "),你首先需要从Python 3中导入print函数:

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

或者,可以使用旧版的Python 2 print语法,在语句后面加上,

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

或者使用" ".join将数字连接成一个字符串并一次性打印出来:

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

看起来我需要的帮助比我想象的要多!感谢您指出我安装了错误版本的 Python,这解释了很多问题。真的非常感谢您的帮助和建议! - Josh Alexandre

4
你可以使用print函数并指定sep参数来创建一个范围,并使用*进行解包:
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=" ")

输出:

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

你在第一个代码中使用的是Python 2而不是Python 3,否则你的print会导致语法错误,所以请使用raw_input并转换为int。

对于Python 3,只需将input转换为int并使用相同的逻辑:

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

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

1
感谢您的帮助,Padraic! - Josh Alexandre

2
您可以这样使用临时字符串:
if n>-6 and n<93:
temp = ""
while (i > n):
    temp = temp + str(n) + " "
    n = n+1
print(n)

感谢 Remuze 的帮助! - Josh Alexandre

-2
这是用Java编写的代码。两个嵌套循环仅用于打印模式,stop变量用于在获得所需整数序列时终止循环。
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++;
        } 
    } 
    
    }
}

2
欢迎来到SO。这似乎并没有回答OP的问题,因为它明确要求帮助Python。请查看如何回答以获取更多详细信息。 - alan.elkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接