Python Forum
A question about global variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A question about global variables
#1
A quick question on global variables

I understand that global variables cannot not be accessed outside of a function but is there anyway I could access a global variable outside of a function?
Thanks-Goldberg291
Reply
#2
On the contrary, global variables is all you have in code outside of functions...
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#3
Ok, then could you please try to explain to me why in line 137 maximum_amount prints the wrong amount, Thanks
import random
import sys
import time
def final_amount_2():
    global maximum_amount
    maximum_amount_2= maximum_amount *.2
    maximum_amount = maximum_amount - maximum_amount_2

def final_amount_1():
    global maximum_amount
    maximum_amount_2= maximum_amount * .1
    maximum_amount = maximum_amount - maximum_amount_2
members={'harry':'10%','chris':'20%','ben':'20%','septiums':'10%','amelia':'20%','jenna':'10%','beetle':'20%','marsha':'10%'}

name = input('Enter your name: ')
print("Hello",name)
answer_1=input('Would you like to play choose your own adventure?: ')
if answer_1=='yes':
    print('Okay lets get started')
elif answer_1 == 'no':
    print("Ugh")
    sys.exit()
answer_2 = input('\nYour name is {} and you live on planet Xeno.  You are hoping to save up for the new Toto2000, the best and newest spaceship there is, but you know there is only one way to get that spaceship because it is too expensive.\n  \nYou either have to rob and steal from the bank of Xeno or work for the rest of your life and try to afford the spaceship at the end of your life.\n  \nType 1 to start planning to rob the bank or enter 2 to work for the rest of your life.\n'.format(name))
if answer_2=='1':
    print('Now you need to start planning for your hiest at Xeno bank.')
elif answer_2=='2':
    print('Thats lame', name)
    sys.exit()
elif answer_1=='no':
    print('\nOkay thank you for your time.\n')
print( '\nFirst you must get a crew for your hiest, you need five people to help you in your hiest.\n \nOne person to drive your getaway hover vechile, one person that can pick locks very well,\n \nOne person that has experience with the high powered drill, and you and one other person will be making sure that no one walks into or by the bank by pretending to be police officers.\n')
time.sleep(13)
print('\nThere are two options for every job and you must decide who you want, but remember the better person that you choose the less money you will get.\nThe Toto200 costs $40,000.\nThe bank holds $250,000.\nIf a task goes wrong you and your gang wont be able to steal as much money. ')
# The next line is going to be your descion on what driver you want
time.sleep(13)
answer_3=input('Your first decsion is to decide who you want to be driving your getaway hover vehicle.  You can either choose Chris which is the better person at driving or you can choose Harry which is worse.  If you choose Chris is pay cut will be 20% but if you choose Harry his pay cut will be 10%.  Type chris or harry')
if answer_3 in ['harry', 'chris']:
    print("You chose {}, your next descion is going to be who you will choose as your locksmith".format(answer_3))
    time.sleep(5)
# The next line will be who you choose for the locksmith.
answer_4=input('You can either choose ben who is better but has a 20% cut or you can choose septimus who is worse but has a 10% cut enter ben or septimus')
if answer_4 in ['ben', 'septimus']:
    print('You chose {}, next you will be choosing who will be operating the drill.'.format(answer_4))
    time.sleep(5)
# Next you will be choosing who operates the drill
answer_5=input("You can either choose Amelia who is better but 20% cut or Jenna who has a 10% cut.  Type jenna or amelia.")
if answer_5 in ['amelia','jenna']:
    print("You chose {}, next you will need to choose who you want to be a police officer with you.".format(answer_5))
    time.sleep(5)
# Next you will be choosing who is the other police officer
answer_6=input("You can either choose beetle who is better but has a 20% cut or you can choose Marsha who has a 10% cut.  Type beetle or marsha.")
if answer_6 in ['beetle','marsha']:
  print("You chose {}, you are ready to do the hiest.".format(answer_6))
  time.sleep(5)
# Next will be the results for all 20%
# Keeping civilians away
if answer_6=='beetle':
    if random.randrange(1,101) < 80:
        print('Beetle and you have successfully kept all civilians away from the bank by pretending to be police!')
        final_amount_2()
    else:
        print('Oh no!  Beetle has failed to keep Civilians away and has called the police, which gives you less time to collect money!  You lose $15,000 of your total amount')
        maximum_amount-=15000
        final_amount_2()

time.sleep(3)
# Locksmith
if answer_4=='ben':
    if random.randrange(1,101)<80:
        print("Ben has succeeded in picking the lock into the bank")
        final_amount_2()

    else:
        print("Oh no! Ben has failed to pick the lock, it takes him 3 tries to pick the lock, which gives you less time to gather money!  You lose $15,000 of your total amount!")
        maximum_amount-=15000
        final_amount_2()
time.sleep(3)
# Drill
if answer_5=='amelia':
    if random.randrange(1,101)<80:
        print('Amelia has succeeded in drilling the whole into the vault.')
        final_amount_2()
    else:
        print('Oh no!  Amelia has failed drilling into the vault, it takes her 3 tries to get into the vault, which gives you less time to collect money!  \nYou lose $15,000 of your total amount!\n')
        maximum_amount-=15000
        final_amount_2()
time.sleep(3)
    # Driver
if answer_3=='chris':
    if random.randrange(1,101) < 80:
        print('Chris succeeded in driving you away')
        final_amount_2()
    else: print('Chris has failed to drive your team away, your gang must walk and drop some of your load off!  You lose $15,000 of your total amount!')
    maximum_amount-=15,000
    final_amount_2()
time.sleep(3)

# Next will be the results for all 10%
if answer_6=="marsha":
    if random.randrange(1,101)>40:
        print('Marsha has failed to keep away civilians, the police have been called, which gives you and your gang less time to collect money.  You lose $30,000 of your total amount!')
        maximum_amount -= 30000
        final_amount_1()
    else:
        print('Marsha has succedeed in keeping away civilians')
        final_amount_1()
time.sleep(3)
if answer_4=='septimus':
    if random.randrange(1,101)<40:
        print('Oh No! Septimus has failed to pick the lock, it takes him an extra 3 times, which gives you and your gang less time to collect money!  You lose $30,000 of your total amount!')
        maximum_amount -= 30000
        final_amount_1()
    else:
        print('Septimus has succeeded in picking the lock into the bank!')
        final_amount_1()
time.sleep(3)
if answer_5=='jenna':
    if random.randrange(1,101)<40:
        print('Oh No! Jenna has failed to drill into the vault, it takes her 3 tries to drill into the vault, which gives you and your gang less time to collect money!  You lose $30,000 of your total amount!')
        maximum_amount -= 30000
        final_amount_1()
    else:
        print('Jenna has succeeded in drilling into the vault!')
        final_amount_1()
time.sleep(3)

if answer_3=='harry':
    if random.randrange(1,101)<40:
        print('Oh No! Harry has failed to drive you and your gang away, you and your gang must drop some of your load and walk!  You lose $30,000 of your total amount!')
        maximum_amount -= 30000
        final_amount_1()
    else:
        print('Harry has succeeded in getting the gang away!')
    final_amount_1()
time.sleep(3)
if maximum_amount>=40000:
    print("You have finished your hiest and had enough money to buy the Toto2000 with",maximum_amount, "left")
else:
    print("You have completed the hiest but you dont have enough money to buy the Toto2000")
Reply
#4
Because you never define the initial value of maximum_amount. You have to assign a value to a variable before you can use that variable on the right side of an assignment, as in final_amount_2. If you had given us the full traceback that Python printed when you tried running the program, it would have been much easier for me to figure that out. So please include that in the future.

Using global is generally a bad idea. It leads to errors exactly like this one. It is much better to pass a value into the function with a parameter and get one out with a return statement. For example:

def final_amount_2(maximum_amount):
    return maximum_amount * 0.8
maximum_amount = 200000
maximum_amount = final_amount_2(maximum_amount)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand global variables 357mag 5 1,065 May-12-2023, 04:16 PM
Last Post: deanhystad
  Global variables or local accessible caslor 4 985 Jan-27-2023, 05:32 PM
Last Post: caslor
  global variables HeinKurz 3 1,102 Jan-17-2023, 06:58 PM
Last Post: HeinKurz
  Clarity on global variables JonWayn 2 905 Nov-26-2022, 12:10 PM
Last Post: JonWayn
  Global variables not working hobbyist 9 4,619 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 2,597 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Global - local variables Motorhomer14 11 4,129 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  Question regarding local and global variables donmerch 12 4,980 Apr-12-2020, 03:58 PM
Last Post: TomToad
  local/global variables in functions abccba 6 3,360 Apr-08-2020, 06:01 PM
Last Post: jefsummers
  Question about naming variables in class methods sShadowSerpent 1 1,961 Mar-25-2020, 04:51 PM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020