Python Basic Syntax





You can use Python in many different ways due to its flexibility and dynamic nature. When you want to test a code or a statement on a line-by-line basis or explore its features, you can use it interactively.
If you want to interpret an entire file of statements or an application program, you can use it in script mode.
Either the Command Line window or IDLE Development Environment can be used to interact with Python.

First Python Program

Let us execute programs in different modes of programming.

Interactive Mode Programming (Command Line Interaction)

The command line is the easiest way to work with Python. Python responds to every completed command entered on the >>> prompt, making it easy to visualize how it works.
Python may not be the best way to interact with it, but it is the easiest.

Starting Python

Depending on your operating system, you can access Python's command line in different ways:

  • On Windows, you can start the Python command line by clicking on its icon or menu item in the Start menu.

  • Click on the Python command line in the folder containing the shortcut or the installed files.

  • Using GNU/Linux, UNIX, or Mac OS systems, you need to run the Terminal Tool and enter the Python command.


To tell the computer what to do, we use commands. In order to get Python to do something for you, you have to enter commands that it is familiar with. Python will then translate these commands into instructions that your computer or device can understand.
Understands and executes.
When the interpreter is invoked without a script file as a parameter, it displays the following 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.
>>>

The print command can be used to print the universal program “Hello, World! ”
Type the following text at the Python prompt and press the Enter −

>>> print "Hello, World!"

If you are running new version of Python, then you would need to use print statement with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result −

Hello, World!


Exiting Python

To exit from Python, you can type any of these commands:
quit()
exit()
Control-Z then press enter

Script Mode Programming

As you work in script mode, you won't see results automatically as you would in interactive mode. A script's output can be viewed by running it or invoking the print() function within your code.
The script is executed when the interpreter is invoked with a script parameter. After the script has finished, the interpreter is no longer active.

We will write a simple Python program in a script. Files in Python have the extension .py. Create a test.py file and type the following code.

print "Hello, Python!"

We assume that Python interpreter is set in PATH variable. Try running this program as follows:

$ python test.py

This produces the following result −

Hello, Python!

Let us try another way to execute a Python script. Here is the modified test.py file −

#!/usr/bin/python

print "Hello, Python!"

We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −

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

This produces the following result −

Hello, Python!

 

Python syntax describes how humans and the system should write and interpret Python programs. Syntax is important if you want to write and run your program in Python.

Python Identifiers

In Python, an identifier is the name given to a function, class, variable, module, or other object. As part of your Python program, every entity you use should be appropriately named or identified.

An identifier begins 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).

In Python, punctuation characters like @, $, and % are not allowed in identifiers. The Python programming language is case-sensitive. In Python, manpower and manpower are different identifiers.

The following are Python identifier naming conventions

  • Identifiers can consist of uppercase letters, lowercase letters, underscores, and digits (0-9). Therefore, myClass, my_variable, var_1, and print_hello_world are valid identifiers.

  • Within identifiers, special characters such as %, @, and $ are not allowed.

  • Numbers should not be used as identifiers. 2variable is invalid, but variable2 is valid.

  • In Python, identifiers are case-sensitive. Python distinguishes between Labor and labor.

  • Python keywords cannot be used as identifiers.

  • The class identifiers begin with an uppercase letter, but the rest begin with a lowercase letter.

  • In your identifier, you can use underscores to separate multiple words.

It is important to choose identifiers that will still make sense to you after a long period of time. Therefore, while it is easy to set c = 2, it may be more useful for future reference if you use a longer but more relevant variable name, such as count = 2.

Reserved Words

The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

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

Lines and Indentation

Unlike Java, C, and C++, Python programs are structured through indentation rather than braces. Python defines blocks of code by indentation not as a matter of style or preference but as a rigid language rule
requirement. Python codes are more readable and understandable because of this principle.

When looking at a Python program, you can easily identify blocks of code because they start at the same distance to the right. You can simply indent another block further to the right if it needs to be nestled more deeply.

The indent space within a block must be consistent. Python automatically indents your code when you enter a statement that requires indentation when using IDLE or other IDEs. Indentation, by
convention, is equivalent to 4 spaces to the right.

For class and function definitions and flow control, Python does not provide braces. Code blocks are denoted by line indentation, which is strictly enforced.

Indentation is variable, but all statements within the block must be indented equally. As an example,

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

However, the following block generates an error −

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

Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks −

Note − Do not try to understand the logic at this point of time. Just make sure you understood 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

Statements

Python interpreters can execute statements. Assigning a value to a variable, such as my_variable = "dog", is an assignment statement. Assignment statements can also be as short as c = 3. Python also has other types of statements, such as if statements, while statements, and for statements.

Multi-Line Statements

There may be several lines in a statement. If you want to break a long statement over multiple lines, you can use parentheses, brackets, and braces. Multi-line expressions should be handled in this way. You can also wrap multiple lines by using a backslash (/) at the end of each line.

Python statements usually end with a new line. However, Python allows the use of the line continuation character (/) to indicate that a line should continue. As an 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 −

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

Quotation in Python

String literals can be indicated with quotation marks in Python. Whether you use single, double, or triple quotes, you must start and end with the same type. When your string spans multiple lines, you would use triple quotes.

The Python language accepts single ('), double ("), and triple (''' or """) quotes to denote string literals.

To span a string across multiple lines, triple quotes are used. All of the following are legal, for example

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

Comments in Python

In your code, you'll find it useful to add notes that describe what your program does. A comment is very useful when you need to review or revisit your program. In addition, it will be helpful to another programmer who might have to go over the source code.
Using the hash (#) symbol, you can add comments to your program. The hash symbol instructs the Python interpreter to ignore the comment.

The hash symbol can be used at the beginning of each line of multi-line comments. Triple quotes can also be used to wrap multi-line comments.

A hash sign (#) outside of a string literal indicates a comment. The Python interpreter ignores all characters after the # and up until the end of the physical line.

#!/usr/bin/python

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

This produces the following result −

Hello, Python!

You can type a comment on the same line after a statement or 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.

Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments:

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

Using Blank Lines

Lines containing only whitespace, possibly with a comment, are known as blank lines, and Python ignores them completely.

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

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 −

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

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

Multiple Statement Groups as Suites

Python suites are groups of statements that make up a single code block. There is a header line and a suite required for compound or complex statements, such as if, while, def, and class.

The header line begins with a keyword and ends with a colon (:), followed by one or more lines that make up the suite. As an example,

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

Command Line Arguments

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 −

$ python -h
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 also program your script so that it accepts a variety of options. After you have studied the rest of the Python concepts, you should study Command Line Arguments.



Frequently Asked Questions

+
Ans: Python Environment Setup - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python 3 Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Overview - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Tutorial for Beginners - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Basic Syntax - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Variable Types - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Basic Operators - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Decision Making - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Loops - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Numbers - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Strings - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Lists - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Tuples - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Dictionary - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Date and Time - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Functions - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Modules - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Files I/O - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Exceptions Handling - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..




Rating - NAN/5
453 views

Advertisements