3

The code below gives the desired result. However, what is the alternative to using global variables? I have to use more than one function.

#Initialising 
feeOne =0.0
feeTwo =0.0
country = ""
rate=""
total =0.0
sFee = 10.0

def dets():
    global sFee, feeOne, feeTwo

    country=input("What is your country? ")
    rate=input("What is your rate? High or Low: ")

    if country =="UK":
        feeOne = 10.0
    else:
        feeOne = 20.0

    if rate=="High":
        feeTwo = 10.0
    else:
        feeTwo = 20.0

def total():
    total = (sFee + feeOne) * feeTwo
    print(total)

dets()
total()
  • 1
    Use OOP pattern or a .py script with that var's declared where you will include into others scripts as you wish. – capcj May 08 '17 at 12:05
  • Sorry - I am quite new to this. I am not sure what that means? Could you please possibly give me an example of how to do this? – Sarah Proctoer May 08 '17 at 12:10
  • First: http://stackoverflow.com/questions/19158339/why-are-global-variables-evil Create a .py script where you instanciate your variables and go on. http://stackoverflow.com/questions/16011056/how-to-avoid-global-variables – capcj May 08 '17 at 12:16
  • I have read these - from what I understand I make different instances of a variable? I think I am completely at a loss. – Sarah Proctoer May 08 '17 at 12:40
  • I will try to help you, sry, i'm at work: You can create a third function that englobes dets and total, understand? You can use parameters too. There's a multiple alternatives for your implementation (that it's a simple code, don't take me bad). – capcj May 08 '17 at 13:07

1 Answers1

0

First of all,

If this is not part of some bigger program and does not need to be called from any other script then, functions are not needed.
You could just create a program without the functions. Directly asking input and displaying output.

Second,
merge the two functions;
this removes needs for any global functions, all functions are local functions

def dets():

    country=input("What is your country? ")
    rate=input("What is your rate? High or Low: ")

    if country =="UK":
        feeOne = 10.0
    else:
        feeOne = 20.0

    if rate=="High":
        feeTwo = 10.0
    else:
        feeTwo = 20.0

    total = (sFee + feeOne) * feeTwo
    print(total)
    ##

OR

    total = sfee 
    + ( 10.0 if input("What is your country? ") == "UK" else 20.0) 
    + ( 10.0 if input("What is your rate? High or Low: ") == "HIGH" else 20.0 )

More than that, you can create a class to envelop the entire calculation.

vintol
  • 48
  • 4