jdf / Processing.py-Bugs

A home for all bugs and feature requests about Python Mode for the Processing Development Environment.
41 stars 8 forks source link

Non numericals in parenthesis don't work. #192

Closed Keir-Clyne closed 6 years ago

Keir-Clyne commented 7 years ago

Was trying to emulate the random.choice() function by generating a list and then using the random() number function to generate a number to choose from the list as follows:

list = ["hello", "goodbye", "haha"] a = random(0,2) text = list[a]

but for some reason processing doesn't allow this. Not sure if there is some kind of random.choice() function I'm missing (Although I can't seem to find one)

tildebyte commented 7 years ago

random should work. You should probably post some more info; version of Processing.py, platform... Most importantly, some kind of output giving more detail about the failure ("processing doesn't allow this" is pretty vague).

Keir-Clyne commented 6 years ago

Sorry for the vague answer.

I'm using Processing 3.3.5 with Python mode build 3026

If I use the code:

a = random(0,2)
alist = ["a", "b", "c"]
print(list[a])

The error message I get is:

processing.app.SketchException: TypeError: list indices must be integers
    at jycessing.mode.run.SketchRunner.convertPythonSketchError(SketchRunner.java:248)
    at jycessing.mode.run.SketchRunner.lambda$2(SketchRunner.java:122)
    at java.lang.Thread.run(Thread.java:748)

For some reason processing doesn't allow non-numerical list indicies (So alist[example] where example is not a number).

I'm pretty new to python and processing so not sure if I'm missing something simple but there doesn't seem to be anything in the tutorials about it. Thanks for any information

jdf commented 6 years ago

That's right; array or tuple indexes have to be integers. It wouldn't mean anything to pick the 1.2nd element of a list.

import random

alist = ["a", "b", "c"]
print(random.choice(alist))
villares commented 6 years ago

Hi @Keir-Clyne,

So random(0,2) will produce a float between 0 and 2 (2 not included), then you might want to use int(random(3)) like:

alist = ["a", "b", "c"]
for _ in range(20):
    r = random(3)
    i = int(r)
    choice = alist[i]
    print (r, i, choice)