SOME COMMONLY USED OPERATIONS IN PYTHON - Complete Guide For Python Programming (2015)

Complete Guide For Python Programming (2015)

SOME COMMONLY USED OPERATIONS IN PYTHON

Using Blank Lines:

A line containing only whitespace, possibly with a comment, is called a blank line and Python ignores it completely. 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, Press the enter key to exit and waits for the user to press the Enter key:

#!/usr/bin/python raw_input("\n\nPress the enter key to exit.")

Here, "\n\n" 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; a = 'abc'; sys.stdout.write(a + '\n')

Multiple Statement Groups as Suites:

In Python, a group of statements, which make a single code block are called suites. 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 and terminates 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

Accessing Command-Line Arguments:

Python provides a getopt module that helps you parse command-line options and arguments.

$ python test.py arg1 arg2 arg3

The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purpose:

• sys.argv is the list of command-line arguments.

• len(sys.argv) is the number of command-line arguments.

Parsing Command-Line Arguments:

Python provides a getopt module that helps you parse command-line options and arguments. This module provides two functions and an exception to enable command-line argument parsing.

getopt.getopt method:

This method parses command-line options and parameter list. Following is simple syntax for this method:

getopt.getopt(args, options[, long_options])

Here is the detail of the parameters:

• args: This is the argument list to be parsed.

• options: This is the string of option letters that the script wants to recognize, with options that require an argument should be followed by a colon (:).

• long_options: This is optional parameter and if specified, must be a list of strings with the names of the long options, which should be supported. Long options, which require an argument should be followed by an equal sign ('='). To accept only long options, options should be an empty string.