Python Forum
Naming a variable with the str value and another variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Naming a variable with the str value and another variable
#1
I want to create a bunch of variables with just a for loop like this -
x = 0
for i in range(1, 11):
    x += 1
    #name a variable "UserLvl_Check" and I want to put x where the underscore is
Reply
#2
you could keep the variables in a dictionary
my_dict = {}
for i in range(1, 11):
    my_dict[f'UserLvl{i}Check'] = i

print(my_dict)
Output:
{'UserLvl1Check': 1, 'UserLvl2Check': 2, 'UserLvl3Check': 3, 'UserLvl4Check': 4, 'UserLvl5Check': 5, 'UserLvl6Check': 6, 'UserLvl7Check': 7, 'UserLvl8Check': 8, 'UserLvl9Check': 9, 'UserLvl10Check': 10}
Reply
#3
Or, since it's just a numeric difference in the game, use a list:

UserLvlCheck = list(range(11))
That gives you a an extra level of zero, but keeps all of the numeric indexes the same.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Variable not defined even though it is CoderMerv 2 36 12 minutes ago
Last Post: CoderMerv
  optimum chess endgame with D=3 pieces doesn't give an exact moves_to_mate variable max22 1 186 Mar-21-2024, 09:31 PM
Last Post: max22
  unbounded variable akbarza 3 426 Feb-07-2024, 03:51 PM
Last Post: deanhystad
  Variable for the value element in the index function?? Learner1 8 541 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable definitions inside loop / could be better? gugarciap 2 373 Jan-09-2024, 11:11 PM
Last Post: deanhystad
  working directory if using windows path-variable chitarup 2 679 Nov-28-2023, 11:36 PM
Last Post: chitarup
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 511 Nov-23-2023, 02:53 PM
Last Post: rob101
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,522 Nov-07-2023, 09:49 AM
Last Post: buran
  Calling functions by making part of their name with variable crouzilles 4 746 Nov-02-2023, 12:25 PM
Last Post: noisefloor
  dynamic variable name declaration in OOP style project problem jacksfrustration 3 716 Oct-22-2023, 10:05 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020