how to print text in stars box with loop

Viewed 1327

How to print text in stars box with loop

Example I want:
input1: input text
input2: high of stars
ex:
input1 = Your Name
input2 = 3
output:

***********
*Your Name*
***********
this my code i have now
def function(text):
    """start"""
    name = len(text)
    num = int(input())
    for i in range(num):
        for j in range(name + 2):
            if i == 0 or j == 0 or i == num - 1:
                print("*", end="")
        print()
function(input())
output is
***********
*
***********

What should I do next.

4 Answers

You can multiply a string. "*" * 10 == '**********' - you don't need the inner for loop then.

Also, you need to print the thing as it should be, not make a border first - you can't just type onto what's already printed.

def function(text):
    """start"""
    name_length = len(text) #renamed your variable, the name was confusing
    num = int(input())
    for i in range(num):
        if i == 0 or i == num - 1: #removed inner loop
            print("*" * (name_length+2))
        else:
            print("*{}*".format(text) #added printing the text and right border
function(input())

You didn't say what should happen for a higher number. I assumed the name should be repeated.

def function(text):
    """start"""
    name = len(text)
    num = int(input())
    text_num = int((num - 1) / 2)

    for i in range(num):
        for j in range(name + 2):
            if i == 0 or i == num - 1:
                print("*", end="")
            elif i == text_num:
                if j == 0 or j == name + 1:
                    print("*", end="")
                else:
                    print(text[j-1], end="")
        print()
function(input())

Another option is to format by line as opposed to character.

Something like this could work:

def function(text):
    """start"""
    name = len(text)
    num = int(input())
    for i in range(num):
        if i == 0 or i == num - 1:
            print('*' * (name + 2))
        elif i == int(num / 2):
            print('*' + text + '*')
        else:
            print('*' + ' ' * name + '*')


function(input())

With num = 3 outputs:

***********
*your name*
***********

With num = 5 outputs:

***********
*         *
*your name*
*         *
***********

You can build the box in a list and then substitute the name at the middle line:

name = "your name"
num  = 3

box              = ["*"+(" "*len(name))+"*"]*num
box[0] = box[-1] = "*" * (len(name)+2)
box[num//2]      = f"*{name}*"
print("\n".join(box))

***********
*your name*
***********
Related