Home > Software engineering >  How can I remove the 'none' out of the output?
How can I remove the 'none' out of the output?

Time:10-12

I was supposed to make a diamond out of this and I have successfully done so but I have a problem. Here is my code

k = 7
def triangle(k):
    a = (2*k) -1
    k = 3
    for x in range(0,a 1):
        if x % 2 != 0:
            f = int((a - x)/2)
            g = f"{'#'*f}{'*'*x}{'#'*f}"
            print(g)
def diamond(k):
    a = (2 * k) - 1
    k = 3
    for x in reversed(range(0, a)):
        if x % 2 != 0:
            f = int((a - x) / 2)
            g = f"{'#' * f}{'*' * x}{'#' * f}"
            print(g)

l = f"{triangle(k)}\n{diamond(k)}"
print(l)

Along with the diamond, there are also two 'none' appearing underneath like this in the output..

######*######
#####***#####
####*****####
###*******###
##*********##
#***********#
*************
#***********#
##*********##
###*******###
####*****####
#####***#####
######*######
None
None

How can I print the output without including the none in the output??

CodePudding user response:

Calling the functions already prints the output. Printing the return values (None) makes little sense. That being said, this can be tremendously simplified:

def up_and_down(n):  # 1,2, ..., n, ..., 2, 1
    return (*range(1, n), *range(n, 0, -1))

def diamond(n):
    for i in up_and_down(n):
        print((n-i)*'#', *('*' for _ in up_and_down(i)), (n-i)*'#', sep='') 

>>> diamond(7)
######*######
#####***#####
####*****####
###*******###
##*********##
#***********#
*************
#***********#
##*********##
###*******###
####*****####
#####***#####
######*######

CodePudding user response:

Here's a modification on @schwobasggl's answer, using f-strings that works in Python 3.6

def up_and_down(n):  # 1,2, ..., n, ..., 2, 1
    return (*range(1, n), *range(n, 0, -1))


def diamond(n, pad='#', fill='*'):
    w = (2 * n) - 1

    for i in up_and_down(n):
        print(f'{fill * len(up_and_down(i)):{pad}^{w}}')

It should end up with the same result:

>>> diamond(7)

######*######
#####***#####
####*****####
###*******###
##*********##
#***********#
*************
#***********#
##*********##
###*******###
####*****####
#####***#####
######*######

If you want to print a triangle (the top half of the diamond), you can iterate over only the first half of up_and_down in the outer loop. Another way is to just iterate over range(1, n 1) - that is 1, 2, 3 for n=3 - as shown below:

def triangle(n, pad='#', fill='*'):
    w = (2 * n) - 1

    for i in range(1, n 1):
        print(f'{fill * len(up_and_down(i)):{pad}^{w}}')

It looks like that should now work to print just the top half of the diamond above:

>>> triangle(7)

######*######
#####***#####
####*****####
###*******###
##*********##
#***********#
*************
  • Related