TypeError:Python 3中+ =:'float'和'NoneType'的不受支持的操作数类型
有没有人知道为什么我不断收到此错误?我真的很新,我会很感激别人的帮助。这是我的代码:TypeError:Python 3中+ =:'float'和'NoneType'的不受支持的操作数类型
import turtle as t
import math as m
import random as r
raindrops = int(input("Enter the number of raindrops: "))
def drawSquare():
t.up()
t.goto(-300,-300)
t.down()
t.fd(600)
t.lt(90)
t.fd(600)
t.lt(90)
t.fd(600)
t.lt(90)
t.fd(600)
t.lt(90)
def location():
x = (r.randint(-300, 300))
y = (r.randint(-300, 300))
t.up()
t.goto(x, y)
return x, y
def drawRaindrops(x, y):
t.fillcolor(r.random(), r.random(), r.random())
circles = (r.randint(3, 8))
radius = (r.randint(1, 20))
newradius = radius
area = 0
t.up()
t.rt(90)
t.fd(newradius)
t.lt(90)
t.down()
t.begin_fill()
t.circle(newradius)
t.end_fill()
t.up()
t.lt(90)
t.fd(newradius)
t.rt(90)
while circles > 0:
if x + newradius < 300 and x - newradius > -300 and y + newradius < 300 and y - newradius > -300:
t.up()
t.rt(90)
t.fd(newradius)
t.lt(90)
t.down()
t.circle(newradius)
t.up()
t.lt(90)
t.fd(newradius)
t.rt(90)
newradius += radius
circles -= 1
area += m.pi * radius * radius
else:
circles -= 1
return area
def promptRaindrops(raindrops):
if raindrops < 1 or raindrops > 100:
print ("Raindrops must be between 1 and 100 inclusive.")
if raindrops >= 1 and raindrops <= 100:
x, y = location()
area = drawRaindrops(x, y)
area += promptRaindrops(raindrops - 1)
return x, y, area
def main():
t.speed(0)
drawSquare()
x, y, area = promptRaindrops(raindrops)
print('The area is:', area, 'square units.')
main()
t.done()
我假设“+ =”有问题,但我不知道是什么。我很确定该区域正确返回。请帮助。 :)
两件事情,我注意到:
1. promptRaindrops
返回一个元组
我相信你并没有打算。但是,当你说area += promptRaindrops(raindrops - 1)
,添加的是元组到area
,这是一个整数。要解决这个问题,你应该说area += promptRaindrops(raindrops - 1)[2]
得到返回的区域。然而,由
2.您的基本情况产生你的错误不返回值
在promptRaindrops
,返回功能,每当1 <= raindrops <= 100
的递归调用。但是,当它超出范围时,它不返回任何内容,只会打印一条消息。您的功能将总是超出该范围,因为如果您继续减少传入的值promptRaindrops
,它最终将低于1.当它返回时,返回None
(因为您没有返回任何内容)。 None
通过对该点进行的每次递归调用起泡,并且您将不可避免地将None
添加到area
。添加一个返回元组的返回语句,你的错误应该消失。
在promptRaindrops()
你有递归调用执行+=
操作到promptRaindrops()
这将不任何回报(NoneType
)如果raindrops
在给定范围之外。
根据程序的行为方式,应该返回一些东西,或者不应该使用给定范围之外的值调用它。
你无法避免调用超出范围的函数;减去传递的值最终会低于1. –
当然,您可以在调用函数之前在输入参数中使用一个简单的条件。这会挫败递归函数的全部目的,但我只想指出任何可能的解决方案。 – Aerows
你的函数'promptRaindrops'有2个路径通过它。当它第一个不能返回任何东西时,因此使用默认的'None'返回值。它应该总是返回相同的类型,否则做一些事情来表明外部错误,比如抛出异常。 –