-1

For context, I'm a student learning Python with a lesson package called CodeHS. We were instructed to use Python to draw a target shaped image. This is done by guiding around a sprite on the screen. However, it seems that no matter what it is that I do, I receive an error message on line 4 stating, local variable 'radius' referenced before assignment on line 4 I'm not sure what it is that I'm doing wrong here. If there is someone out there who thinks that they may have an answer that fits this situation, please let me know.

This is my first time posting a question on StackOverflow. Because of this, I may have not given enough information or made myself clear. If this is the case, please let me know. I want to learn:)

Here is an image showing the lesson dashboard if this helps.

Below is a copy of the code I've written.

radius = 25
def target():
    for i in range(4):
        circle(radius)
        right(90)
        penup()
        forward(25)
        pendown()
        left(90)
        radius = radius + 25
target()

Thanks, everyone!

ForceBru
  • 41,233
  • 10
  • 61
  • 89
logori
  • 9
  • 1
  • 5
    Does this answer your question? [Local variable referenced before assignment in Python?](https://stackoverflow.com/questions/18002794/local-variable-referenced-before-assignment-in-python) – AMC Mar 25 '20 at 16:56

2 Answers2

2

Assigning to radius inside the function makes it a local variable, so the global variable is completely shadowed. Unless you need radius to be used outside the function, it should be initialized in the function itself.

def target():
    radius = 25

    for i in range(4):
        circle(radius)
        right(90)
        penup()
        forward(25)
        pendown()
        left(90)
        radius = radius + 25
target()
chepner
  • 446,329
  • 63
  • 468
  • 610
  • 1
    Ok. Interesting. Thank you for this. I tested it in the system and it worked flawlessly. Really appreciate the help! – logori Mar 25 '20 at 17:00
1

what you want to do is pass radius into your function like so:

def target(radius=25):
    """put your code here"""
acushner
  • 8,972
  • 1
  • 32
  • 32