1

Hey so I was trying to practice this exercise in python, but the code was only available in java, the code goes as follows:


void setup() {
  size(640, 360);
  dim = width/2;
  background(0);
  colorMode(HSB, 360, 100, 100);
  noStroke();
  ellipseMode(RADIUS);
  frameRate(1);
}

void draw() {
  background(0);
  for (int x = 0; x <= width; x+=dim) {
    drawGradient(x, height/2);
  } 
}

void drawGradient(float x, float y) {
  int radius = dim/2;
  float h = random(0, 360);
  for (int r = radius; r > 0; --r) {
    fill(h, 90, 90);
    ellipse(x, y, r, r);
    h = (h + 1) % 360;
  }
}

I have the following code for python:

 def setup():
    size(800,800)
    background(0)
    colorMode(HSB, 360,100,100)
    noStroke()
    ellipseMode(RADIUS)
    frameRate(1)    


def draw():
    background(0)
    for x in range(0, width, x = x + width/2):
        drawGradient(x, height/2)
        
   
    
def drawGradient(a,b):
    radius = width/2
    h = random(0,360)
    for r in range(radius, 0, radius= radius - 1):
        fill(h, 90,90)
        ellipse(a,b,r,r)
        h = (h+1) % 360

I am getting the following error

UnboundLocalError: local variable 'x' referenced before assignment

1
  • shouldn't the dim be iterated backwards though, to create the radial circles? i was also confused as to how python knows the second argument, like if its less than or greater than Commented Sep 12, 2021 at 14:45

1 Answer 1

4

Read about the range() function and for-loops. In python a typical for loop is:

for i in range(0, 10, 1)
    print(i)

This loop prints the numbers from 0 to 9.


The correct syntax for your code is:

def draw():
    background(0)
    for x in range(0, width+1, width/2):
        drawGradient(x, height/2)
def drawGradient(a,b):
    radius = width/4
    h = random(0,360)
    for r in range(radius, 0, -1):
        # [...]

Complete example:

def setup():
    global dim
    size(640, 360)
    dim = width/2
    background(0);
    colorMode(HSB, 360, 100, 100)
    noStroke()
    ellipseMode(RADIUS)
    frameRate(1)    

def draw():
    background(0)
    for x in range(0, width+1, width/2):
        drawGradient(x, height/2)
        
def drawGradient(x, y):
    radius = dim/2
    h = random(0, 360)
    for r in range(radius, 0, -1):
        fill(h, 90, 90)
        ellipse(x, y, r, r)
        h = (h+1) % 360
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.