alki <webmaster at pawntastic.com> wrote in comp.lang.python: > So a function is just a group of codes? Then how do you use a function? Will > you please give me an example? Thanks Let's take a very simple example, a function that adds two numbers, x and y: def add(x, y): return x+y The function has two "arguments", named x and y, that can be used inside the function. The "return" statement tells it to return the sum of x and y. Now if we do sum = add(3,4) print sum later, that will print 7. "add(3,4)" calls the function, with the values x=3 and y=4 filled in. Therefore it returns 7, and that is called sum. A function can do a lot more, and use other functions in the same way. This function checks if a certain word occurs on a webpage (either in the html or the text itself), and returns 1 if it does, 0 if it doesn't: def find_word(url, word): import urllib, string page = urllib.URLopener().open(url).read() if string.find(page, word) != -1: return 1 else: return 0 This function uses a class from urllib, calls a few functions on it (they belong to the class, they're "methods", that's why you get the dot notation), and the function "string.find" (it's the function named "find", inside the "string" module) to easily get the work done. If find returns something other than -1, the word is on the page. The modules are full of already defined functions, and you probably already use some of them as well - if you have a list l, len(l) gives its length; and len() is the function that does that. -- Remco Gerlich
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4