An alternative to a global variable?
The code below gives the desired output. However, what is the alternative to using global variables? I have to use multiple functions.
#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()
+3
source to share
1 answer
First of all,
If it is not part of some larger program and does not need to be called from any other script, then the functions are unnecessary.
You can just create a program with no functions. Directly request input and output output.
Second,
combine the two functions; this eliminates the need 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 )
Moreover, you can create a class to cover the entire calculation.
0
source to share