0

So I am trying to create a function that will let me simply call the function, and I give it 10 values, and a variable, and it will change that variable into one of the values provided, randomly.

import random

place = "NA"

def randomize (value1, value2, value3, value4, value5, value6, value7, value8, value9, value10, variable):
global variable
variable  = random.choice([value1, value2, value3, value4, value5, value6, value7, value8, value9, value10])

randomize ("Dungeon", "Plains", "Castle", "Prison", "Tavern", "Armory", "Docks", "Warehouse", "ThroneRoom", "Bedroom", place)

print place

This however tells me the following:

SyntaxError: name 'variable' is local and global
Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65

2 Answers2

0

In Python, you don't usually modify input parameters. I know this is standard in C, but it's easier to return the value and assign you variable to the output of the function instead:

import random

def randomize(*values):
    return random.choice(values)

place = "NA"
print place

place = randomize("Dungeon", "Plains", "Castle", "Prison", "Tavern", "Armory", "Docks", "Warehouse", "ThroneRoom", "Bedroom")
print place
Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65
0

For 1, 2, 3, ... n values you should use a list. You also need to write less code, so it scales better. And you should try to avoid global variables... Reasons why you can find in the global internet. For this example you even could save a method definition.

import random
places = ["Dungeon", "Plains", "Castle", "Prison", "Tavern", "Armory", "Docks",
          "Warehouse", "ThroneRoom", "Bedroom"]  # list with n elements...
place = random.choice(places)
print place
Community
  • 1
  • 1
wenzul
  • 3,948
  • 2
  • 21
  • 33