这是我的源代码:
def farmer_johns():
r = int(input('Enter the radius of the circle in feet:'))
#check for valid input
try:
while input >= 0 :
# area of brown
#area of square - area of circle
import math
pi = math.pi
area_square = (r+r)**2
area_circle = pi* r**2
area_brown = area_square - area_circle
print('The area of the brown shaded region is {:.2f} feet^2.'.format(area_brown))
#turtle graphics set up
import turtle
wn = turtle.Screen()
a = turtle.Turtle()
a.pensize(5)
#draw circles
a.pencolor('green')
a.penup()
a.goto(r,r)
a.pendown()
a.circle(r)
a.penup()
a.goto(r,-r)
a.pendown()
a.circle(r)
a.penup()
a.goto(-r,-r)
a.pendown()
a.circle(r)
a.penup()
a.goto(-r,r)
a.pendown()
a.circle(r)
#square
a.pencolor('blue')
a.penup()
a.goto(r,r+r)
a.pendown()
a.goto(-r,r+r)
a.goto(-r,-r+r)
a.goto(r,-r+r)
a.goto(r,r+r)
#middle region
a.pencolor('#654321')
a.fillcolor('#b5651d')
a.begin_fill()
a.penup()
a.goto(r,r)
a.pendown()
a.circle(r,-90)
a.penup()
a.goto(0,r+r)
a.right(180)
a.pendown()
a.circle(r,-90)
a.penup()
a.goto(-r,r)
a.left(-180)
a.pendown()
a.circle(r,-90)
a.penup()
a.goto(0,0)
a.left(180)
a.pendown()
a.circle(r,-90)
a.end_fill()
#writing
# a.write('The area of the brown shaded region is {:.2f} feet^2.'.format(area_brown))
except ValueError:
print('invaild input')
except TypeError:
print('invaild input')
问题是,当我输入字母作为输入时,我得到了这个:
farmer_johns()以英尺为单位输入圆的半径:Ee Traceback(最近一次调用最后一次):文件“”,第1行,文件“C:\ Users \ SueAnn \ Desktop \ Comp Sci \ Projects \ project_3 \ farmer john again.py“,第19行,在farmer_johns r = int(输入('以英尺为单位输入圆的半径:'))ValueError:基数为10的int()的无效文字:'Ee'
“Except:TypeError”代码行有效但“Except:ValueError”
1 回答
正如'Mike Scotty'指出的那样,你是
try .. except
错误的代码行!更改为以下内容:
您可以将
while True:
与break
结合使用 .