I have a list of names, and I would like my program to randomly select one of those names. I tried using the following:
import random
def main():
Arkansas = 1
Manchuria = 2
Bengal = "3"
Baja_California = 4
Tibet = 5
Indonesia = 6
Cascade_Range = 7
Hudson_Bay = 8
High_Plains = 9
map = random.randrange(1, 10)
print(map)
main()
I also tried making each of the numbers as strings, using the eval()
function for randrange()
, but none of this worked.
Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.
Random integer values can be generated with the randint() function. This function takes two arguments: the start and the end of the range for the generated integer values. Random integers are generated within and including the start and end of range values, specifically in the interval [start, end].
Don't assign numbers OR strings. Use a list.
choices = ['Arkansas', 'Manchuria', 'Bengal', 'Baja California'] # etc.
Then take a random.choice
random_choice = random.choice(choices)
Another option is to use a dictionary.
my_dict = {1:"Arkansas", 2:"Manchuria", 3:"Bengal",
4:"Baja California", 5:"Tibet", 6:"Indonesia",
7:"Cascade Range", 8:"Hudson Bay", 9:"High Plain"}
map = random.randrange(1, 10)
print(my_dict[map])
Using a list and random.choice()
is probably the better option (easier to read, less bytes), but if you have to assign numbers, this will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With