0

I'm new to python and I am trying to figure out how do I enter an error message if the user inputs a number less than zero. Here is my code to give you a better understanding and I thank you all in advance for any advice.

# Python Program printing a square in star patterns. 

length = int(input("Enter the side of the square  : "))

for k in range(length):
    for s in range(length):
        if(k == 0 or k == length - 1 or s == 0 or s == length - 1):
            print('*', end = ' ')
        else:
            print('*', end = ' ')
    print()
Subbu VidyaSekar
  • 2,503
  • 3
  • 21
  • 39
  • Not an answer to your question but if I may offer a comment from a coding perspective. In your nested for loop, your `if` statement doesn't do anything. Both the `if` and the `else` outcome results in `print('*', end = ' ')`. – ramzeek Mar 09 '22 at 03:25
  • Thanks for the constructive feedback. It means a lot :) – karen sandoval Mar 10 '22 at 04:58

2 Answers2

1

Here is a simple and straight forward way to use a while loop to achieve this. Simple setting an integer object of check to 0. Then the while loop will evaluate check's value, then take user input, if the user input is greater than 0, let's set out check object to 1, so when we get back to the top of the loop, it will end.

Otherwise, if the if check fails, it will print a quick try again message and execute at the top of the loop again.

check = 0
while check == 0:
    length = int(input("Enter the side of the square  : "))
    if length > 0:
        check = 1
    else:
        print("Please try again.")
0xhughes
  • 2,703
  • 4
  • 26
  • 38
0

You can use this code after the input statement and before for loop.

       if length < 0 :
       Print("invalid length")
       Break