pythonvariablesinputpointsvoting

How to make a variable name dependant on input in python?


I need to create multiple variables based on int input so that if input is 5 then variables are created like: worker1, worker2, worker3, etc.

Is there any way in which I could generate variables like these and then add points to them dependant on the number chosen by the user? Example:

How many workers? 10 -Choose worker 4 -added 1 point to worker4


Solution

  • Instead of using multiple variables, you can use a dictionary. Using multiple variables is less Pythonic than using a dictionary and can prove cumbersome with large data. In your example, you could use a dictionary to store each worker and their number of points. Documentation for dictionaries can be found here

    For example:

    #recieve a valid input for the number of workers
    while True:
        num = input("How many workers would you like to create?\n") # accepts an int
        try:
            num = int(num)
        except ValueError:
            print("Must input an integer")
        else:
            break
    
    #create a dictionary with the workers and their scores (0 by default)
    workers = {'worker'+str(i+1) : 0 for i in range(num)}
    
    # get the user to choose a worker, and add 1 to their score
    while True:
        worker = input("Which worker would you like to add a point to?\n") #accepts worker e.g worker1 or worker5
        if worker in workers:
            workers[worker] += 1
            print(f"Added one point to {worker}")
            break
        else:
            print("That is not a worker")
    
    print(workers)
    

    This code gets a user input to create a certain number of workers. It then gets user input to add a point to one of the workers. You can change this to add multiple points to different workers, but this is just a basic example, and it depends on what you want to do with it.