Saturday, June 13, 2020

Python Basic Syntax Tutorial



Hello guys! Welcome back to another section of my 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. However, there are some major differences between the languages.

Our First Python Program

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

Script Mode Programming

Invoking the interpreter with a script parameter begins an execution of the script and continues 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 set in 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. Below is the modified test.py file -

#!/usr/bin/python 

print  "Hello,  Python!"

Let us 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 Lang. program 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 up an identifier with two leading underscores, it indicates a more strongly private identifier.



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 provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by the 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 make sure 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 typically ends with a new line. The Python program does, however, allows for the use of the line continuation character (\) to denote that the line should continue.

Example

Following below is a short example -

 total =  item_one  + \ 
              item_two  + \ 
              item_three

Statements that are 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 indicate string literals, provided same type of quote starts 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 is not inside of 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 same line after a statement or even 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 a whitespace, possibly with a comment, is known as a blank line and Python will totally ignore it.

In an interactive interpreter session, in order 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, which makes up a single code block are called 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 which make up the suite.

Example
Following below is a short example -

 if  expression : 
      suite 
 elif  expression : 
      suite else : 
      suite


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

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

Command Line Arguments 
Many programs can be 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 program your script in such a way that it should accept various options. The Python Command Line Arguments is an advanced topic that will be discussed in my subsequent tutorials.

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

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.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.