[Tutor] Trouble with SUM()
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Apr 21 02:34:50 EDT 2019
On 20/04/2019 21:51, Ju Bo wrote:
> Hi, I'm trying to write a program that uses a while loop to ask a user for
> multiple values then use the program to add all the values, however many
> there may be, then print the sum.
Your code very nearly does that, it just needs a slight tweak.
> I'm having trouble with the sum()
> function.
You don't really need sum() here but you could use it if you
particularly want to. But in that case your understanding
of how it works needs adjusting.
First lets look at how to do it without sum()
> con = "y"
>
> while con == "y":
> AMT = float(input("What is the price of the item? $"))
> con = input("Would you like to continue? [y/n]")
> price = float(sum(AMT + AMT))
You want to add AMT to price not add AMT to itself.
The way to do that is to write
price = price + AMT
or using a Python shortcut:
price += AMT
You don't need to convert to float since you
already converted the input. adding floats produces
a float answer automatically.
Incidentally Python convention says to use all uppercase names
for constant values (In this case it might be something like
the maximum number of items you are allowed to buy). So you
should really change AMT to amt. But that is just a style issue.
Now, how would we use sum() if we wanted to?
sum() works by adding all the values of a sequence such as
a list or tuple. So to use sum() we first need to create an
empty list of amounts. Each time round the loop we then
append AMT to that list. At the end of the loop we can use
sum to get the final price.
price = sum(amounts)
Notice there are no addition operations inside the call
to sum(). sum() does all the addition for us internally.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list