Python Basic Syntax Tutorial



Hello dear readers! Welcome back to another edition of our tutorial on Python. In this tutorial post, we are going to be discussing about the Python Syntax.

The Python language shares many things in common with Java, C and Perl. Nevertheless, there are some major differences between the languages.

Our First Python Program

Let us now take a look at how to execute programs in the various modes of programming.

Script Mode Programming

Invoking the Python's interpreter with a script parameter begins an execution of the script and then continues with the execution until the script is finished. The Python interpreter will no longer be active once the script is finished.

Let us now write a simple Python program in a script. The Python files has an extension of .py. Type the following source code in the test.py file -

print   "Hello,   Python!"

We assume that you have Python interpreter already set in the PATH variable. Now try running this code as follows -

$   python  test.py

Output

This above code will produce the following output.

Hello, Python!

Let us try another way to execute a Python script. The following below is the modified test.py file -

#!/usr/bin/python 

print  "Hello,  Python!"

We assume that you have Python interpreter available in the usr/bin directory. Now, try to run the code as follows -

$   chmod  +x  test.py                 #  This is to make file executable 

$./test.py

Output

This will produce the following output -

Hello, Python!


Interactive Mode Programming

Invoking the Python's interpreter without passing a script file as a parameter will display the below prompt -

$  python 
Python   2.4.3  (#1,  Nov  11  2010,  13:34:43) 
[GCC  4.1.2  20080704  (Red  Hat  4.1.2-48)]  on  linux2 
Type  "help",  "copyright",  "credits"  or  "license" for more information. 
>>>

Type the following text into the Python prompt and press Enter -

>>>   print   "Hello, Python!"

If you are running the new version of Python, then you will need to make use of the print statement along with parenthesis as in to print ("Hello, Python!");. However in Python version 2.3.4, this will produce the following output -

Hello, Python!


Python Identifiers

A Python identifier is a name that is used in identifying a variable, module, class or any other objects. It starts with the letter A to Z or even a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 - 9).

Python does not allow punctuation characters such as %, $ and @ within identifiers. Python is a Case Sensitive language, therefore Hello and hello are two different identifiers in Python.

Following below are the naming convention for Python identifiers -

  • The class name starts with an uppercase letter. All other identifiers starts with a lower case letter.
  • Starting an identifier with a single leading under score indicates that the identifier is private.
  • When you start an identifier with 2 leading underscores, it indicates a more strongly private identifier.
  • If the identifier ends with two trailing underscores, then the identifier is language defined special name.



Python Reserved Keywords

The following table contains a lists of all the Python Keywords. These are reserved words and can not be used as constant or variable or any other identifier name. All of these reserved keywords contains only lowercase.

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield

Lines and Indentation

Python does not provide braces to indicate blocks of code for class and function definitions or flow control. The blocks of code are denoted by line indentation, which is strongly enforced.

The number of the spaces in the indentation variable, but all spaces within the block must be indented. For example -

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

However the following block below generates an error message -

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

Thus, in Python all the continues lines indented with same number of spaces is going to form a block. The following example below has various statement blocks -

Note - Do not try to understand the logic at this point in time. Just try to understand the various blocks even if they are without braces.

#!/usr/bin/python 

import sys 

try: 
     # open file stream 
     file =  open(file_name, "w") 
except  IOError: 
     print "There was an error writing to",  file_name 
     sys.exit( ) 
print  "Enter '",  file_finish, 
print  "' When finished" 
while  file_text != file_finish: 
     file_text =  raw_input("Enter text: ") 
     if file_text ==  file_finish: 
          # close the file 
          file.close 
          break 
     file.write(file_text) 
     file.write("\n") 
file.close( ) 
file_name =  raw_input("Enter filename: ") 
if len (file_name) == 0: 
     print  "Next time please enter something" 
     sys.exit( ) 
try: 
     file open(file_name, "r") 
except  IOError: 
     print  "There was an error reading file" 
     sys.exit( ) 
file_text file.read( ) 
file.close( ) 
print  file_text


Multi Line Statements

Statements in Python ends with a new line. Python, however, allows for the use of the line continuation character (\) to indicate that the line should continue.

Example

The following below is a short example -

 total =  item_one  + \ 
              item_two  + \ 
              item_three

Statements contained within the {}, [] or () brackets do not need to make use of the line continuation character. For example -

days  =  ['Monday',  'Tuesday',  'Wednesday', 
                'Thursday',  'Friday']

Quotation in Python

Python program accepts single ('), double ("), triple ("' or """) quotes to denote string literals, provided the same type of quote begins and ends the string.

Triple quotes are used to span the string across multiple lines.

Example

Following below are legal -

word  =  'word' 
sentence  =  "This is a sentence." 
paragraph  =  """This is a paragraph. It is made 
up of multiple lines and sentences."""


Python Comments
A hash sign (#) that's not inside a string literal begins a comment. All the characters after the # and up to the end of the physical line are part of the comment and is been ignored by the Python interpreter.

#!/usr/bin/python 

#  First comment 
print  "Hello,  Python!"    # second comment

This will produce the following output -

Hello,  Python!

You can type in a comment on the same line after a statement or an expression -

name =  "Madisetti"    # This is again comment

You can comment multiple lines as follows -

#  This is a comment. 
#  This is a comment, too. 
#  This is a comment, too. 
#  I said that already.

The following triple quoted string is also ignored by the Python interpreter and can as well be used as a multi-line comment.

 ''' 
 This is a multiline 
 comment.
 '''


Using Blank Lines
A line containing only whitespace, maybe with a comment, is known as a blank line and Python totally ignores it.

In a Python's interactive interpreter session, to terminate a multiline statement, you must enter an empty physical line.

Waiting for the User
The following line of the program displays the prompt, saying "Press the enter key to exit", and waits for the user to take action -

#!/usr/bin/python 

raw_input("\n\nPress the enter key to exit.")

Here, "\n\n" is 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 the console window open until the user is done with an application.

Multiple Statement Groups as Suites
A group of individual statements, that makes up a single code block are suites. All those compound or complex statements, such as def, if, while, and class requires a header line and suite.

Header lines begin the statement and ends with a colon and are followed by one or more lines that makes up the suite.

Example
The following below is a short example -

 if  expression : 
      suite 
 elif  expression : 
      suite else : 
      suite


Multiple Statements on a Single Line
Semicolon (;) allows for multiple statements on a single line given that neither statement start a new code block. Following below is a sample snip using the semicolon -

import  sys;  x =  'foo';  sys.stdout.write(x + '\n')

Command Line Arguments 
Many programs can run to provide you with some basic data about how they should be run. Python enables you to do this with -h-

 $   python  -
usage:  python [option] ... [-c cmd | -m mod | file | -] [arg] ... 
Options and arguments (and corresponding environment variables): 
-c cmd : program passed in as string (terminates option list) 
-d : debug output from parser (also PYTHONDEBUG=x) 
-E : ignore environment variables (such as PYTHONPATH) 
-h : print this help message and exit 

[ etc. ]

You can code your script in such a way that it should accept various options. The Python's Command Line Arguments is an advanced topic that will be discussed in our subsequent tutorials.

Alright guys! This is where we are rounding up for this tutorial. In our next tutorial, we will be discussing about the Python Data Types

Do feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.