Pezbone
Pezbone

Reputation: 115

How to create continuously changing variables in Python

In pseudocode, you can create variables such as 'variable(x)', having x as a forever changing number therefore creating multiple different variables. For example, if:

x = 0
variable(x) = 4
x = 1
variable(x) = 7

then printing 'variable(0)' would give you the result '4' and printing 'variable(1)' would output '7'. My question is: is this possible to do in Python?

Upvotes: 0

Views: 1107

Answers (4)

Marcus Müller
Marcus Müller

Reputation: 36442

Seeing as your pseudocode doesn't declare a variable, but a function, it's pretty easy to build something like this:

def my_function(x):
    return 3*x + 4

Then you can

print my_function(0)
4
print my_function(1)
7

Of course, you can do pretty much everything in that function; the mathematical linear mapping I used was just an example. You could be reading a whole file, looking for x in it and returning e.g. the line number, you could be tracking satellite positions and return the current position of satellite Nr. x... This is python, a fully-fledged programming language that supports functions, like pretty much every non-declarative programming language I can think of.

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168726

You can't use exactly that syntax in Python, but you can come close using a dict.

variable = {}
x = 0
variable[x] = 4
x = 1
variable[x] = 7
print(variable[0])
print(variable[1])

If the domain of your variable is non-negative integers, and you know the largest integer a priori, then you could use a list:

variable = [None]*2
x = 0
variable[x] = 4
x = 1
variable[x] = 7
print(variable[0])
print(variable[1])

Upvotes: 1

Evyatar Sivan
Evyatar Sivan

Reputation: 612

you can use dictionary

    variable = {} 
    variable['0'] = 4
    variable['1'] = 7

    x=1
    print varibale[x]

will print 7

Upvotes: 0

f p
f p

Reputation: 3223

The nearest could be a list:

x = []
x.append(4)
x.append(7)

print(x[0])
4
print(x[1])
7

And if you don't want to use a count as identifier you can use Rob's answer.

Upvotes: 0

Related Questions