Newbie
Newbie

Reputation: 15

Return to second prompt if user input triggers Error (Python)

How do I loop back to previous user input(width) instead of asking user to re-enter the height variable again after ValueError is triggered.

while True:
    try:
        l=int(input("Length : "))
        w=int(input("Width : "))
        area=l*w
        perimeter=2*(l+w)
        print("Area of Rectangle : ",area)
        print("Perimeter of Rectangle : ",perimeter)
    except ValueError:
 
       print("Enter a numeric value")

Output: Output

Upvotes: 1

Views: 40

Answers (1)

user15801675
user15801675

Reputation:

One possible solution is to create 2 while loops, each, with one input.

while True:
    try:
        l=int(input("Length : "))
        break
    except ValueError:
        print("Enter a numeric value")
while True:
    try:
        w=int(input("Width : "))
        break
    except ValueError:
        print("Enter a numeric value")
area=l*w
perimeter=2*(l+w)
print("Area of Rectangle : ",area)
print("Perimeter of Rectangle : ",perimeter)    

Upvotes: 1

Related Questions