0

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?

7
  • Do you want something like a switch-case? If So, you can use a dict. def variable(x): return {0:4,1:7}[x]? Commented May 13, 2016 at 16:20
  • 1
    do you want an array that is called variable? then you could call variable[0] to get a value Commented May 13, 2016 at 16:21
  • 1
    do you maybe want to write a function that maps x to different values?? Commented May 13, 2016 at 16:26
  • The psedocode you're showing doesn't define define variable as a variable, but as a function of x. Commented May 13, 2016 at 16:27
  • Am I right to presume Python is your first programming language? You should really be reading a Python tutorial. Commented May 13, 2016 at 16:30

4 Answers 4

1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Rob. This is very helpful!
0

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.

Comments

0

you can use dictionary

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

    x=1
    print varibale[x]

will print 7

Comments

0

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.

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.