1

So for example num = 1010, so num is 4 digits long, can you create 4 variables automatic?

for example:

num = 1010
len(num)

num_2 = whatever
num_3 = whatever
num_4 = whatever
num_5 = whatever

because num got 4 digits, you add 4 extra variables (doesn't matter which name) so if num would be 5 digits, you had num_2 - num_6 (so its 2, 3, 4, 5, 6) and so on.. so if there are more digits, it creates automatic new variables (or less digits, less variables)

because to write it with if it would take long, to create when num could be 1 but also 1000 (with input() )

1 Answers1

2

Use dictionary instead of multiple variables with almost like same name

num = 1010
length = len(str(num))

res = {i+1:str(num)[i-1] for i in range(1, length+1)}
res[1] = num

This gives a better and easy way to access variables

And the num[1] is to store the original value of the num variable, you can remove it if you don't need

Your required values will be stored in the res dictionary

If you want to use the num name to access values like num_ which you are familiar with (i guess) then change res to num

num = res

And access the first digit of 1010 (here, 1) like num[2]

Or you can also use a simple list to store them like

res = [num, *[i for i in iter(str(num))]]

Here, your required variable values will be in the res list

Or if you still want the num_format variables, then

for i in range(2, len(str(num))+2):
    globals()[f'num_{i}'] = str(num)[i-2]

The values will get stored in the variables named like num_2, num_3, num_4, ...

One-line for the same above code

globals().update({f'num_{i}': str(num)[i-2] for i in range(2, len(str(num))+2)})

Tell me if its not working for you...

Ghost Ops
  • 1,710
  • 2
  • 13
  • 23
  • Seems like the code probably doesnt really help... maybe I just didn't said it good enough, so if num had 4 digits (for example 1010) can you add 4 variables, that go from num_2 to num_5 (so its "num_" with a number from 2, 3, 4, 5 (for the digits)), so if num would be 5 digits for example then it would go from num_2 to num_6 ("num_" + 2, 3, 4, 5, 6). –  Oct 19 '21 at 14:07
  • @Chaos i edited my answer, tell me if its okay for you... – Ghost Ops Oct 19 '21 at 14:16
  • @Chaos is it okay now chaos? i saw some notifications tho... – Ghost Ops Oct 19 '21 at 14:25
  • ye worked, tyvm –  Oct 19 '21 at 14:26