-1

This is my code, I am trying to add recursion so when the user inputs a number less than 0, it will not only say Invalid Entry, but it will also bring up the original prompt for them to try another number. I am also trying to change my for loop into a while loop. Any help?

space = '\t'
star = '*'
size = int(input("Enter the height of the pattern (must be greater than 0): "))

if size <= 0 :
    print("Invalid Entry!\n")

for i in range(0, size) :
    star_count = 2 * i - 1

    line = space * (size - i - 1)

    if i == 0 :
        line += "1"
    else :
        line += str(2 * i) + space

    line += (star + space) * star_count

    if i > 0 :
        line += str(2 * i + 1)

    print(line)

The output should look like this

                1
            2   *   3
        4   *   *   *   5
    6   *   *   *   *   *   7
8   *   *   *   *   *   *   *   9
  • 1
    Rather than recursion you may want to check the user input in a loop. The loop will terminate if user provide a value greater than 0 – kuro May 13 '21 at 05:00
  • your code never will display the output as you intend to. Partial solution to your query is this change below lines to if size <= 0 : print("Invalid Entry!\n") This line while size <= 0 : print("Invalid Entry!\n") size = int(input("Enter the height of the pattern (must be greater than 0): ")) – Vivs May 13 '21 at 05:03
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). And the code from [Creating a pyramid with numbers separated by asterisks](https://stackoverflow.com/q/67512014/1431750). – aneroid May 13 '21 at 05:42

2 Answers2

0

What's wrong with for loop?

space = '\t'
star = '*'
while 1:
    size = int(input("Enter the height of the pattern (must be greater than 0): "))
    if size > 0:
        break
    print("Invalid Entry!")
    print("Please Try again.")

i = 0
while i < size:
    star_count = 2 * i - 1

    line = space * (size - i - 1)

    if i == 0 :
        line += "1"
    else :
        line += str(2 * i) + space

    line += (star + space) * star_count

    if i > 0 :
        line += str(2 * i + 1)
    i += 1

    print(line)
Xenox Inno
  • 138
  • 1
  • 5
0

The limitation to this code will be you always have to input 3 to get the answer which intend to get as per your query

space = '\t'
star = '*'
size = int(input("Enter the height of the pattern (must be greater than 0): "))

while size <= 0 :
    print("Invalid Entry!\n")
    size = int(input("Enter the height of the pattern (must be greater than 0): "))

for i in range(0, size) :
    star_count = 2 * i - 1

    line = space * (size - i - 1)
    if i == 0 :
        line += "1"
    else :
        line += str(2 * i) + space
    line += (star + space) * star_count
    if i > 0 :
        line += str(2 * i + 1)
    print(line)
Vivs
  • 447
  • 4
  • 11