Anders Andersson
Anders Andersson

Reputation: 61

Instead of printing, returning the value of whole the string instead

Currently working on an assignment where I want to print stars as triangles, the code is currently looking like this (very basic, I know):

def triangelbasupp(n,m):
    for a in range(0,m):
        print((n*" "),(m*"*"))
        m=m-2
        n=n+1
        if m<=0:
            break

When I enter, for example (3,1) I will get first 3 stars in the first row, then 1 star. This code is working fine, the problem is that for the assignment, I want to ONLY return the whole string that constitutes the triangle, it also has to contain the '\n' for switching row. Does anyone have a clue how I can do this?

Upvotes: 1

Views: 64

Answers (2)

Ohad Eytan
Ohad Eytan

Reputation: 8464

Instead of printing, initialize an empty string and use the string concatenation operator to build the string:

def triangelbasupp(n,m):
    s = ""
    for a in range(0,m):
        s += n*" " + m*"*" + "\n"
        m=m-2
        n=n+1
        if m<=0:
            break
    return s

Upvotes: 2

tobias_k
tobias_k

Reputation: 82929

Collect the lines in a list, then join them with \n and return.

def triangelbasupp(n,m):
    lines = []
    for a in range(0,m):
        lines.append(n*" " + m*"*")
        ...
    return "\n".join(lines)

Or shorter:

def triangelbasupp(n, m):
    return "\n".join(("*"*i).center(n) for i in range(m, 0, -2))

Upvotes: 2

Related Questions