[Tutor] please help me modify this code so that I can utilize raw_input
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Oct 4 14:11:54 EDT 2016
On 04/10/16 15:04, Richard Koeman wrote:
> I would like to modify this code so that instead of me calling the function
> with the list as shown [1,2,3,4], the user inputs the list with raw_input.
>
You don't need to modify your code you just need ton write a function
that reads a list from the user. Notice that this can e done by either
repeatedly asking the user to input values until they are done or by
reading a string containing the values and converting the string to a
list of numbers.
> """Define a function sum() and a function multiply() that sums and
> multiplies (respectively) all the numbers in a list of numbers. For
> example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4])
> should return 24."""
<rant>
I do wish teachers would not ask students to reinvent the wheel.
Python already has a perfectly good sum() function.
And both problems become trivial if using functools.reduce()
</rant>
>
> def sum(mylist = [], *args):
> print mylist
> sum_of_number = 0
> for i in mylist:
> sum_of_number += i
> print "The sum of the digits in your number is %s" %(sum_of_number)
> def multiply(mylist = [], *args):
> product_of_number = 1
> for i in mylist:
> product_of_number = product_of_number * i
> print "The product of the digits in your number is %s"
> %(product_of_number)
>
> sum([1,2,3,4])
> multiply([1,2,3,4])
Incidentally, notice that the assignment asks you to *return* the
results not print them. This is good practice, keep the printing
separate from the calculation. You can then print the result,
if you wish, with
print( sum([....]) )
hth
--
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