-1

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

muchuu17
  • 5
  • 1
  • 1
    No, just use a list. – user202729 Jan 20 '21 at 12:07
  • 2
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – quamrana Jan 20 '21 at 12:14
  • Does this answer your question? [Creating dynamically named variables from user input](https://stackoverflow.com/questions/11354214/creating-dynamically-named-variables-from-user-input) – Gino Mempin Jan 20 '21 at 13:07

1 Answers1

0

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.

Jack Morgan
  • 317
  • 1
  • 14