We have seen the basics of Python in the previous blogs. Hope you have followed the previous blogs. Now let us see how to write programs and let us look at things that need to be noted while writing programs.
- A python file has a .py extension. For example: myfirstprogram.py
If you are using IDLE, go to File>New File ( or ctrl +N). Enter your code. Then Save the code by going to File>Save As. After this run the code by going to Run> Run Module ( or press F5). The output of the code will be displayed.Now, if you are using the command line terminal , open an editor from the terminal and specify the name of the python file. For example : vi myfirstcode.py or nano myfirstcode.py . This will take you to the editor. Enter the code. Exit the editor . Running the code requires you to enter “python myfirstcode.py” and press Enter.
Comments are used in python to make it easy for people viewing the code to understand the code. Comments are really important in programming. A user X may define his own variables and functions. Another user Y viewing this program may not understand those variables and functions. Hence comments can tell what each function or variable is.
Comments are not compiled by the compiler. They are just to provide meaning to code. Good programs have good comments.
Comments in python start with the hash character “#”.
a=a+1 #Here I increase the value of a by 1
Whitespace is the most important concept of python that often differentiates python from other programming languages. Whitespace is used to denote blocks. In other languages curly brackets (
}) are common. A block is nothing but a piece of the program that is executed as a unit. For example : a function definition.
Whitespace increases readability. It makes the code look neater and ordered.
for i in range(4):
Here the 2 print statements are written after a space from the column of the beginning of the for loop statement.
Whitespace is nothing but space. It can be given by pressing the space bar or the tab key. The tab key is always preferred. I suggest you to use tabs for whitespace. Please do not mix tabs and spaces and debugging will then be really hard.
4. Remember Python does not have variable declarations. Like other languages, python does not require variables to be declared before they are being used.
a=5 # a is considered as an integer.
5. To get input from the user.
number = input(‘Enter your number please: ‘)
This command will output ‘Enter you number please:’ on the terminal(output) screen and whatever the user inputs will be stored in the variable number. Using this command ,you can get the input from the user.
These are basic tools to be kept in mind before coding in python. In the next blog we will learn writing programs.
Image courtesy: Google Images