*= operator
Frank Millman
frank at chagford.com
Sat Nov 21 08:46:46 EST 2015
"Cai Gengyang" wrote in message
news:a76b1b5b-4321-41bb-aeca-0dac787752d9 at googlegroups.com...
> This is a piece of code that calculates tax and tip :
>
> def tax(bill):
> """Adds 8% tax to a restaurant bill."""
> bill *= 1.08
> print "With tax: %f" % bill
> return bill
>
> def tip(bill):
> """Adds 15% tip to a restaurant bill."""
> bill *= 1.15
> print "With tip: %f" % bill
> return bill
>
> meal_cost = 100
> meal_with_tax = tax(meal_cost)
> meal_with_tip = tip(meal_with_tax)
>
> Does bill *= 1.08 mean bill = bill * 1.15 ?
Firstly, I assume that you actually meant 'bill = bill * 1.08' at the end of
the last line.
Secondly, how can I help you to answer this kind of question yourself.
Here are two ways.
1. Try it out at the interpreter -
c:\>
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> bill = 100
>>> bill *= 1.08
>>> bill
I deliberately omitted the last line. Try it yourself and see what you get.
2. Read the fine manual.
The Index has a section headed 'Symbols'. From there you will find '*=',
with a link to 'augmented assignment'.
If you follow the link, you will find a detailed explanation. Here is an
excerpt -
"An augmented assignment expression like x += 1 can be rewritten as x = x +
1 to achieve a similar, but not exactly equal effect. In the augmented
version, x is only evaluated once. Also, when possible, the actual operation
is performed in-place, meaning that rather than creating a new object and
assigning that to the target, the old object is modified instead."
Frank Millman
More information about the Python-list
mailing list