Home>

I'm new to python. It may be a very rudimentary question,
Please be kind to me. ..
I want to call num1 to num3 as below dynamically.
(Turn the for statement and output the value by referring to num1 to 3)
I was wondering if I could do it with the following code, but num is a variable
It doesn't seem to work.
I know you can do it by putting it in an array,
This time, I'm looking for a program that needs to be assigned to a variable.
I did a lot of research, but I didn't understand ...
Should I use eval or exec?
I wanted to write code using eval and exec,
I don't understand the meaning of such a built-in function, and I didn't know how to write it.
I'm sorry if you're a beginner and have heard something you don't understand.
I would be grateful if you could give me any advice.

num1 = A
num2 = B
num3 = C
for i range (1,4):
  num ='num' + str (i)
  print (num)
  • Answer # 1

    solved.

    print (eval (num))

  • Answer # 2

    Let's use an array
    Then you can specify it with a variable

  • Answer # 3

    list(list) Is used.

    nums = [None, A, B, C]
    for i in range (1,4):
      num = nums [i]
      print (num)