[Tutor] variable * raw_input
Alan Gauld
alan.gauld at btinternet.com
Tue Aug 7 23:33:20 CEST 2007
"Dewight Kramer" <dfkramer at ucdavis.edu> wrote
> quality. But I dont understand something below is code.
Since you don't tell us what exactly you don't undertand
I'll make some general comments on the code...
> # establish variables
> bill = float(0.0)
> bad = float (0.0)
> ok = float(0.10)
> good = float (0.15)
> great = float (0.20)
You don;t need the float() call because the values are
already floats by dint of having a decimal point in them.
float is really for converting non float values(integer or string)
to floats.
> service="nothing"
> tip = float ()
> total = float ()
these lsat two will be the same as
tip = 0.0
total = 0.0
> print "This is a tipping calculator."
>
> bill = raw_input ("\nWhat was the total bill amount? ")
raw_input returns a string, you probably want to convert that to
a float, so here you do want to use float(), like so:
> bill = float(raw_input ("\nWhat was the total bill amount? "))
> service = raw_input("Please input one of the following to"+
> " describe the service:"+"\nbad\nok\ngood\ngreat
> \n")
You could use a triple quoted string here for clearer layout:
service = raw_input(
"""Please input one of the following to describe the service:
bad
ok
good
great
""")
> tip = bill * service
But now you are trying to multiply a number(bill) by a string ('ok',
'bad' etc)
Thsat won;t work, instead you need to convert the string into some
kind
of number. The common way to do that would be using a dictionary:
serviceVal = {'bad': 0, 'ok': 0.1, 'good': 0.15, 'great':0.2}
and now the tip line looks like:
tip = bill * serviceVal[service]
> total = bill + tip
> print "Then you should leave a" + tip + "tip. This will bring the
> total to" + total +"."
You might find this easier using string formatting
print "Then you should leave a $%.2f tip. This will bring the total to
$%.2f." % (tip, total)
Notice how that lets you control what the output looks like
more precisely.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list