取两个数字作为输入,宽度和高度。创建一个正方形,其中每行有WIDTH数字和HEIGHT行

时间:2014-10-07 20:11:43

标签: python range

这是我到目前为止的代码。我的出局需要看起来类似于:

Please enter the width: 5

Please enter the height: 2

1 2 3 4 5

6 7 8 9 10

或其他例子是

Please enter the width: 2

Please enter the height: 3

1 2 

3 4

5 6

def main():

    # variables width and height
    width  = 0
    height = 0

    # Takes input from user for variables
    width  = int( input( "Please enter the width: " ) )
    height = int( input( "Please enter the height: " ) )

    i = 0
    while i < height:
        for x in range( 1, ( width * height ) + 1 ):
            print( x, "", end = "" )

main()

目前,我的代码会在一行中打印出所有内容。

我无法弄清楚如何让线条保持打印数字直到达到宽度,下拉新线并继续直到达到高度。

2 个答案:

答案 0 :(得分:0)

所以,我的建议是使用嵌套for循环。在伪代码中,

set the number variable to 0
for each line,
    for each number in the line,
        increase the number
        and print it
    end each line with a \n

答案 1 :(得分:0)

您还可以使用modulo查找新行的位置:

if i%width == 0:
     print("")

这样你只需要一个计数器来增加。这是一个完整的例子,通过检查要打印的数字的长度来打印具有统一形状的整洁盒子:

def main():
    # variables width and height
    width = 0
    height = 0

    # Takes input from user for variables
    width = int(input("Please enter the width: "))
    height = int(input("Please enter the height: "))

    i = 0
    max_num = width * height
    while i < max_num:
        i += 1
        needed_space = len(str(max_num)) - len(str(i))
        print(i, " " * needed_space, end='')
        if i % width == 0:
            print("")


main()