CFC
CFC

Reputation: 33

Confused with global constants (python)

Hi this is the problem we were given

"Write a Python program which asks the user to enter their gross pay and then calculates net pay based on the following deductions;  PRSI 3%,  Health Contribution 4%  PAYE 41%  U.S.C. 7% Hint: Deductions should be represented as global constants. Your program should include a number of functions i.e. a function to display instructions to the user; a function which takes input from the user and then calls a third function which calculates net pay (i.e. gross pay – deductions)"

Here is my effort

def instructions():
    print ("Hello, and welcome to the programme")


def getOutput():
    G = int(input("Enter gross income: "))
    return G


def displayBreak():
    print("")
    print("Less deductions")
    print("---------------")



def doDeductions():
    Value=G*.03
    Health=G*.04
    Pay=G*.41
    Social=G*.07
    Net=G-Value-Health-Pay-Social

print("PRSI                    ",Value)
print("Health Contrb.          ",Health)
print("PAYE                    ",Pay)
print("USC                     ",Social)
print("")
print("Net Pay                 ",Net)
print("Programme Complete")



################################################


instructions()

print("")

getOutput()


displayBreak()

print("")

doDeductions()

This "doDeductions" will not work I know it is wrong but I have no idea why

Any help would be greatly appreciated,

Thanks

Upvotes: 0

Views: 126

Answers (1)

furkle
furkle

Reputation: 5059

The problem is that you're not storing Value, Health, Pay, Social, or Net anywhere but inside your function. These values exist only for the duration of the doDeductions() method, and only within that scope. They do not exist once you get to your chain of print() statements, which is one of the reasons the program would not run - you were asking it to print non-existent objects.

Note that you're also ignoring one of the mandates of your assignment, which is to store the deductions as global constants.

What you should do, outside the context of a class, is store global values:

PRSI = 0.03
HEALTH_CONTRIBUTION = 0.04
PAYE = 0.41
USC = 0.07

G = 0
Value = 0
Health = 0
Pay = 0
Social = 0
Net = 0

def getOutput():
    doDeductions(int(input("Enter gross income: ")))

def doDeductions(G):
    global Value, Health, Pay, Social, Net, PRSI, HEALTH_CONTRIBUTION, PAYE, USC
    Value = G * PRSI
    Health = G * HEALTH_CONTRIBUTION
    Pay = G * PAYE
    Social = G * USC
    Net = G - Value - Health - Pay - Social

The global keyword is used to state to the interpreter that the variable you are defining in a non-global scope should be assigned to the global variable.

This is a really ugly way of doing this, though, and one of the advantages of classes is that you can have members which you can access with self.member, rather than needing to call global every single time you refer to a variable in the top scope.

Upvotes: 1

Related Questions