开发者

why am I getting one line of numbers? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago. 开发者_StackOverflow社区
num = int(input('Enter a number:'))

for i in range(0, num, 1):
    for j in range(0, i):
        print(num, end =" ")

for i in range(num, 0, -1):
    for j in range(0, i):
        print(num, end=" ")


Because end=" " overrides the default behaviour which is to print a newline \n.

The effect of this is to separate each number by a space rather than a newline \n.


This line print(num, end=" ") will only print the initial number num. Are you perhaps wanting one of your iterating numbers (i or j)?

Also end=" " suppresses the normal behavior of appending a \n to the end of the print statements.


EDIT

Going by your comment, I think you want this (assuming num=3):

3 
3 3 
3 3 3 
3 3 
3 

Which you can get by adding print statements that only provide newlines like so:

def diamond(number):
    for i in range(0, number, 1):
        for j in range(0,i):
            print(number, end=" ")
        print("")

    for i in range(number, 0, -1):
        for j in range(0, i):
            print(number, end=" ")
        print("")

If you want each row to have a number equal to row size, change the number in the print statements to i.


EDIT 2

Do you mean you want this?

Enter a number:5

1 
2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1 

The reason the user input from before won't work is probably due to the ordering of the python file or how you called the method. If you write this into a .py file and run it through IDLE you can get that.

def diamond(number):
    for i in range(0, number, 1):
        for j in range(0,i):
            print(i, end=" ")
        print("")

    for i in range(number, 0, -1):
        for j in range(0, i):
            print(i, end=" ")
        print("")


num = int(input('Enter a number:'))
diamond(num)

If you mean you want

1
1 2
1 2 3
1 2
1

then you need to replace those i's with j+1 (remember, the range is starting at 0).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜