Friday, July 19, 2013

Global

     So, global variables are variables that can be used outside of a function. But what happens when we use them inside a function? Well, let's create a new program, and write this:

def groceries(oranges):
    orangePrice = 1.53
    print("Orange price inside function: ", orangePrice)
    orangeTotal=orangePrice * oranges
    return orangeTotal

print("Enter a price for the oranges")
orangePrice=float(input())

totalPrice = groceries(3)

print("Orange price outside function: ", orangePrice)

print("Orange total: ", totalPrice)

     Now, let's save the program and run it. Let's say, each orange costs $3, so type "3" when you run the program. So, here's what should happen.

Enter a price for the oranges
3
Orange price inside function:  1.53
Orange price outside function:  3.0
Orange total:  4.59

     Hold on a second, $3 times $3 doesn't equal $4.59! $1.59 times 3 equals $4.59! What about our oranges that cost $3 each? Well, this program here has a bug.
     No, not a real bug. There's a problem that doesn't make it run right. How did we get this bug, though? Well, orange price is $1.59 when it's being used inside the function, and is the user's input outside of the function. The user's input doesn't even exist during the function! It's a little confusing, but all we have to do to fix this is with the global function. Retry the program, instead with this code:

def groceries(oranges):
    global orangePrice
    print("Orange price inside function: ", orangePrice)
    orangeTotal=orangePrice * oranges
    return orangeTotal

print("Enter a price for the oranges")
orangePrice=float(input())

totalPrice = groceries(3)

print("Orange price outside function: ", orangePrice)

print("Orange total: ", totalPrice)

     The program should be debugged now and you should get this:

Enter a price for the oranges
3
Orange price inside function:  3.0
Orange price outside function:  3.0
Orange total:  9.0

     The program has now calculated the price correctly! You see, the user's input didn't exist in the function because it was created after the function. I know, still confusing, but that's the best explanation I can think of. But with the global keyword, the function knew there was a variable somewhere in the program it needed to use. This can be very useful when you need to use something in a function and somewhere else!

     That's just about it for this article. I challenge you to edit the program so it takes several different prices inputted by the user!

No comments:

Post a Comment