Value defined in one function not available in another - python

Alright, so this is my first post. I have searched through here trying to find any questions for reference if I missed it I apologize.
So my daughter and I are writing a game together. I have been working on some of the foundation programming while she does the creative stuff.
I have a function where the user picks a "class" that assigns base values for certain aspects and returns them as a variable. Following other posts I first tried using return function but that didn't work so I tried global function. That allows the program to use the variable to simply print it outside the function, but when another function tries to use the variable it comes up as not variable referenced before assignment.
import random
import time
#these were another attempt at finding a way to make the classes
#available to other functions
combat = 0
strength = 0
agility = 0
magic = 0
intelligence = 0
def chose_class():
#I tried return "each characteristic" at the end, but it wouldn't
#even print out the returned value
global strength
global combat
global agility
global magic
global intelligence
health = 10
print("Chose your class:")
print("Warrior: 1")
print("Wizard: 2")
print("Philosopher: 3")
print("Thief: 4")
print("Help: 5")
dog1 = int(input(":"))
if dog1 ==1:
strength = 7
combat = 7
agility = 5
stealth = 3
magic = 1
intelligence = 1
elif dog1 == 2:
strength = 3
combat = 1
agility = 3
stealth = 3
magic = 8
intelligence = 6
elif dog1 == 3:
strength = 3
combat = 1
agility = 3
stealth = 3
magic = 2
intelligence = 8
elif dog1 == 4:
strength = 2
combat = 4
agility = 6
stealth = 8
magic = 1
intelligence = 6
elif dog1 == 5:
print("Warrior Dog:")
print(" Warrior Dogs possess great strength and combat ability")
print(" they have medium agility, but low stealth, magic and")
print(" intelligence.")
print("\n"*2)
print("Wizard Dog:")
print(" Wizard Dogs have low strength, combat, and agility,")
print(" they have medium stealth and high magic capabilities.")
print("\n"*2)
print("Philosopher Dog:")
print(" Philosopher Dogs are highly intelligent, while they")
print(" have low strength, they have medium combat ability.")
print(" Their agility, stealth, and magic start low but can")
print(" rapidly improve by finding hidden objects on quests.")
print("\n"*2)
print("Thief Dogs")
print(" Thief Dogs have high agility and stealth, as well as")
print(" average intelligence and combat. They have low combat,")
print(" magic, and strength.")
else:
chose_class()
def room17():
print("**Description**")
print("Do you want to fight the cat guard or sneak past it?")
print("Fight: 1")
print("Sneak Past: 2")
choice17 = str(input(":"))
if "1" in choice17:
fight17 = random.randint(0,5)
combat17 = combat * fight17
if combat17 <= 20:
print("You were successful")
combat = combat + 1
else:
print("You lost the fight and had to retreat")
health = health - 1
room1()
else:
sneak17 = random.randint(0,5)
stealth17 = sneak17 * stealth
if stealth17 <= 20:
print("You snuck past the guard")
stealth = stealth + 1
else:
print("The guard caught you, he attacks and you have to retreat")
health = health - 2
stealth = stealth - 1
room1()
chose_class()
# this was just to see if the value was returned
print("Combat:", combat)
# I'm jumping to the first combat event to try to test the program
room17()
Okay, so that should be enough of what I have to demonstrate the issue. I'm completely self taught so I'm sure there are tons of stylistic issues, which I'm perfectly happy to get help with. But if anyone can help with why the variable "combat" is returned from "def chose_class()" to the print command but then not assigned in the "def room17()" I would greatly appreciate it.

Related

Telium Adventure Game: how to fix the problem where it prints out any npc's in the room but instead it just prints there is 'None' here

There is module files as well but they work perfectly, the main problem is when you enter a module and it just printing out There is 'none' in here for every module. Additionally, if I wanted to change the fuel gain from 50 to randomly chose between 20,30,40 or 50.
The rest of the code works well but when the npc in a room is outputted it should say there is a 'workers' in here instead of just none for each module.
#Telium - Game
import random
#Global Variables
num_modules = 17 #Number of modules in the space station
module = 1 #Module of space station we are in
last_module = 0 #Last module we were in
possible_moves = [] #List of possible moves we can make
alive = True #Whether player is alive or not
won = False #Whether player has won
power = 100 #Amount of power the space station has
fuel = 500 #Amount of fuel the player has in flamethrower
locked = 0 #Module that has been locked by the player
queen = 0 #Location of queen alien
vent_shafts = [] #Location of ventilation shaft entrances
info_panels = [] #Location of info panels
workers = [] #Location of worker aliens
#procedure declarations
#This loads the global module
def load_module():
global module, possible_moves
possible_moves = get_modules_from(module)
output_module()
def get_modules_from(module):
moves = []
text_file = open("Charles_Darwin\module" + str(module) + ".txt", "r")
for counter in range(0,4):
move_read = text_file.readline()
move_read = int(move_read.strip())
if move_read != 0:
moves.append(move_read)
text_file.close()
return moves
def output_module():
global module
print()
print("--------------------------------------------------------------
-----------------------")
print()
print("You are in module",module)
print()
npc = spawn_npcs()
print("There is a ", npc ,"here")
def output_moves():
global possible_moves
print()
print("From here you can move to modules: | ",end='')
for move in possible_moves:
print(move,'| ',end='')
print()
def get_action():
global module, last_module, possible_moves, power
valid_action = False
while valid_action == False:
print("What do you want to do next ? (MOVE, SCANNER)")
action = input(">")
if action == "MOVE" or action.lower() == 'move' or action.lower()
== 'm' or action.higher() == 'M':
move = int(input("Enter the module to move to: "))
if move in possible_moves:
valid_action = True
last_module = module
module = move
#power is decreased by 1 for every move
power =- 1
else:
print("The module must be connected to the current
module.")
def spawn_npcs():
global num_modules, queen, vent_shaft, greedy_info_panels, workers
module_set = []
for counter in range(2,num_modules):
module_set.append(counter)
random.shuffle(module_set)
i = 0
queen = module_set[i]
for counter in range(0,3):
i=i+1
vent_shafts.append(module_set[i])
for counter in range(0,2):
i=i+1
info_panels.append(module_set[i])
for counter in range(0,3):
i=i+1
workers.append(module_set[i])
def check_vent_shafts():
global num_modules, module, vent_shafts, fuel
if module in vent_shafts:
print("There is a bank of fuel cells here.")
print("You load one into your flamethrower.")
fuel_gained = 50
print("Fuel was",fuel,"now reading:",fuel+fuel_gained)
fuel = fuel + fuel_gained
print("The doors suddenly lock shut.")
print("What is happening to the station?")
print("Our only escape is to climb into the ventilation shaft.")
print("We have no idea where we are going.")
print("We follow the passages and find ourselves sliding down.")
last_module = module
module = random.randint(1,num_modules)
load_module()
#Main Program starts here
#Menu options
print("ENTER 1 for instructions")
print("ENTER 2 to play")
print("ENTER 3 to quit")
menu = int(input("Please enter a number corresponding to what you want to
do: "))
if menu == 1:
instructions = input("Do you want to read the instructions(Y/N): ")
if instructions == "Y":
print("You, the player are trying to navigate around a space
station named the 'Charles Darwin' which contains many modules")
print("The aim of the game is to find a and trap the queen alien
called 'Telium' who is located somewhere randomly in the station, the
queen will try to escape to connectinhg modules so beware")
print("To win - you have to lock the queen in one of the modules
so she is trapped, you can kill her with a flamethrower, there is also
objects to help on the way so keep a look out")
spawn_npcs()
#Outputs where the queen, shafts, panels and workers are located
print("Queen alien is located in module:",queen)
print("Ventilation shafts are located in modules:",vent_shafts)
print("Information panels are located in modules:",info_panels)
print("Worker aliens are located in modules:",workers)
#when the players is alive, the module will load
while alive and not won:
load_module()
if won == False and alive == True:
output_moves()
get_action()
#if power is 0 then the user will die and the game will end
if power == 0:
print("You ran out of life support, you died")
alive == False
#win message once you have trapped the queen or when you run out of life
support
if won == True:
print("The queen is trapped and you burn it to death with your
flamethrower.")
print("Game over. You win!")
if alive == False:
print("The station has run out of power. Unable to sustain life
support, you die.")
check_vent_shafts()
First the easy part. You can randomly get 20, 30, 40 or 50 by using random.randint like this:
random.randint(2, 5) * 10
The harder part:
As you discussed with #Random Davis in the comments, you want to assign the npcs to random modules and then print which one you encounter.
To append three random (possibly repeating) modules, use
for _ in range(0,3):
vent_shafts.append(random.choice(module_set))
Using global variables (and the global keyword) is generally considered bad practice as it can cause sideeffects due to other parts of the program modifying a variable you wouldn't expect it to / forgot about. Try to use them as function parameters where needed and return the results
queen, vent_shafts, info_panels, workers = spawn_npcs(5)
def spawn_npcs(num_modules):
module_set = []
for i in range(2, num_modules):
module_set.append(i)
for _ in range(0,3):
vent_shafts.append(random.choice(module_set))
for _ in range(0,2):
info_panels.append(random.choice(module_set))
for _ in range(0,3):
workers.append(random.choice(module_set))
queen_module = module_set[0]
return queen_module, vent_shafts, info_panels, workers

The script is not assigning points to the attribute

I'm trying to create a text-based adventure game and all is going well until I encountered a problem with assigning points to attributes. I've been using this website to help with the process but realized that it might be in Python 2. Here's all that I've done so far code:
#Date started: 3/13/2018
#Description: text-based adventure game
import random
import time
def display_intro():
print('It is the end of a 100-year war between good and evil that had \n' +
'killed more than 80% of the total human population. \n')
time.sleep(3)
print('The man who will soon be your father was a brave adventurer who \n' +
'fought for the good and was made famous for his heroism. \n')
time.sleep(3)
print('One day that brave adventurer meet a beautiful woman who he later \n' +
'wed and had you. \n')
time.sleep(3)
def get_gender(gen=None):
while gen == None: # input validation
gen = input('\nYour mother had a [Boy or Girl]: ')
return gen
def get_name(name = None):
while name == None:
name = input("\nAnd they named you: ")
return name
def main():
display_intro()
gender_num = get_gender()
charater_name = get_name()
print("You entered {} {}.".format(gender_num, charater_name))
if __name__ == "__main__":
main()
character_name = get_name()
# Assignning points Main
my_character = {'name': character_name, 'strength': 0, 'wisdom': 0, 'dexterity': 0, 'points': 20}
#This is a sequence establises base stats.
def start_stat():
print("\nThis is the most important part of the intro\n")
time.sleep(3)
print("This decides your future stats and potentially future gameplay.")
time.sleep(4)
print("\nYou have 20 points to put in any of the following category:
Strength, Health, Wisdom, or Dexterity.\n")
def add_charater_points(): # This adds player points in the beginnning
attribute = input("\nWhich attribute do you want to assign it to? ")
if attribute in my_character.keys():
amount = int(input("By how much?"))
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
else:
print("That attribute doesn't exist!!!")
def print_character():
for attribute in my_character.keys():
print("{} : {}".format(attribute, my_character[attribute]))
playContinue = "no"
while playContinue == "no":
Continue = input("Are you sure you want to continue?\n")
if Continue == "yes" or "Yes" or "y":
playContinue = "yes"
start_stat()
add_charater_points()
else:
display_intro()
gender_num = get_gender()
charater_name = get_name()
running = True
while running:
print("\nYou have {} points left\n".format(my_character['points']))
print("1. Add points\n2. Remove points. \n3. See current attributes. \n4. Exit\n")
choice = input("Choice: ")
if choice == "1":
add_charater_points()
elif choice == "2":
pass
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
And here's what happens when I run it:
It is the end of a 100-year war between good and evil that had
killed more than 80% of the total human population.
The man who will soon be your father was a brave adventurer who fought for
the good and was made famous for his heroism.
One day that brave adventurer meet a beautiful woman who he later wed and
had you.
Your mother had a [Boy or Girl]: boy
And they named you: Name
You entered boy Name.
And they named you: Name
Are you sure you want to continue?
yes
This is the most important part of the intro
This decides your future stats and potentially future gameplay.
You have 20 points to put in any of the following category: Strength,
Health, Wisdom, or Dexterity.
Which attribute do you want to assign it to? strength
By how much? 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice: 3
name : Name
strength : 0
wisdom : 0
dexterity : 0
points : 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice:
Oh, and prompt for the name of the play goes again twice for some reason. Also, what does the my_character.keys() under def add_charater_points() mean? Since I just started to learn to code python, if there are any other tips you guys can give me it would be greatly appreciated.
The last two lines of this snippet
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
add the character points to the attribute, and immediately subtract them again. I think you might mean
my_character['points'] -= amount
Your repeated prompt is probably because you have a whole lot of code that logically seems to belong in function main() but is coded to run after main() finishes.

montyhall simulator gone wrong(python)

#
# Monty Hall Problem Simulation
# Author: Ryan Sturmer
#
import random
def play_round(doors, switch):
# Choose the location of the car
car = random.randint(1, doors)
# Contestant chooses a door
initial_choice = random.randint(1, doors)
# Monty opens ALL the other doors except one
if initial_choice != car:
monty_leaves = car # If the car wasn't chosen, Monty is forced to reveal its location
else:
while True:
monty_leaves = random.randint(1, doors)
if monty_leaves != initial_choice:
break
# monty_leaves is now the door that Monty DIDN'T open
if switch:
final_choice = monty_leaves
else:
final_choice = initial_choice
victory = (final_choice == car)
return victory, initial_choice, final_choice, car
def simulation(iterations, doors=3):
games_won_switch = 0
games_won_noswitch = 0
for i in range(iterations):
won_game, intial_choice, final_choice, car = play_round(doors, False)
if(won_game):
games_won_noswitch += 1
won_game, intial_choice, final_choice, car = play_round(doors, True)
if(won_game):
games_won_switch += 1
print ""
print " Monty Hall Simulation"
print "---------------------------------------------"
print " Iterations: %d" % iterations
print " Games won when switching doors: %d (%g%%)" % (games_won_switch, 100*float(games_won_switch)/float(iterations))
print "Games won when NOT switching doors: %d (%g%%)" % (games_won_noswitch, 100*float(games_won_noswitch)/float(iterations))
===========================================================================
I found this code from github.
When I run this code, the sum of games_won_switch and games_won_noswitch is not equals to iteration.
(For example, if I set iteration 1,000 -> it appears 996, 1,001, 1,008 not exact 1,000)
How can i fix problem this up?
There is no mistake in the code; it runs the simulations twice:
Once when the player chooses to switch doors every time, and another time when the player chooses to never switch doors. It then prints the results of both simulations.
The results are from independent simulations.
for i in range(iterations):
# Sim with player choose to open the door each time
won_game, intial_choice, final_choice, car = play_round(doors, False)
if(won_game):
games_won_noswitch += 1
# Sim with player choose NEVER to open the door
won_game, intial_choice, final_choice, car = play_round(doors, True)
if(won_game):
games_won_switch += 1
In consequence, because sim(open=True) is not (1 - sim(open=False)), but result from two sets of simulations, the addition of results may not add up precisely to the number of trials.

Python problems with "local variable referenced before assignment"

I have had problems with the shell saying local variable referenced before assignment and don't feel any previous answers have helped. Can I have some specific advice to this code:
import random
marginalCheck = random.randint(0,1)
print("This is the political campaign simulator")
global popularity
popularity = 50
def unpopularT():
if popularity <= 30 and popularity < 0:
print("You are decreasing in popularity.")
popularityRecover = input("Do you wish to carry on or resign. If this carries on, you are likely to lose to a landslide by your Labour opposition")
if popularityRecover == "resign":
print("You have become an infamous, unpopular politician. You are remembered as a horrible, unkind person")
else:
print("You are hanging by a thread")
elif popularity > 70:
print("You are seriously doing well among your supporters and gaining new ones every day")
else:
print("You are doing fine so far in the campaign")
def campaignT():
leadershipT = input("You are chosen as a candidate by your colleagues in the Tory leadership contest. Do you wish to take an A - Far Right, B - Right, C - Centre, D - Left or E - Far Left stance on the political spectrum")
if leadershipT == "A" or leadershipT == "B":
print("You have been elected as leader of the Tories and leader of the opposition. Now the election campaign starts")
ClassicToryAusterity = input("What do you wish to do about the poor funding in the NHS by the Labour government. A - Do you wish to keep the current program, B - Do you wish to increase funding dramatically and increase taxes, C - Do you propose minor increases with small raises on tax, D - Do you support austere implementations on the Health Service")
if ClassicToryAusterity == "A":
popularity += -5
elif ClassicToryAusterity == "B":
popularity += 5
elif ClassicToryAusterity == "C":
popularity += 2
elif ClassicToryAusterity == "D":
popularity += -10
BedroomTax = input("What do you propose to do about the bedroom tax. A - increase it, B - freeze it, C - Decrease it, D - Scrap it")
if BedroomTax == "A":
popularity += -10
elif BedroomTax == "B":
popularity += -5
elif BedroomTax == "C":
popularity += -1
else:
popularity += 10
unpopularT()
else:
print("The Tory whip dislikes your stance and you have not been voted as leader")
chosenParty = input("Choose a party. A - LibDem, B - Labour, C- Tory")
if chosenParty == "C":
print("You have been elected as a councillor by your fellow peers.")
marginality = input("They want you to stand as a MP in a seat. Do you want to stand in a safe or marginal seat")
if marginality == "marginal":
if marginalCheck == 0:
print("You have failed to be elected to parliament")
else:
print("You are duly elected the MP for your constituency!")
campaignT()
else:
campaignT()
What I don't understand is that I have referenced popularity as a global variable, but according to the shell, it is local.
If you want to use access global variables inside functions you don't need to declare anything, but if you need to re-assign the variable by any means, you need to declare it inside the function. For example:
test = 'hello'
def print_test():
print test
def set_test():
global test
test = 'new value'
in your case, you didn't declare the global variable popularity inside your function and you were trying to re-assign it.
So in your case:
def unpopularT():
global popularity
# your code
def campaignT():
global popularity
# your code

How to access and edit variables inside functions in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Im new(-ish) to python and I made a game today which after I finished I realised I'd made a big mistake :
inside the functions I had to access and edit variables which where also accessed and changed in other functions and maybe in the future outside the functions. And I don't know how to do that.
I've researched for a long time and found very few things that might solve the problem, I've tried a few, but they haven't worked and I don't understand how to use others.
Could you please try to help me with the problem and if you spot others please tell me, as Im not too good at debugging :(
Here is the code below, its quite big (I've put the variables I need to access and change in bold):
from random import randint
print ("Ghost Game v2.0")
print ("select difficulty")
score = 0
alive = True
difficulty = 0
doors = 0
ghost_door = 0
action = 0
ghost_power = 0
#define the function 'ask_difficulty'
def ask_difficulty() :
difficulty = input ("Hard, Normal, Easy")
set_difficulty()
# define the function 'set_difficulty' which sets the difficulty.
def set_difficulty() :
if difficulty == 'Hard' or 'Normal' or 'Easy' :
if difficulty == 'Hard' :
doors = 2
elif difficulty == 'Normal' :
doors = 3
elif difficulty == 'Easy' :
doors = 5
else:
print ("Invalid input, please type Hard, Normal, or Easy")
ask_difficulty()
# define the function 'ghost_door_choose' which sets the ghost door and the chosen door
def ghost_door_choose(x):
ghost_door = randint (1, x)
print (doors + " doors ahead...")
print ("A ghost behind one.")
print ("Which do you open?")
if doors == 2 :
door = int("Door number 1, or door number 2...")
if 1 or 2 in door :
ghost_or_no()
else :
print ("Invalid input")
ghost_door_choose(difficulty)
elif doors == 3 :
door = int("Door number 1, door number 2, or door number 3")
if 1 or 2 or 3 in door :
ghost_or_no()
else:
print ("Invalid input")
ghost_door_choose(difficulty)
elif doors == 5 :
print("Door number 1, door number 2, door number 3, door number 4, or door number 5.")
if 1 or 2 or 3 or 4 or 5 in door :
ghost_or_no()
else:
print ("Invalid input")
ghost_door_choose(difficulty)
# define the function 'ghost_or_no'
def ghost_or_no() :
if door == ghost_door:
print ("GHOST!!")
print ("Initiating battle...")
battle()
else:
print ("No ghost, you\'ve been lucky, but will luck remain with you...")
score = score + 1
ghost_door_choose(difficulty)
# define the function 'battle' which is the battle program
def battle() :
ghost_power = randint (1, 4) # 1 = Speed, 2 = Strength, 3 = The ghost is not friendly, 4 = The ghost is friendly
print ("You have 3 options")
print ("You can flee, but beware, the ghost may be fast (flee),")
print ("You can battle it, but beware, the ghost might be strong (fight),")
print ("Or you can aproach the ghost and be friendly, but beware, the ghost may not be friendly (aproach)...")
action = input ("What do you choose?")
if flee in action :
action = 1
elif fight in action :
action = 2
elif aproach in action :
action = 3
else :
print ("Invalid input")
battle()
if ghost_power == action :
if action == 1:
print ("Oh no, the ghost\'s power was speed!")
print ("DEFEAT")
print ("You\'r score is " + score)
alive = False
elif action == 2:
print ("Oh no, the ghost\'s power was strength!")
print ("DEFEAT")
print ("You\'r score is " + score)
alive = False
elif action == 3:
print ("Oh no, the ghost wasn\'t friendly ")
alive = False
elif ghost_power == 4 and action == 3 :
print ("Congratulations, The ghost was friendly!")
score = score + 1
ghost_door_choose(difficulty)
elif ghost_power != action and ghost_power != 4 :
if action == 1:
print ("Congratulations, the ghost wasn\'t fast!")
score = score + 1
ghost_door_choose(difficulty)
elif action == 2:
print ("Congratulations, you defeated the ghost!")
score = score +1
ghost_door_choose(difficulty)
elif ghost_power != action and ghost_power == 4 :
if action == 1:
print ("You ran away from a friendly ghost!")
print ("Because you ran away for no reason, your score is now 0")
score = 0
ghost_door_choose(difficulty)
elif action == 1:
print ("You killed a friendly ghost!")
print ("Your score is now 0 because you killed the friendly ghost")
score = 0
ghost_door_choose(difficulty)
#actual game loop
ask_difficulty()
while alive :
ghost_door_choose(doors)
Consider:
x=0
z=22
def func(x,y):
y=22
z+=1
print x,y,z
func('x','y')
When you call func you will get UnboundLocalError: local variable 'z' referenced before assignment
To fix the error in our function, do:
x=0
z=22
def func(x,y):
global z
y=22
z+=1
print x,y,z
The global keyword allows a local reference to a global defined variable to be changed.
Notice too that the local version of x is printed, not the global version. This is what you would expect. The ambiguity is if there is no local version of a value. Python treats globally defined values as read only unless you use the global keyword.
As stated in comments, a class to hold these variables would be better.
Those variables at the top of your script are global and to set them in functions, you have to declare them global in the function. As a smaller example,
score = 0
alive = True
def add_score(value):
"""Add value to score"""
global score
score += value
def kill_kill_kill():
global alive
alive = False
The next step is to create classes, which can get complicated. For instance, if you want to track score by user but a user can have multiple characters which each have their own aliveness, you would start to build classes to represent those things.
The global keyword may be what you are looking for.
For example in the following code.
some_variable = 10
def some_function():
global some_variable
some_variable = 20
This would result in some_variable (in the global scope) referring to the value of 20. Where as it would remain at 10 (in the global scope) without the use of the global keyword.
More on global and local variables here.
A function has its own variable scope - this is true for many languages. This means that once the function finishes executing, the variables cease to exist (and Python's garbage collection will clean them up).
The old-school (and generally frowned upon, not necessarily fairly) way of doing this is to use Global Variables. These are variables you declared outside the scope of the function, usually at the beginning of your source, and can be used throughout your program's various functions and classes.
There are good reasons people don't use global variables much, from performance issues through to getting them confused with locally scoped variables, but they are a quick and easy way to keep information and access it throughout your program.
To use a global, you need to declare within the function that you are using that variable, like this:
MyGlobal="This is a global variable"
def MyFunction():
global MyGlobal
MyGlobal += " and my function has changed it"
if __name__=="__main__":
print MyGlobal
MyFunction()
print MyGlobal
Having said this, the usual way to pass information to and from functions is to use arguments and return values - this is a better design methodology, and the one usually taught. This is more a design method than a change to your code; you write your program with keeping global variables down to an absolute minimum.
To take the above example, this would change our code to the following:
def MyFunction(MyArg):
MyArg+=" and my function has given me a new version of it"
return MyArg
if __name__=="__main__":
MyVariable="This is a variable"
print MyVariable
MyVariable = MyFunction(MyVariable)
print MyVariable
Note that this is much more flexible - I can use it as I have above, to change the value of MyVariable, but I could also use the same function to return the new value to a different variable, keeping the original intact.
I hope this helps, sorry if I was a tad verbose.

Categories

Resources