簡體   English   中英

編程新手,學習python。 試圖讓這個程序工作

[英]New to programming, learning python. Trying to get this program to work

首先,鏈接到“問題”:

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。 我已經嘗試了幾天(至少這段代碼沒有給出錯誤消息......)我確信這是一個簡單的修復,但我只是不知道它會是什么。 真的很感激任何幫助。

編輯:在else語句中包含counter(),就像我以前在修補它時所做的那樣。 它現在調用計數器,但我也得到一個錯誤:

回溯(最近一次調用最后一次):文件“C:\\ Users \\ USER \\ Google Drive \\ School \\ PYTHON \\ 5_16_piEstimator.py”,第53行,在main()文件“C:\\ Users \\ USER \\ Google Drive \\ School \\ PYTHON \\ 5_16_piEstimator.py“,第49行,在主飛鏢()文件”C:\\ Users \\ USER \\ Google Drive \\ School \\ PYTHON \\ 5_16_piEstimator.py“第37行,用飛鏢ifDist()文件”C:\\ Users \\ USER \\ Google Drive \\ School \\ PYTHON \\ 5_16_piEstimator.py“,第20行,ifDist計數器()文件”C:\\ Users \\ USER \\ Google Drive \\ School \\ PYTHON \\ 5_16_piEstimator.py“,第23行,計數器數= count + 1 UnboundLocalError:賦值前引用的局部變量'count'

除了不調用你的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的本地(計數器)變量

永遠不會調用您的計數器函數,因此計數永遠不會增加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM