【问题标题】:Print a sequence on one line in Python 3在 Python 3 中的一行上打印一个序列
【发布时间】:2016-03-24 13:49:23
【问题描述】:

我已设法使排序正确,但我不确定如何将其打印在同一行上。我有这个:

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

【问题讨论】:

  • 一旦您将输入转换为int,此代码就可以工作。究竟是什么不符合您的期望?

标签: python python-3.x printing sequence


【解决方案1】:

从您的第一个(工作)代码来看,您可能正在使用 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 版本错误,这说明了很多。非常感谢您的帮助和建议!
【解决方案2】:

您可以使用 print 作为函数并指定 sep arg 并使用 * 解包:

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,否则您的打印会导致语法错误,因此请使用 raw_input 并强制转换为 int。

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

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

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

【讨论】:

  • 感谢帕德莱克的帮助!
【解决方案3】:

您可以像这样使用临时字符串:

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

【讨论】:

  • 感谢 Remuze 的帮助!
【解决方案4】:

这是用java编写的。两个嵌套循环只是打印模式,当我们得到所需的整数序列时,停止变量用于终止循环。

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++;
        } 
    } 
    
    }
}

【讨论】:

  • 欢迎来到 SO。这似乎没有回答 OP,因为它明确要求 Python 的帮助。详情请查看how-to-answer
猜你喜欢
  • 1970-01-01
  • 2012-11-19
  • 2011-08-01
  • 2021-10-20
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
相关资源
最近更新 更多