From Python Tutorial 01, we have installed the Spyder application. Spyder application is the IDE for Python.
Now let us to start creating the first application.
But before hand, let us go through the basic arithmetic operator that Python use. Some of them appears only available in Python.
*;;;43 * 3;;;129;;;Multiplication;nn;
**;;;43 ** 3;;;79507;;;43 to power 3;nn;
//;;;43//3;;;14;;;Same is divide, but only take the integer part and disregard the remainder;nn;
Our first Python Function
Okay! Let’s try to create the first Python Function – area_triangle.
Area_Triangle is a function that calculate the area of a triangle. It accepts to input arguments:
- Base &
Following is the formula for calculating the area size of a triangle:
0.5 * Base * Height
Following is the steps:
- New a Python document in Spyder.
- Spyder will create a new file automatically.
You will find that the first 7 lines have something by default. The first link is the code setting and the 2nd to the 7th line is the document info.We will have look into the this in later tutorial. Now, let’s focus on creating new functions
- Following is my function
Line 1 – 7:
Was generated by Spyder. So leave it at the moment
“#%%” – This is a cell separator. It is a IPython function. IPython allow us to divide the entire program into different cells using “#%%” function. A cell simply a session on the file.
An Python file and have many cells and they are separated by the “#%%” operator.
This is where my new function is
- “Def” Statement is to define the function Area_triangle that accept two variables “Base” and “Height” and calculate the area.
- All indented statements immediate go under the Def Statement will be considered as a statement belongs to the function.This program is adding 4 spaces at the beginning of each line as indentation instead of using a tab. This is because using a tab may cause some issue to Python.
Line 11 – Line 20 :
“”” <documentation > “””
I have documented this function by writing down what is this function for, how does it work etc. It is mainly for our own future references.
Line 21 – 23:
Calculate the area and using the print function to print the results.
Note: Python variable name is case sensitive. This means a variable “Area” is separate from the variable “area”.
Run the new function
Now we have finished writing the function. Following is the steps to run the function.
- Right click the cell and click “Run cell” from the menu
- This will load the program in the Python automatically.
- We will see it from the IPython console
- To run the function, type “area_triangle(<base>,<height>” in the Console Following image is an example
Let’s try to see the help function for this newly created function.
- Click the cell again.
- Press <Ctrl +I> from the keyboard