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?
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])
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.
you can use dictionary
variable = {}
variable['0'] = 4
variable['1'] = 7
x=1
print varibale[x]
will print 7
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.
Related
I am new to Python and I am trying to create multiple variables with the values of zero.
var1 = 0
var2 = 0
var3 = 0
so on...
How to do this in Python
You could use a list to store your values like this:
l = []
for i in range(10):
l.append(0)
It would work like this (almost what #CoolCoding123 has)
var1,var2, var3 = (0, 0, 0)
You almost never need to do this, i.e. create variables dynamically. But you could do it by altering the global variable dictionary. The below would create variables var0...var9 with every one set to 0:
varnames = ['var' + str(n) for n in range(10)]
for var in varnames:
globals()[var] = 0
However, don't do such evil things. Read up on data structures such as list and dicts.
As you asked how to create multiple variables with zero values, here is one way to do:
n = 5
data = {}
for i in range(5):
data["var%s" % i] = 0
Later on, if you need the value of a particular index i, then you can get the value using
value = data["var%s" % index]
I have recently undertook converting all of my older batch files towards running on Python 3.6 to allow for them to run on multiple OS's. During this process I have hit a wall, my question is how to best convert these following batch commands to something capable of being run in Python. I have looked around extensively and it has all been for naught. I am open to suggestions.
set number=1
set var%number%=[some value here]
I have already tried things similar to this in Python:
number = 1
("var"+str(number)) = [some value here]
As well as this to try to get the interpreter to process the variable I'm going to assign to done before I attempt assignment.
number = 1
var = ("var"+str(number))
(var) = [some value here]
The reason why I am trying to convert the first method is so that the program could initially set a changing value to 'var1' then 'var2' then 'var3' etc. Is this one of those things that is unique to batch files and not languages such as Python?
If you're trying to change the value of number then set the value by
number = 1
And change it again by doing the same
number = 6
Edit: I see what you're trying to do, it is better not to do this in Python and you should try to avoid it for multiple reasons, but anyways here's an example of using exec (assuming number equals to 1):
exec("var"+str(number)+"=0")
Which would run
var1=0
Like this answer says, you could just do:
numbers = [1, 2, 3]
for n in numbers:
exec('var_%d = [20]' % n)
print(var_1) # prints [20]
print(var_2) # prints [20]
print(var_3) # prints [20]
However, there are arguments against the usage of exec in that answer, so you should consider a dictionary. You can define as many keys (var1, var2, etc...) as you need.
if __name__ == '__main__':
v = {}
numbers = [1, 2, 3]
for n in numbers:
v['var' + str(n)] = 10 # initial value 10
print(v['var1']) # 10
print(v['var2']) # 10
print(v['var3']) # 10
v['var2'] = 20 # update value to 20
print(v['var2']) # 20
Or if you need more customization, maybe consider defining your own class?
class MyVar(object):
def set(self, number, value):
setattr(self, 'var' + str(number), value)
if __name__ == '__main__':
number = 1
v = MyVar()
v.set(number , 20)
print(v.var1) # prints 20
v.set(number , 40)
print(v.var1) # now prints 40
v.var1 = 50
print(v.var1) # now prints 50
It's hard to recommend anything else without knowing more about what you want to do.
I started lately to use Python instead of Matlab and I have a question to which the answer might be obvious but I can't figure it out yet.
I have the following module in python called shared_variables.py:
global a
global b
a = 2
b = 3
c = a
d = b
in my main.py script I do the following things:
import shared_variables
for i in range(1,4):
shared_variables.a += 1
shared_variables.b += 1
print 'a= ',shared_variables.a
print 'b= ',shared_variables.b
print 'c= ',shared_variables.c
print 'd= ',shared_variables.d
and the output is the following:
a= 3
b= 4
c= 2
d= 3
a= 4
b= 5
c= 2
d= 3
a= 5
b= 6
c= 2
d= 3
Basically c and d values are not updated at each iteration. How can I solve this problem? I am asking this question because I have written a longer program in which I need to share common values between different modules that i need to update at each different iteration.
The following lines set the values of the variables once (e.g., assign the current value of a to c):
a = 2
b = 3
c = a
d = b
It does not mean that c changes whenever a changes nor that d changes whenever b changes. If you want variables to change value you'll need to assign a new value to them explicitly.
Integers are immutable in Python. You can't change them.
a += 1 is a syntax sugar for a = a + 1 i.e., after the assignment a is a different int object. c is not a anymore.
If a and c were mutable objects such as lists then changing a would change c. c = a makes c and a both to refer to the same object i.e., c is a.
For example,
a = [0]
c = a
a[0] += 1
print(a, c) # -> [1] [1]
Here are nice pictures to understand the relation between names and objects in Python
c and d start out as references to the same value as a and b, not to the same memory position. Once you assign new values to a and b, the other two references won't follow.
Python values are like balloons, and variable names are like labels. You can tie a thread between the label (name) and the balloon (value), and you can tie multiple labels to a given balloon. But assignment means you tied a new balloon to a given label. The other labels are not re-tied as well, they still are tied to the original balloon.
Python integers are immutable; they remain the same balloon throughout. Incrementing a by adding 1 with the in-place addition operator (a += 1) still has to find another balloon with the result of a + 1, and tie a to the new integer result. If a was tied to a balloon representing 2 before, it'll be replaced by a new balloon representing the value 3, and a will be retied to that. You cannot take a marker to the integer balloon and erase the 2 to replace it with 3.
I am reading a book about Python and there is a special part in the book about Multiple-Target Assignments. Now the book explains it like this:
but I dont see use of this. This makes no sense for me. Why would you use more variables?
Is there a reason to do this? What makes this so different from using: a='spam'and then printing out a 3 times?
I can only think of using it for emptying variables in one line.
A very good use for multiple assignment is setting a bunch of variables to the same number.
Below is a demonstration:
>>> vowels = consonants = total = 0
>>> mystr = "abcdefghi"
>>> for char in mystr:
... if char in "aeiou":
... vowels += 1
... elif char in "bcdfghjklmnpqrstvwxyz":
... consonants += 1
... total += 1
...
>>> print "Vowels: {}\nConsonants: {}\nTotal: {}".format(vowels, consonants, total)
Vowels: 3
Consonants: 6
Total: 9
>>>
Without multiple assignment, I'd have to do this:
>>> vowels = 0
>>> consonants = 0
>>> total = 0
As you can see, this is a lot more long-winded.
Summed up, multiple assignment is just Python syntax sugar to make things easier/cleaner.
It's mainly just for convenience. If you want to initialize a bunch of variables, it's more convenient to do them all on one line than several. The book even mentions that at the end of the snippet that you quoted: "for example, when initializing a set of counters to zero".
Besides that, though, the book is actually wrong. The example shown
a = b = c = 'spam'
is NOT equivalent to
c = 'spam'
b = c
a = b
What it REALLY does is basically
tmp = 'spam'
a = tmp
b = tmp
c = tmp
del tmp
Notice the order of the assignments! This makes a difference when some of the targets depend on each other. For example,
>>> x = [3, 5, 7]
>>> a = 1
>>> a = x[a] = 2
>>> a
2
>>> x
[3, 5, 2]
According to the book, x[1] would become 2, but clearly this is not the case.
For further reading, see these previous Stack Overflow questions:
How do chained assignments work?
What is this kind of assignment in Python called? a = b = True
Python - are there advantages/disadvantages to assignment statements with multiple (target list "=") groups?
And probably several others (check out the links on the right sidebar).
You might need to initialize several variables with the same value, but then use them differently.
It could be for something like this:
def fibonacci(n):
a = b = 1
while a < n:
c = a
a = a + b
b = c
return a
(variable swapping with tuple unpacking ommited to avoid confusion as with the downvoted answer)
An important note:
>>> a = b = []
is dangerous. It probably doesn't do what you think it does.
>>> b.append(7)
>>> print(b)
[7]
>>> print(a)
[7] # ???????
This is due to how variables work as names, or labels, in Python, rather than containers of values in other languages. See this answer for a full explanation.
Presumably you go on to do something else with the different variables.
a = do_something_with(a)
b = do_something_else_with(b)
#c is still 'spam'
Trivial example and the initialization step questionably didn't save you any work, but it's a valid way to code. There are certainly places where initializing a significant number of variables is needed, and as long as they're immutable this idiom can save space.
Though as the book pointed out, you can only use this type of grammar for immutable types. For mutable types you need to explicitly create multiple objects:
a,b,c = [mutable_type() for _ in range(3)]
Otherwise you end up with surprising results since you have three references to the same object rather than three objects.
I wrote this small program to print multiplication tables. I was understanding the local variables then I added two variables with same name in each function. but it is running and I am not getting any 2 variables with same name error. Please help me understand the idea here -
def printMultiples(n):
i = 1
i = 5
while i <= 10:
print n*i, '\t',
i = i + 1
print
def printMultTable():
i = 1
i = 10
while i <= 10:
printMultiples(i)
i = i + 1
The variable i gets defined as soon as the function is run, it does not wait until the lines
i = 1
i = 10
are run. When the code is compiled, Python looks at every variable that is assigned in the function, and creates definitions for any that aren't declared to be global or nonlocal.
Each i = line will just change the value, it doesn't cause it to be defined again.
Here's what's happening in your script:
i = 1
creates the variable i and assigns the value 1 to it
i = 5
replaces the value held in i with 5
while i <= 10:
starts your loop
print n*i, '\t',
The first iteration of the loop will print n * 5 and a tab character
i = i + 1
increments i by one
There aren't two variables with the same name, there's one variable that is being assigned to twice.
i = 1 # i is declared and assigned to 1
i = 5 # the same i is reassigned to 5
In python, symbols are just names for variables. They are do not allocate memory as they do for say, C/C++. So what you are doing is simply reassigning the values to 'i' in each case.
You're not actually creating two variables with the same name; your second i = is reassigning i to a new value, same as i = i + 1 is setting i to the value of i + 1.
There are more Pythonic ways to deal with looping a fixed number of times, by the way:
for i in range(1, 11):
printMultiples(i)
This will execute printMultiples for values starting in 1 and less than 11.