Jet Jet
Jet Jet

Reputation: 11

How to make variables reassign every time a loop is done?

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.

Upvotes: 1

Views: 74

Answers (4)

Phoenix
Phoenix

Reputation: 1788

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)))

Upvotes: 0

martineau
martineau

Reputation: 123443

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

Upvotes: 1

moctarjallo
moctarjallo

Reputation: 1615

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)

Upvotes: 0

James Tollefson
James Tollefson

Reputation: 893

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)]

Upvotes: 2

Related Questions