How to Define a Function in Python
Creating a function doesn’t require much work. Python tends to make things fast and easy for you. The following steps show you the process of creating a function that you can later access:
1Open a Python Shell window.
You see the familiar Python prompt.
2Type def Hello(): and press Enter.
This step tells Python to define a function named Hello. The parentheses are important because they define any requirements for using the function. The colon at the end tells Python that you’re done defining the way in which people will access the function. Notice that the insertion pointer is now indented. This indentation is a reminder that you must give the function a task to perform.
3Type print(This is my first Python function!) and press Enter.
You should notice two things. First, the insertion pointer is still indented because IDLE is waiting for you to provide the next step in the function. Second, Python hasn’t executed the print() function because it’s part of a function and is not in the main part of the window.
The function is now complete. You can tell because the insertion point is now to the left side. In addition, the Python prompt (>>>) has returned.
Even though this is a really simple function, it demonstrates the pattern you use when creating any Python function. You define a name, provide any requirements for using the function (none in this case), and provide a series of steps for using the function. A function ends when an extra line is added (you press Enter twice).
Working with functions in the Edit window is the same as working with them in the Python Shell window, except that you can save the Edit window content to disk.