[Tutor] help writing functions

Alan Gauld alan.gauld at btinternet.com
Thu Feb 23 09:49:39 CET 2012

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
    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.

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list