Adi219
Adi219

Reputation: 4814

Refer to a previous calculation in python?

I was wondering if there's a way to refer to a previous part of a calculation in the same statement.

For example:

(random.randint(1, 2) * 10) + ... ## Is there a way to refer to the random number 
                                  ## previously  calculated, which will go in
                                  ## the space of the ellipsis?

I know this could be done using a variable, but ideally I'm looking for a one-liner.

Thanks!

Upvotes: 1

Views: 63

Answers (2)

Mike Müller
Mike Müller

Reputation: 85442

If you are up to a, rather unreadable, one-liner that uses (random.randint(1, 2) * 10) only once, you can do something like this:

[x + y for x, y in [[(random.randint(1, 2) * 10)] * 2]][0]

Clearly, using a variable is the preferred way.

Upvotes: 0

Anton vBR
Anton vBR

Reputation: 18906

The simple answer is No, there is no way..

This is what I mean with: this is what functions are for. (Ofc you could say that this is what variables are for too - but it goes hand in hand).

import random

func = lambda x: x*10 + x  # function alt1 

def func(x):               # function alt2
    return x*10 + x

And call it with:

func(random.randint(1, 2)) # and this can now in turn be used inside formulas

For instance you can now do:

def calculate_something(x):
    return x*x

calculate_something(func(random.randint(1, 2)))

Upvotes: 1

Related Questions