1

I've tried both of these versions:

import random 
def r(n):
    random.seed(1234)
    for i in range(n):
        x=random.uniform(-1,1)
        y=random.uniform(-1,1)
        return (x,y)

import random 
def r(n):
    random.seed(1234)
    while n>0:
        n-=1
        x=random.uniform(-1,1)
        y=random.uniform(-1,1)
        return (x,y)

But both only produce 1 point. I'm hoping to make it produce n random points (x,y) and have it print out all n points.

1
  • 1
    You got only one point because the return statement will finish your r() function in the first iteration of the for loop. You can return all your n points from the function, as the previous answer informed. Or you can create a function that will return just a pair of points, and call it repeatedly n times. Commented Nov 9, 2020 at 0:24

4 Answers 4

2

You just need to accumulate your results in a list and return the list. This works:

import random 
def r(n):
    random.seed(1234)
    results = []
    for i in range(n):
        x=random.uniform(-1,1)
        y=random.uniform(-1,1)
        results.append((x,y))
    return results

results = r(10)
print(results)

Out:

[(0.9329070713842775, -0.11853480164929464), 
(-0.9850170598828256, 0.8219519248982483), 
(0.878537994727528, 0.16445514611789824), 
(0.3431269629759701, -0.8321235463258321), 
(0.5329618655835926, -0.5263804492737645), 
(-0.9383719565467801, 0.577545434472567), 
(-0.3078220688057538, 0.24656295007833706), 
(0.23163139020723045, -0.7028907225834249), 
(-0.6338187051801367, -0.7711740606226247), 
(-0.9707624390261818, -0.026496918790483326)]
Sign up to request clarification or add additional context in comments.

Comments

1

You can create the list very succinctly using a list comprehension as shown below:

import random
random.seed(1234)

def r(n):
    """ Create, print out, and return a list of `n` random points. """
    points = [(random.uniform(-1,1), random.uniform(-1,1)) for _ in range(n)]
    print(points)
    return points

Comments

0

Use print instead of return in both of your cases

import random 
def r(n):
    random.seed(1234)
    for i in range(n):
        x=random.uniform(-1,1)
        y=random.uniform(-1,1)
        print(x,y)

Comments

0

At risk of confusing you before you've mastered the basics... If you change the return keyword to the yield keyword, it becomes a generator function which returns an iterator.

# this is a generator function now
def r(n):
    random.seed(1234)
    for i in range(n):
        x=random.uniform(-1,1)
        y=random.uniform(-1,1)
        # `yield` instead of `return`
        yield (x,y)

# collect iterator into list
print(list(r(3)))

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.