Rafał
Rafał

Reputation: 53

Function in a for loop

this is my code:

import random

a = 10000
b = random.random()
c = 2

def random1(a,b,c):
    z = a * b * c
    print(z)

def random2():
    for i in range(10):
        random1(a,b,c)

random2()

I have a problem with my output, because function random2() gives me ten exactly the same numbers, for example:

10652.014111193188
10652.014111193188
10652.014111193188
10652.014111193188
10652.014111193188
10652.014111193188
10652.014111193188
10652.014111193188
10652.014111193188
10652.014111193188

Where is the mistake? Or I can't use function that gives me random numbers in a for loop :/. Everything is fine, when I'm looping formula instead of function, the problem shows only when function is in for loop.

Upvotes: 0

Views: 84

Answers (3)

pashute
pashute

Reputation: 4053

Actually you shouldn't be putting b into the random functions at all! If you want the function Random1 to create a random number multiplied by a and c:

import random

a = 10000
# remarked: b = random.random()  
c = 2

def random1(a,c):
    b = random.random()
    z = a * b * c
    print(z)



def random2(): # I would call it testRandom1
    for i in range(10):
        random1(a ,c)

random2() # test random1 ten times.

Upvotes: 0

David Zemens
David Zemens

Reputation: 53623

A simple change should do it, bind b to random.random, and then call b() while passing to random1

import random

a = 10000
b = random.random
c = 2

def random1(a,b,c):
    z = a * b * c
    print(z)

def random2():
    for i in range(10):
        # call b() here instead of b
        random1(a,b(),c)

random2()

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

b never changes, even though you initialized it with a random value. Neither a nor c ever changes, either, but you probably expected that.

Upvotes: 0

Related Questions