Other languagessuch as PHPread and process an entire file before executing it, which means you can call a function before it is defined because the compiler reads the definition of the function before it tries to call it. Python is different: If the function definition has not been reached by the time you try to call it, you get an error. The reason behind this behavior is that Python actually creates an object for your function, and that in turns means two things. First, you can define the same function several times in a script and have the script pick the right one at runtime. Second, you can assign the function to another name just by using =.

Function definition starts with def, then the function name, then parentheses and a list of parameters, and then a colon. The contents of a function need to be indented at least one level beyond the definition. So, using function assignment and dynamic declaration, you can write a script that prints the right greeting in a roundabout manner:

... print "Hello, " + Name + "!"

>>> def hello_hungarian(Name): ... print "Szia, " + Name + "!"

>>> hello = hello_hungarian >>> hello("Paul") Szia, Paul!

>>> hello = hello_english >>> hello("Paul")

Notice that function definitions include no type information. Functions are typeless, like we said. The upside of this is that you can write one function to do several things:

>>> def concat(First, Second): ... return First + Second

>>> concat(["python"], ["perl"]) ['python', 'perl'] >>> concat("Hello, ", "world!") 'Hello, world!'

That demonstrates how the return statement sends a value back to the caller, but also how a function can do one thing with lists and another thing with strings. The magic here is being accomplished by the objects. We write a function that tells two objects to add themselves together, and the objects intrinsically know how to do that. If they don'tif, perhaps, the user passes in a string and an integerPython catches the error for us. However, it is this hands-off, "let the objects sort themselves out" attitude that makes functions so flexible. Our concat() function could conceivably concatenate strings, lists, or zonksa data type someone created herself that allows adding. The point is that we do not limit what our function can dotacky as it might sound, the only limit is your imagination!



Was this article helpful?

0 0

Post a comment