0

was wondering if I someone could lend a hand with the issue I am having with my python 3.4 code. I have found it hard to word my problem and searching the web for an answer has been difficult, so I thought it would be easier if I were to show the code and the issue to be resolved.

cola_cost = 2
surcharge = 0

def calc_takeaway(cost):
    global surcharge
    cost = cost * 1.05
    surcharge = surcharge + (cost * 0.05)

cola_place = input("Do you want your cola to go? ")
if cola_place == "yes":
    calc_takeaway(cola_cost)

print("$"cola_cost) ## cola cost should be $2.10 but instead prints out $2
print("$"surcharge)

Basically, my cola_cost will not change its global value after being passed into the calc_takeaway function. Sorry if this is too basic I would kist like to get this issue solved. Thank you.

EDIT: I'd also like to mention that I would like to use the function on different cost variables (i.e fanta_cost, water_cost...) as well.

Valentin Podkamennyi
  • 7,161
  • 4
  • 29
  • 44
cwleb
  • 3
  • 1
  • You are not changing the global variable `cola_cost`. You are changing the function parameter `cost`, which acts as a local variable in the function. – DYZ Sep 08 '18 at 04:09

2 Answers2

0

Consider avoiding global in the first place if possible atleast when alternate methods are possible, because they are a bad usage. Instead of global, use simple parameter passing and function return concepts to handle the issue.

cola_cost = 2
surcharge = 0

def calc_takeaway(cost, surcharge):
    cost = cost * 1.05
    surcharge = surcharge + (cost * 0.05)
    return cost, surcharge

cola_place = input("Do you want your cola to go? ")
if cola_place == "yes":
    cola_cost, surcharge = calc_takeaway(cola_cost, surcharge)

print("$", cola_cost) # $ 2.10 
print("$", surcharge)
Austin
  • 25,759
  • 4
  • 25
  • 48
0

Your global variable is sent by value, and so you're not really changing it, but rather a copy of it. Here is a simpler example based on your code:

cola_cost = 2

def try_to_change_global_variable(cost):
    cost = 174

try_to_change_global_variable(cola_cost)

print(cola_cost)

And when you run it you'll get:

$ python cola.py
2
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87