In: Computer Science
In this exercise we will practice using nested loops. You will write s program that prompts the user to enter an integer between 1 and 9 and displays a pyramid of numbers, as shown in the example below.
The program must validate the input given by the user and make sure that:
Here is a sample run:
Enter the number of lines (1 - 9): 10 Error: you must enter a value between 1 and 9. Try again. Enter the number of lines (1 - 9): 0 Error: you must enter a value between 1 and 9. Try again. Enter the number of lines (1 - 9): 4 1 212 32123 4321234
Notes:
How your program will be graded:
Language is python 3
#Try block
try:
    #User input value
    number = int(input("Enter the number of lines (1-9): "))
    #Valditing the number, till user gives correct input.
    while number<1 or number>9:
        print("Error: you must enter a value between 1 and 9. Try again.")
        number = int(input("Enter the number of lines (1-9): "))
    #This for loop is used for counting number of rows from 1 to number
    for i in range(1,number+1):
        #Printing spaces by subtracting i from number
        for j in range(number-i):
            print(" ",end="")
        #Printing number from higher to lower from 3 to 1 or 2 to 1
        for k in range(i,0,-1):
            print(k,end="")
        #After 2 to 1 we need to print 2 and so on
        #For 1 there will be no another value
        #So, I write if condition and printing from 2 to i+1
        if i!=1:
            for k in range(2,i+1):
                print(k, end="")
        #Printing new line
        print()
#Except block
except ValueError:
    print("Enter only digits")
Sample input and output:
Enter the number of lines (1-9): 10
Error: you must enter a value between 1 and 9. Try again.
Enter the number of lines (1-9): 0
Error: you must enter a value between 1 and 9. Try again.
Enter the number of lines (1-9): 5
1
212
32123
4321234
543212345
Enter the number of lines (1-9): 10
Error: you must enter a value between 1 and 9. Try again.
Enter the number of lines (1-9): 0
Error: you must enter a value between 1 and 9. Try again.
Enter the number of lines (1-9): 4
1
212
32123
4321234