Skip to content
Advertisement

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

Advertisement

Answer

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement