找到你要的答案

Q:Print integer number multiple times using single for loop and without using string in Python

Q:打印整数多次采用单循环和不使用字符串在Python

For e.g I have number n=5 as input and i want to print my output like this :-

1
22
333
4444

But using for loop once and without using string anywhere in program

例如,我有数字N = 5作为输入,我想打印输出我这样:—

1
22
333
4444

但在程序中任何地方使用一次和不使用字符串

answer1: 回答1:

Using math, it would be,

for i in range(1,n):
    print i*(10**i-1)/9

Check repdigit for more information.

使用数学,这将是,

for i in range(1,n):
    print i*(10**i-1)/9

更多信息请纯位数。

answer2: 回答2:

You need to specify no newline at the print statement. In python 2, that means using sys.stdout.write or importing the python3 print function

from __future__ import print_function # python 2 only
def expand(n):
    for i in range(1, n+1):
        for _ in range(i):
            print(i, end="")
        print(" ", end="")
    print("")


expand(5)
1 22 333 4444 55555

After more details were posted, and a link to the original question on hackerrank, I realize this is not actually a valid solution. Still, I will leave it here in case it is helpful.

你需要在打印语句没有指定换行符。在Python 2,这意味着使用sys.stdout.write或者进口Python3打印功能

from __future__ import print_function # python 2 only
def expand(n):
    for i in range(1, n+1):
        for _ in range(i):
            print(i, end="")
        print(" ", end="")
    print("")


expand(5)
1 22 333 4444 55555

在更多的细节被公布,并链接到在HackerRank原题,我意识到这不是一个有效的解决方案。不过,我会把它留在这里,以防有帮助。

python  for-loop