Python Basic Syntax


Contents

The Python language has numerous acquaintances to Perl, C, and Java. Still, there are decisive deviations found between the languages.

First Python Program

Let us run the programs in assorted modes of programming.

Interactive Mode Programming

Raising the interpreter with no passing a script file as a constant carries up 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.
>>>

Kind of following text at the Python prompt and press the Enter −

>>> print "Hello, Python!"

If you are executing latest version of Python, then users would demand to utilize the print statement with aside as in print ("Hello, Python!");. However in Python version 2.4.3, this supplies the following result −

Hello, Python!

Script Mode Programming

Evoking the analyst with a script constraint begins execution of the script and persists until the script is completed. When the script language coding is accomplished, user could find that the interpreter goes on inactive mode.

Let us write a simplex Python program in a script. Python files have extension .py. Type the following source code in a test.py file −

print "Hello, Python!"

We expect that you possess Python interpreter set in PATH variable. Now, try to run 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 expect that you have Python interpreter accessible in /usr/bin directory. Now, try to execute this program as follows:

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

This syntax the following result −

Hello, Python!

Python Identifiers

A Python symbol is a name utilized to identify a changeable, function, class, ability or other object. An identifier commences 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 executions do not authorize punctuation characters such as @, $, and % within identifiers. Python is one of the only a case delicate open source programming language. Thus, in the respective programming language, programmers could find various identifiers; especially, two most known ‘manpower’ and ‘manpower’ in Python.

Here are naming conventions for Python identifiers -

  • Class names beginning with an uppercase letter. Entire other identifiers begin with a lowercase letter.
  • Commencing from an identifier with an individual primary underscore points out that the identifier is private.
  • Beginning an identifier with two starting underscores bespeaks a strongly private identifier.
  • If the symbol also ends with two tracking underscores, the identifier is a language-defined special name.

Reserved Words

The below-mentioned chart displays the Python keywords. These keys are substituted words and users cannot utilize them as constant or changeable or any other identifier names. Every Python keywords incorporate 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

Python delivers no braces to bespeak blocks of code for class and process definitions or flow control. Blocks of code are designated by line indentation, which is stiffly enforced.

The number of spaces in the indenture is variable, but all statements within the block must be ordered the same amount. For example −

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

But, the following block generates an error −

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

Thus, in Python, each continuous lines formatted with same number of spaces will form a block. The following illustration has individual statement blocks -

Note − Do not try to realize the logic at this point of time. Just ensure you appreciated various blocks even if they are with no 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

Content in Python typically end with a brand-new line. Python systems do, yet, authorizes the use of the line continuation character (\) to designate that the line should continue.

For 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

Python evaluates single ('), double (") and triple (''' or """) quotes to designate string literals, as long as the same type of quote begins and ends the string.

The triple quotes are utilized to pair the string across multiple lines. For instance, entire the following are legal −

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

Comments in Python

A hash sign (#) that is not internal a string literal starts a comment. Entire characters after the # and up to the end of the material line are portion of the comment and the Python interpreter can ignore it.

#!/usr/bin/python

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

This supplies the following result −

Hello, Python!

You can type a comment on the stated line after a statement or reflection −

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 as a multiline comments:

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

Using Blank Lines

A line comprising only whitespace, perhaps with a comment, is best-known as a blank line and Python completely ignores it.

In an interactive translator session, you must get into an empty physical line to end a multiline statement.

Waiting for the User

The following line of the program shows the prompt, the statement saying “Press the enter key to exit”, and delays for the user to take action −

#!/usr/bin/python

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

Here, "\n\n" is utilized to make two new lines before showing the actual line. Once the user presses the key, the program ends. This is a quite a simple trick to keep a console table window open until the users have done with an application.

Multiple Statements on a Single Line

The semicolon ( ; ) authorizes multiple statements on the individual line offered that neither statement is a new code block. Here is a example snipping utilizing the semicolon −

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

Multiple Statement Groups as Suites

Groups of individual statements, which brand a single code block, are called suites in Python.

Compound or complex statements, such as if, while, def, and class necessitate a header line and a suite.

Header lines starts the statement (with the keyword) and ending with a colon ( : ) and are moved by one or more lines which made up the suite. For example −

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

Command Line Arguments

Numerous programs could run to offer you with any basic information about how they should be run. Python alters 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 in such a manner that it should evaluate assorted options. Command Line Arguments is an beforehand topic and should be studied a bit later once you have away through rest of the Python ideas.

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.



Navigation
Tutorial
Tutorial
Tutorial