0

Adding a number to a text and making it a variable

Hi. I'm really new to all of this. The problem is kinda hard for me to explain. What can I do to make this piece of code work ---------------------------------- a1 = 90 a2 = 60 a3 = 55555 def a(number): var1 = 'a' + number return var1 print(a(1, 2, 3)) --------------------------------------- I want a single line of print to give me a list of a1-3 variables using this metod. like this output: 90, 60, 55555 if I do print(a('1')) it gives me a1 as an output but I want to get 90

21st Nov 2020, 7:50 PM
kluski śląskie
kluski śląskie - avatar
4 Respuestas
+ 4
use eval() function.. You can do like this : a1 = 90 a2 = 60 a3 = 55555 def a(number): var1 = 'a' +str(number) return var1 print(eval(a(1)),eval(a(2)),eval(a(3)))
21st Nov 2020, 8:11 PM
Jayakrishna 🇮🇳
+ 5
a1 = 90 a2 = 60 a3 = 55555 def a(*number): mylist = [] for x in number: var1 = eval('a' + str(x)) mylist.append(var1) return mylist print(*a(1, 2, 3)) ## remember...using eval is discouraged
21st Nov 2020, 8:24 PM
rodwynnejones
rodwynnejones - avatar
+ 5
Would you consider placing your values within a dictionary or list. You could then call the values as you need them, thus avoiding the use of eval. Example: a = [90, 60, 5555, 14, 27] print(*[a[i] for i in range(len(a))]) b = {1: 90, 2:60, 3: 5555,} print(*[b[i] for i in range(1,4)])
21st Nov 2020, 8:36 PM
Rik Wittkopp
Rik Wittkopp - avatar
0
Jayakrishna🇮🇳 rodwynnejones Cool guys! Both codes work perfectly. Thank you!!!!!
21st Nov 2020, 8:29 PM
kluski śląskie
kluski śląskie - avatar