Basic Syntax

Hello World – Our First Python Program

Let us now create our very first python program. We will show you two ways to print “Hello World” in python.

Using the Python Interpreter

With the Python interactive interpreter, it is easy to check Python commands. The Python interpreter can be invoked by typing the command “python” without any parameter followed by the “return” key at the shell prompt: In your terminal/shell type

$python

This should open up an interactive prompt as shown below

Python 2.7.15+ (default, Nov 27 2018, 23:36:35) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Type the following text at the Python prompt ‘>>>’and press the Enter

>>> print "Hello, World!"

Note: To close the Python interactive interpreter in Linux type Ctrl-D

Execute a Python Script

Now we will create a python program using a script file. Python scripts have a .py extension eg script.py. To save and edit programs in a file we need an editor. There are lots of editors, but you should choose one, which supports syntax highlighting and indentation. Example of editors: sublime, pycharm, Atom, Visual Studio, vi, vim, emacs, geany, gedit, etc. Create a file and name it as hello.py. Type the following in the hello.py file and save it.

print "Hello, World!"

We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −

$ python hello.py

The result should be:

Hello, World!

Congratulations, you just created your very first Python program!

Lines & Indentation

Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported, but the standard indentation requires standard Python code to use four spaces. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example:

if True:
    print "True"
else:
    print "False"

Quotation in python

Python accepts single (‘) and double (“) quotes to denote string literals, as long as the same type of quote starts and ends the string.

word = 'word'
sentence = "This is a sentence."

Comments in python

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

# This is a comment

print "A commented string" # This is a comment and is ignored

Tripled quoted strings are also comments and mainly used for multi-line comments. For Example:

""" This is a
multi-line comment. 
"""