Python Basic Syntax

Python is a very simple language, and has a very straightforward syntax. It encourages programmers to program without boilerplate (prepared) code. The simplest directive in Python is the “print” directive – it simply prints out a line (and also includes a newline, unlike in C).

There are two major Python versions, Python 2 and Python 3. Python 2 and 3 are quite different. Python 2 it is more widely used and supported. However, Python 3 is more semantically correct, and supports newer features.

For example, one difference between Python 2 and 3 is the print statement. In Python 2, the “print” statement is not a function, and therefore it is invoked without parentheses. However, in Python 3, it is a function, and must be invoked with parentheses.

To print a string, just write:

print “This line will be printed.”

Basic Syntax and first example Hello Python:-

  • All python files will have extension .py
  • put the following source code in a test.py file.

print “Hello, Python!”;#hello world program

  • run this program as follows:

$ python test.py

  • This will produce the following result: 

Hello, Python!

You can use the shell to write the python program in linux. Shell editor can be opened by vi editor. If you want to know how to open a editor using vi, follow the below link.

For example to write a python program, open/create a file using vi as follows:

  • vi testhello.py 

This will create a python file. press i to go in insert mode.

  • type the following code.

#!/usr/bin/python

print “Hello, Python!”

  • This produces the following result −

Hello, Python!

Web Hosting

Python Identifiers

  • Identifier is Identify (name) a variable, function, class, module or other object.
  • Identifier is a combination of alphanumeric characters, the first being a letter of the alphabet or an underline, and the remaining being any letter of the alphabet, any numeric digit, or the underline.
  • An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
  • Python does not allow punctuation characters such as @, $ and % within identifiers.
  • Python is a case sensitive programming language. For example, Manpower and manpower are two different identifiers in Python.
  • Starting an identifier with a single leading underscore indicates by convention that the identifier is meant to be private.
  • Starting an identifier with two leading underscores indicates a strongly private identifier.
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

 Lines and Indentation

  • No braces to indicate blocks of code for class and function definitions or flow control.
  • Blocks of code are denoted by line indentation, which is rigidly enforced.
  • The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. 

Indentation Example

if True:

print “True”

else:

print “False“

 Or even better

if True:

print “True”

else:

print “False“

Multi-Line Statements

  • Multi line statement would be as follows:-

total =  item_one +

item_two +

item_three

  • Statements contained within the [], {} or () brackets do not need to use the line continuation character

For example: –

days = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’,’Sunday’]

Quotation in Python

  • Python accepts single (‘), double (“) and triple (”’ or “””) quotes to denote string literals as long as the same type of quote starts and ends the string.
  • The triple quotes can be used to span the string across multiple lines.

Example :

  • word = ‘word’
  • sentence = “This is a sentence.”
  • paragraph = “””This is a paragraph. It is

made up of multiple lines and sentences.

We are using here 3 double quotes”””

Single line Comment in Python

All characters after the # and up to the physical line end are part of the comment and the Python interpreter ignores them.

For example:

print “Hello, Python!”; # comment start after pressing # key

Multi line Comment in Python

Triple quoted lines represent multi line comments in python. For example:

”’

This is a multiline
comment.
”’

Waiting for the User in Python

The following line of the program displays the prompt, “Press the enter key to exit” and waits for the user to press the Enter key:

 raw_input(“nnPress the enter key to exit.”)

Here, “nn” are being used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.

Multiple Statements on a Single Line

The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon:

import sys; x = ‘foo’;

This is the same as below code:

import sys;

x = ‘foo’;

Multiple Statement Groups as Suites

A group of individual statements, which make a single code block are called suites in Python.

Compound or complex statements, such as if, while, def, and class, are those which require a header line and a suite.

Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite.

For example:

if expression :

suite

elif expression :

suite

else :

suite

 

Related Posts

  • 92
    A sample Program #!/usr/bin/python print "Hello, Python!"; Outupt: Executing the program.... $python2.7 main.py Hello, Python! What is Python? Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU…
    Tags: python
  • 82
      Welcome to the Python Knowledge Base and Tutorial   Python : Overview : What is Python? Why learn Python? Feature of Python Basic Syntax Where to write python program? Check if python already installed Python : Installation on Windows and Simple Example How to install python in windows? Simple Example…
    Tags: python
  • 55
    As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why. For this reason, it is a good idea to add notes to…
    Tags: python
  • 55
    Example: !/usr/bin/python a = 21 b = 10 c = 0 c = a + b print "Line 1 - Value of c is ", c c += a print "Line 2 - Value of c is ", c c *= a print "Line 3 - Value of c is…
    Tags: print, example, python
  • 54
    Example: #!/usr/bin/python a = 10 b = 20 list = [1, 2, 3, 4, 5 ]; if ( a in list ): print "Line 1 - a is available in the given list" else: print "Line 1 - a is not available in the given list" if ( b not…
    Tags: print, python, example

Satya Prakash

VOIP Expert: More than 8 years of experience in Asterisk Development and Call Center operation Management. Unique Combination of Skill Set as IT, Analytics and operation management.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: