Python Syntax
Python Syntax
The syntax or code writing style of Python is very easy. It is somewhat similar to writing code in english language. This is the speciality of Python that we can execute large tasks in less line of code as comapred to other languages. For example, suppose you want to write a code of "Hello World". In C or Java you have import some libraries first and then make a function (in C) or class (in JAVA) and then write the code in that particular block. But in Python you can make this program in single line like,
As you can see you saved your time in Python. Only single line of code and you get the result. In above example, I used the Python Shell to execute the line, but we can also make python script also. Just create a file with .py extension and write your code in that file and execute it. To execute the file, just open it in the python shell and click on the run button that you will see in the menu bar and your file will get execute. To execute the file in cmd, just type the command python and your filename with extension, for example suppose that you have a script file named myfile.py then to execute it in cmd type :
python myfile.py
Indentation :
As I said that the syntax of python is very easy but there are also some rules to follow in terms of syntax. In C or Java, to show a particular code block we use curly braces "{}", but in Python we use the indentation to a particular block of code. Indetation is generally is 4 spaces or 1 tab, but the spaces is upto programmer atleast one. You have to use the same number of spaces in the same block of code, otherwise there will be error. For example:
As you can see after the line of for loop, next line starts with the spaces called indetation which shows that this line belongs to this particular block of code. The colon (:) in the for loop line is also the Python way of writing the loops. In functions and classes also colon is used which we will cover later.
Comments :
Comments are the non executable part of the code but very important. Comments are the simple plain language text which describes what is happening in the code at a particular line or block. Comments help developers to understand the program working and logic. In python there are two ways to make comments i.e. single line comment and multi line comments.
To make a single line comment just use # before the line.
To make multiline comment, use triple single or double quotes.



Comments
Post a Comment