编程新手,学习python。试图得到这个程序

2024-09-30 06:11:58 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,链接到“问题”:

http://interactivepython.org/courselib/static/thinkcspy/Labs/montepi.html

我一直都很好,直到把柜台摆好。一旦我弄清楚了,我有信心做剩下的事。在

import turtle
import math
import random

fred = turtle.Turtle()
fred.shape("circle")

wn = turtle.Screen()
wn.setworldcoordinates(-1,-1,1,1)

def main():

    count = 0

    def ifDist():
        if fred.distance(0,0) > 1:
            fred.color("blue")
        else:
            fred.color("red")
            counter()   

    def counter():
        count = count + 1
        return count

    def darts():
        numdarts = 2
        for i in range(numdarts):
            randx = random.random()
            randy = random.random()

            x = randx
            y = randy

            fred.penup()
            fred.goto(randx, randy)
            ifDist()
            fred.stamp()
            fred.goto(randx, -randy)
            ifDist()
            fred.stamp()
            fred.goto(-randx, randy)
            ifDist()
            fred.stamp()
            fred.goto(-randx, -randy)
            ifDist()
            fred.stamp()

    darts()

    print(count)

main()


wn.exitonclick()

它一直为计数器打印0。我已经试了几天了(至少这段代码没有给出错误信息…),我确信这是一个简单的修复,但我不知道它会是什么。任何帮助都将不胜感激。在

EDIT:在else语句中包含counter(),就像我之前修改它时所做的那样。它现在会调用计数器,但我也会收到一个错误:

回溯(最近一次呼叫): 文件“C:\Users\USER\Google Drive\School\PYTHON\5\u 16_piEstimator.py“,第53行,英寸 主() 文件“C:\Users\USER\Google Drive\School\PYTHON\5\u 16_piEstimator.py“,第49行,主要内容 飞镖() 文件“C:\Users\USER\Google Drive\School\PYTHON\5\u 16_piEstimator.py“,第37行,省道 ifDist() 文件“C:\Users\USER\Google Drive\School\PYTHON\5\u 16_piEstimator.py,ifDist中的第20行 计数器() 文件“C:\Users\USER\Google Drive\School\PYTHON\5\u 16_piEstimator.py“,第23行,柜台 count=计数+1 UnboundLocalError:赋值前引用了局部变量“count”


Tags: 文件pydefcountgooglerandomdrivefred
2条回答

除了不调用您的counter()函数之外,这无论如何也行不通。在

正如@Perkins在评论中提到的,你不能在你的范围之外修改引用。不能递增count,因为int在Python中是不可变的。count = count + 1正在创建一个新的int对象并丢弃旧对象。新实例需要绑定到count变量

假设Python3,你可以说count是“非本地的”

def counter():
    nonlocal count
    count = count + 1
    return count

这将告诉Python可以在main中更改count的绑定,而不是尝试使用名为count的本地(计数器)变量

您的counter函数永远不会被调用,因此计数永远不会增加。在

相关问题 更多 >

    热门问题