user2458988
user2458988

Reputation: 1

How to modify a variable name in Python

Let's say I have a variable named job1, where job1 is equal to "Salesman".

Now let's say I have another variable named job2 which is equal to "Chef".

I add 10 more jobs (job3, job4, etc..) and want to cycle through them randomly based on the number attached to them.

would it be possible for me to search randomly based on a random number generator? Generate a random number 1-10 and tack the number given onto the end of the job variable to find that specific one?

sample would look like this:

choice = random.randint(1, 4)

job1 = "salesman"

job2 = "chef"

job3 = "driver"

job4 = "waiter"

'''here is where I want to take the random number and put it on the end of job to get job1, job2, job3, job4, etc. and print it'''

I'm sure there's an easier way of doing this but is there a possible way for what I'm inquiring?

Thanks for your time

Upvotes: 0

Views: 638

Answers (1)

rmunn
rmunn

Reputation: 36688

You're better off using random.choice() for what you're trying to do:

import random
jobs = ["salesman", "chef", "driver", "waiter"]
print random.choice(jobs)  # Will print one of those four, at random

random.choice() will automatically pick one element from the list you give it, whatever length the list is, so if you add more jobs to the list you won't need to change your code. That's a much better way to do this than trying to change variable names, which Python deliberately makes hard to do.

Upvotes: 2

Related Questions