Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a variable selected by a random number

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.

like image 978
Ovi Avatar asked Jun 04 '15 18:06

Ovi


People also ask

How do you select a random item in a list Python?

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.

How do you generate a random number in Python?

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].


2 Answers

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)
like image 111
Two-Bit Alchemist Avatar answered Sep 19 '22 16:09

Two-Bit Alchemist


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.

like image 23
michaelpri Avatar answered Sep 21 '22 16:09

michaelpri