-
Book Overview & Buying
-
Table Of Contents
Python Illustrated
By :
We can think of a function as a magic spell that groups separate lines of code. Instead of rewriting the incantation each time, you name your spell, define it once, and then call it at will. The more spells (functions) you have in your code, the more readable and easy to maintain your program becomes, because it can do complex tasks with a single invocation of the right function (ideally with a very descriptive name).
We declare a function with the keyword def, followed by the function name, a pair of parentheses, and a colon. Inside the parentheses, we can optionally have parameters; we’ll see these soon. Here’s a simple example without parameters:
def greet():
print("Hello humans!")
We used def to say, “I’m defining a function.” The name of the function is greet. And inside the function body (which is indented), we placed a print statement. As it stands, this function just prints a message when called...