Python Syntax

The Python syntax defines a set of rules that are used to create a Python Program. The Python Programming Language Syntax has many similarities to Perl, C, and Java Programming Languages. However, there are some definite differences between the languages.

Execute Python Syntax

As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line:


        >>> print("Hello, World!")
        Hello, World!

Or by creating a python file on the server, using the .py file extension, and running it in the Command Line:

C:\Users\Your Name>python myfile.py

Python Indentation

Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example


          if 5 > 2:
            print("Five is greater than two!")
        

Python will give you an error if you skip the indentation:

Example

Syntax Error:


          if 5 > 2:
          print("Five is greater than two!")
        

The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one.

Example


          if 5 > 2:
            print("Five is greater than two!")
          if 5 > 2:
                  print("Five is greater than two!")
        

You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:

Example

Syntax Error:


          if 5 > 2:
            print("Five is greater than two!")
                  print("Five is greater than two!")
        


Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object. 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. Thus, *Manpower* and *manpower* are two different identifiers in Python.

Here are naming conventions for Python identifiers:


Python Variables

In Python, variables are created when you assign a value to it:

Example

Variables in Python:


          x = 5
          y = "Hello, World!"

Python has no command for declaring a variable.

You will learn more about variables in the Python Variables chapter.


Comments

Python has commenting capability for the purpose of in-code documentation.

Comments start with a #, and Python will render the rest of the line as a comment:

Example

Comments in Python:


          #This is a comment.
          print("Hello, World!")

Python Reserved Words

and as assert
break class continue
def del elif
else except False
finally for from
global if import
in is lambda
None nonlocal not
or pass raise
return True try
while with yield

Python Multi-Line Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example:

Example


        total = item_one + \
                item_two + \
                item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example following statement works well in Python:

Example


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

Quotations 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 are used to span the string across multiple lines. For example, all the following are legal:

Example


          word = 'word'
          print (word)

          sentence = "This is a sentence."
          print (sentence)

          paragraph = """This is a paragraph. It is
            made up of multiple lines and sentences."""
          print (paragraph)

Using Blank Lines in Python Programs

A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.

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


Waiting for the User

The following line of the program displays the prompt, the statement saying Press the enter key to exit, and waits for the user to take action:

Example


           #!/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 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:

Example


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

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

Example


              if expression :
                suite
              elif expression :
                suite
              else :
                suite

Command Line Arguments in Python

Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h:

Example


              $ python3 -h
              usage: python3 [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 also program your script in such a way that it should accept various options. Command Line Arguments is an advanced topic and should be studied a bit later once you have gone through rest of the Python concepts.

Previous Next