有人知道我为什么老是犯这个错误吗?我是新来的,希望有人能帮我。这是我的密码:
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()我假设"+=“有问题,但我不知道是什么。我相当肯定这个地区被归还了。请帮帮忙。:)
发布于 2016-09-14 01:10:12
我注意到两件事:
1. promptRaindrops返回一个元组
我相信您不是有意这样做的,但是当您说area += promptRaindrops(raindrops - 1)时,您将向area添加一个元组,这是一个整数。要解决这个问题,您应该使用area += promptRaindrops(raindrops - 1)[2]来返回该区域。但是,您的错误是由
2.基本大小写不返回值
在promptRaindrops中,无论何时1 <= raindrops <= 100,都会返回函数的递归调用。但是,当它超出该范围时,它什么也不返回,只打印一条消息。您的函数将始终超出该范围,因为如果您不断减少传入promptRaindrops的值,它最终将降至1以下。当它返回None时(因为您没有返回任何内容)。None会在每一个递归调用中出现气泡,您将不可避免地将None添加到area中。添加返回返回元组的语句,您的错误就会消失。
https://stackoverflow.com/questions/39481039
复制相似问题