One way to do this would be with the following:
def costEdit(nCost):
nCost = '%.2f'%(nCost*1.25)
#nCost = nCost*1.25
return nCost
Let me break this down for you.
Take the line:
'%.2f'%(nCost*1.25)
And break it down into its components:
(' ( (%) .2f) ')%(nCost*1.25)
- Everything inside
''
is just a normal string.
- The
%
is a symbol that means "substitute in later".
.2f
is a command in Python that truncates 2 places after a decimal.
%(nCost*1.25)
means "nCost*1.25
is what you put in place of %
"
So in order, it does the math of nCost*1.25
, puts it inside the string, then cuts off everything else and gives you what is left.
Take note that I've rewritten your costEdit
function to accept nCost
as an argument. This means that now you can call:
costEdit(nCost)
with any number that you want, and it will do the math.
Also note I've replaced print
with return
. This means that now, you will have to write:
print costEdit(80)
to get
100
However it now means you can do math with costEdit
, such as:
print 4*costEdit(80)
and instead of printing 100
along the way, it will just print
400
Questions? Leave a comment.
Happy coding!
EDIT: Regarding your error,
I think I've reproduced it and understand the problem.
When I type:
costEdit('15')
I get your error.
This is because when you do costEdit('15')
, you're entering '15'
and not 15
. If a value is between ''
or ""
, you're dealing with a value of type string
.
In python, you can't multiply a float
(type of number) with a string
. That's what this is complaining about.
To remedy the situation, just remove the quotes. Then you're entering a number of type float
or int
(integer), both of which can be multiplied by a float
(the value 1.25
inside costEdit()
).
I hope this solves your issue-- I have to get off the PC for the night. If it doesn't help, leave a comment and I'll return tomorrow.
Otherwise, I'm glad I could help and remember to select a best answer on your question, so those who helped can get their precious precious pointssssss