Python – Basic Syntax

basic syntax python
Python - Basic Syntax

Basic Syntax, The Python language has many similarities to Perl, C, and Java. However, there are a few precise variations among the languages.

First Python Program

Let us execute programs in different modes of programming.

Interactive Mode Programming

Invoking the interpreter without passing a script document as a parameter brings 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.
>>>

Type the following text at the Python prompt and press the Enter −

>>> print "Hello, Python!"

If you are going for walks new version of Python, then you definately might need to apply print declaration with parenthesis as in print (“Hello, Python!”);. However in Python model 2.4.Three, this produces the following end result −

Hello, Python!

Script Mode Programming

Invoking the interpreter with a script parameter starts execution of the script and maintains till the script is completed. When the script is finished, the interpreter is now not energetic.

Let us write a easy Python application in a script. Python files have extension .Py. Type the subsequent supply code in a take a look at.Py document −

print "Hello, Python!"

We assume which you have Python interpreter set in PATH variable. Now, try and run this application as follows −

$ python test.py

This produces the following result −

Hello, Python!

Let us strive every other way to execute a Python script. Here is the modified take a look at.Py record −

#!/usr/bin/python

print "Hello, Python!"

We anticipate which you have Python interpreter to be had in /usr/bin directory. Now, try to run this application as follows −

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

This produces the following result −

Hello, Python!

Python Identifiers

A Python identifier is a call used to perceive a variable, feature, 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 no longer permit punctuation characters along with @, $, and % inside identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two special identifiers in Python.

Here are naming conventions for Python identifiers −

  • Class names begin with an uppercase letter. All other identifiers start with a lowercase letter.
  • Starting an identifier with a unmarried leading underscore suggests that the identifier is non-public.
  • Starting an identifier with leading underscores indicates a strongly private identifier.
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined unique call.

Reserved Words

The following listing suggests the Python keywords. These are reserved phrases and also you cannot use them as constant or variable or some other identifier names. All the Python key phrases incorporate lowercase letters best.

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield

Basic Syntax, Lines and Indentation

Python gives no braces to indicate blocks of code for sophistication and characteristic definitions or waft manipulate. Blocks of code are denoted by line indentation, that’s rigidly enforced.

The wide variety of areas in the indentation is variable, however all statements inside the block should be indented the identical amount. For 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"

Basic Syntax, Thus, in Python all of the non-stop strains indented with equal variety of spaces could form a block. The following instance has numerous declaration blocks −

Note − Do no longer try and apprehend the logic at this factor of time. Just ensure you understood various blocks despite the fact that they may be 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 quit with a new line. Python does, however, permit using the line continuation character () to indicate that the road need to keep. For instance −

total = item_one + \
        item_two + \
        item_three

Statements contained inside the [], , or () brackets do no longer want to use the road continuation individual. For instance −

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

Basic Syntax, Quotation in Python

Python accepts unmarried (‘), double (“) and triple (”’ or “””) prices to indicate string literals, so long as the same sort of quote starts offevolved and ends the string.

The triple costs are used to span the string throughout multiple lines. For example, all the following are criminal −

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

Comments in Python

Basic Syntax, A hash signal (#) that isn’t inside a string literal starts a remark. All characters after the # and up to the quit of the bodily line are a part of the comment and the Python interpreter ignores them.

#!/usr/bin/python

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

This produces the following result −

Hello, Python!

You can type a touch upon the same line after a declaration 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 overlooked via Python interpreter and may be used as a multiline comments:

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

Using Blank Lines

A line containing handiest whitespace, in all likelihood with a comment, is known as a clean line and Python definitely ignores it.

In an interactive interpreter consultation, you ought to enter an empty physical line to terminate a multiline announcement.

Basic Syntax, Waiting for the User

Basic Syntax, The following line of this system shows the set off, the announcement announcing “Press the enter key to go out”, and waits for the consumer to take action −

#!/usr/bin/python

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

Here, “nn” is used to create new strains earlier than showing the actual line. Once the user presses the important thing, the program ends. This is a pleasing trick to hold a console window open till the user is performed with an application.

Basic Syntax, Multiple Statements on a Single Line

The semicolon ( ; ) allows a couple of statements on the unmarried line given that neither statement starts offevolved a brand new code block. Here is a sample snip the use of the semicolon −

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

Multiple Statement Groups as Suites

A organization of man or woman statements, which make a single code block are referred to as suites in Python. Compound or complicated statements, such as if, whilst, def, and class require a header line and a set.

Header traces start the declaration (with the keyword) and terminate with a colon ( : ) and are followed by means of one or greater lines which make up the suite. For instance −

if expression :
   suite
elif expression :
   suite
else :
   suite

Basic Syntax, Command Line Arguments

Basic Syntax, Many packages may be run to provide you with a few basic statistics about how they ought to be run. Python enables you to do that 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. ]

Basic Syntax, You also can program your script in any such manner that it need to receive numerous alternatives. Command Line Arguments is a sophisticated subject matter and should be studied a chunk later once you’ve got long past through rest of the Python standards.