+ 1
Is there is possible to create like this?🤔
Enter how many variables you need? 5 Your variables are a,b,c,d,e,f Enter the value for your variables 1 2 3 4 5 Printing variables a=1 b=2 c=3 d=4 e=5
5 odpowiedzi
+ 3
'''
In C there exists something like this, where you can make a string a variable name through the preprocessor. I don't know about such an option in Python though.
If you cap the amount of variables, you could define an array of letters (i.e. string) and loop over it.
'''
var_str = "abcdefghijklmnopqrstuvwxyz"
var_sub_str = var_str[:5]
var_values = [1,2,3,4,5]
for i, var in enumerate(var_sub_str):
print(var,"=",var_values[i])
# but still the "variable name" and its value is actually separated using two arrays
# you could also combine it to a dictionary, where the letter is the key and the value the value
d = dict()
for i, var in enumerate(var_sub_str):
d[var] = var_values[i]
print(d)
print(d['c'])
+ 3
If i understand right. Not really in this way.
You can store in 2d array where first element is a key (like a) and second is a value(like 1).
But i don't think you can receive the name of a variable to initialize a variable with same name.
+ 3
You can in fact do this using the exec function:
>>> exec('x = 10')
>>> x
10
---------------
But in this case I think that would be unnecessary since you can easily do the same using a dictionary or a list.
And if you think about it, it does make a bit more sense to store all these related values in one variable, rather than using those many different variables.
It would also make it easier to loop over, not to mention you can also use the same variable names elsewhere in your code.
---------------
Here's a working example:
https://trinket.io/python3/5c6ee449ca
+ 1
D'lite after get variables name i need assign a value to each variables is this possible
+ 1
Just A Rather Ridiculously Long Username
Thanks bro