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
CodePudding user response:
It would work like this (almost what @CoolCoding123 has)
var1,var2, var3 = (0, 0, 0)
CodePudding user response:
You could use a list to store your values like this:
l = []
for i in range(10):
l.append(0)
CodePudding user response:
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.
CodePudding user response:
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]