0

Does anyone know how to save a string with multiple prints in for function? I am able to draw a pyramid, but I am stuck on writing it to a file.

Here is my code:

n = int(input("Enter number: "))
file_1 = open("pyramid.txt", "a")

for i in range(1, n + 1):
    for j in range(1, n - i + 1):
        file_1.write(" ", end="")
    for j in range(1, i + 1):
        file_1.write("* ", end="")
    print("")

file_1.close()
CodenameLambda
  • 1,486
  • 11
  • 23

1 Answers1

1

Your code is a little bit broken. You are printing to create a newline, but write the rest to the file.

To output the pyramid to stdout (the terminal output):

n = int(input("Enter number: "))
for i in range(1, n + 1):
    for j in range(1, n - i + 1):
        print(" ", end="")
    for j in range(1, i + 1):
        print("* ", end="")
    print("")

To output it to the file:

n = int(input("Enter number: "))
file_1 = open("pyramid.txt", "a")

for i in range(1, n + 1):
    for j in range(1, n - i + 1):
        file_1.write(" ")
    for j in range(1, i + 1):
        file_1.write("* ")
    file_1.write("\n")

file_1.close()

Shortened:

n = int(input("Enter number: "))
print("\n".join(" " * (n - i) + "* " * i for i in range(1, n + 1)))

or

n = int(input("Enter number: "))
f = open("pyramid.txt", "w")
f.write("\n".join(" " * (n - i) + "* " * i for i in range(1, n + 1)) + "\n")
f.close()
CodenameLambda
  • 1,486
  • 11
  • 23