By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,660 Members | 1,187 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,660 IT Pros & Developers. It's quick & easy.

Function to take input as string, input parameter to function

P: 2
Ok, so I am almost done with this question:
Write and test a function to take as input a list of strings (each of which
represents a number) and to return a list of numeric values. For example, if
the input to the function is [67, 8,75] and return [67,8,75]. The input
should be as a parameter to the function.


here is the code I have written:
Expand|Select|Wrap|Line Numbers
  1. def func( num1, *numtuple):
  2.     print num1
  3.     for num in numtuple:
  4.         print num
it works fine except for the fact that the input HAS to be as a string. Any help would be great because I am stumped.

Cheers
Sep 4 '10 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
The instructions require the function argument to be a list of strings as in
Expand|Select|Wrap|Line Numbers
  1. ['1','2','3']
This can be done two ways.
Expand|Select|Wrap|Line Numbers
  1. def f(*args):
  2.     # Accept a variable number of arguments
  3.     pass
  4.  
  5. def f(strList):
  6.     # Accept a single argument
  7.     pass
Your function must return a list of numbers. This can be done several ways, but you must use the return statement as in
Expand|Select|Wrap|Line Numbers
  1. def f(*args):
  2.     # Calculate somevalue
  3.     return somevalue
Assuming the numbers are all integers, here are some examples:
Expand|Select|Wrap|Line Numbers
  1. >>> strList = ['1','2','3']
  2. >>> map(int, strList)
  3. [1, 2, 3]
  4. >>> [int(n) for n in strList]
  5. [1, 2, 3]
  6. >>> result = []
  7. >>> for n in strList:
  8. ...     result.append(int(n))
  9. ...     
  10. >>> result
  11. [1, 2, 3]
  12. >>> 
HTH
Sep 4 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.