[Tutor] help writing functions

Saad Javed sbjaved at gmail.com
Thu Feb 23 16:41:44 CET 2012


Sorry for the formatting. Added return statements to both functions. Adding
return [x, y] to get_value func. That solved the problem. Thank you! :)

Saad

On Thursday, February 23, 2012, Alan Gauld wrote:

> On 23/02/12 00:59, Saad Javed wrote:
>
>  [CODE]feed = urllib.urlopen(rssPage) #rssPage: address of xml feed
>> tree = etree.parse(feed)
>> x = tree.xpath("/rss/channel/item/**title/text()")
>> x = str(x[0])
>> for tag in tags: #tags is a list of items like hdtv, xvid, 720p etc
>> x = re.sub(r'\b' + tag + r'\b', '', x)
>> z = re.sub(r'[^\w\s]', '', x)
>> y = tree1.xpath("/rss/channel/**item/pubDate/text()")
>> print "%s - %s" %(z.rstrip(), y[0][:16])[/CODE]
>>
>
> Please don;t insert wiki style markers, its just confusing.
> Also please use plain text for email otherwise the formatting
> tends to get lost.
>
>  [CODE]def get_value(feed):
>> try:
>> url = urllib2.urlopen(feed)
>> tree = etree.parse(url)
>> x = tree.xpath("/rss/channel/item/**title/text()")
>> y = tree.xpath("/rss/channel/item/**pubDate/text()")
>> x = str(x[0])
>> y = str(y[0][:16])
>> return x
>> return y
>>
>
> This will always return x and never y because a return statement
> terminates the function. If you want to return both values you need to put
> them in the same return statement:
>
> return x,y
>
> If you want to return only one you need to select which
> with an if/else.
>
> return x if <some condition> else y
>
> or just
>
> if <some condition>
>   return x
> else
>   return y
>
> If you prefer.
>
>  except SyntaxError:
>>
>
> You should probably not try catching Syntax errors since thats usually a
> fault in your code! Instead fix the syntax error.
>
>  def del_tag(x):
>> tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '720P',
>> 'IMMERSE', '720p', 'X264']
>> for tag in tags:
>> x = re.sub(r'\b' + tag + r'\b', '', x)
>> y = re.sub(r'[^\w\s]', '', x)
>>
>
> You don't return x or y so they get thrown away at the end of the
> function. Which makes the whole thing a waste of space...
>
>  def main():
>> a = get_value(rssPage)
>> b = del_tag(a)
>> print b
>> if __name__ == '__main__':
>> main()[/CODE]
>>
>> Running this code returns [B]None[/B].
>>
>
> None is the default return value if you do not provide one.
> main has no return statement. Neither does del_tag()
> Both main and del_tag will therefore return None.
>
> HTH
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120223/509451a0/attachment-0001.html>


More information about the Tutor mailing list