How do the code make to do something if code doesn't get the expected TYPE in python

Question:

In this custom-made function, I try to calculate the area of a circle. So if the user inputs not an integer as the Count of circles I want to go back again to Count of Circle and I can’t figure out how I should do it. same goes for Value of angle

”’def circlearea (r):
print ("Calculating Area Of A Circle")
radius = r
print ("Radius Is ", radius)
pi = 22/7

# Count Of Circles Section 
circleLoop = 1
while circleLoop == 1:

    circles = input("Count Of Circle: ")

    if type(circles) is not int:
        circles = int(circles)
        circleLoop = 2
    else :
        print (323)
        circleLoop = 1
        

# Value Of Angle Section 
angleLoop = 1
while angleLoop == 1:
    
    angle = input("The Value Of Angle: ")

    if angle is int or float:
        angle = float(angle)
        break
    else :
        print (False)
        print ("Invalid Angle Please Try Again !!")
    
area = pi*radius**2*(angle/360)*circles
print ("Area Of This Circle Is: ", area)'''
Asked By: Hiran

||

Answers:

you need to handle this case using try excapt. Try like this

# Count Of Circles Section 
circleLoop = 1
while circleLoop == 1:

    circles = input("Count Of Circle: ")
    try:
        circles = int(circles)
    except:
        print("invalid")
        continue # if its not integer it will continue to loop again

    if type(circles) is not int:
        circles = int(circles)
        circleLoop = 2
    else:
        print(323)
        circleLoop = 1
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.