Python Basic Syntax





Python is a flexible and dynamic language that you can use in different ways. You can use it interactively when you simply want to test a code or a statement on a line-by-line basis or when you’re exploring its features.
You can use it in script mode when you want to interpret an entire file of statements or application program.
To use Python interactively, you can use either the Command Line window or the IDLE Development Environment.

First Python Program

Let us execute programs in different modes of programming.

Interactive Mode Programming (Command Line Interaction)

The command line is the most straightforward way to work with Python. You can easily visualize how Python works as it responds to every completed command entered on the >>> prompt.
It may not be the most preferred interaction with Python, but it is the simplest way to explore how Python works.

Starting Python

There are different ways to access Python’s command line depending on the operating system installed on your machine:

  • If you’re using Windows, you can start the Python command line by clicking on its icon or menu item on the Start menu.
  • You may also go to the folder containing the shortcut or the installed files and click on the Python command line.
  • If you’re using GNU/Linux, UNIX, and Mac OS systems, you have to run the Terminal Tool and enter the Python command to start your session.


We use commands to tell the computer what to do. When you want Python to do something for you, you have to instruct it by entering commands that it is familiar with.Python will then translate these commands to instructions that your computer or device
can understand and execute.
Invoking the interpreter without passing a script file 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.
>>>

To see how Python works, you can use the print command 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

When working in script mode, you won’t automatically see results the way you would in interactive mood. To see an output from a script, you’ll have to run the script and/or invoke the print() function within your code.
Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.

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

print "Hello, Python!"

We assume that you have 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 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 refers to the set of rules that defines how human users and the system should write and interpret a Python program. If you want to write and run your program in Python, you must familiarize yourself with its syntax.

Python Identifiers

A Python Identifier is a name given to a function, class, variable, module, or other objects that you’ll be using in your Python program. Any entity you’ll be using in Python should be appropriately named or identified as they will form part of your program.

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 −

  • An identifier can be a combination of uppercase letters, lowercase letters, underscores, and digits (0-9). Hence, the following are valid identifiers: myClass, my_variable, var_1, and print_hello_world.
  • Special characters such as %, @, and $ are not allowed within identifiers.
  • An identifier should not begin with a number. Hence, 2variable is not valid, but variable2 is acceptable.
  • Python is a case-sensitive language and this behavior extends to identifiers. Thus, Labor and labor are two distinct identifiers in Python.
  • You cannot use Python keywords as identifiers.
  • Class identifiers begin with an uppercase letter, but the rest of the identifiers begin in lowercase.
  • You can use underscores to separate multiple words in your identifier.

You should always choose identifiers that will make sense to you even after a long gap. Hence, while it is easy to set your variable to c = 2, you might find it more helpful 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

While most programming languages such as Java, C, and C++ use braces to denote blocks of code, Python programs are structured through indentation. In Python, blocks of codes re defined by indentation not as a matter of style or preference but as a rigid language
requirement. This principle makes Python codes more readable and understandable.

A block of code can be easily identified when you look at a Python program as they start on the same distance to the right. If it has to be more deeply nestled, you can simply indent another block further to the right.

You have to make sure that the indent space is consistent within a block. When you use IDLE and other IDEs to input your codes, Python intuitively provides indentation on the subsequent line when you enter a statement that requires indentation. Indentation, by
convention, is equivalent to 4 spaces to the right.

Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same 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"

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

Statements are instructions that a Python interpreter can execute. When you assign a value to a variable, say my_variable = “dog”, you’re making an assignment statement. An assignment statement may also be as short as c = 3. There are other kinds of statements in
Python, like if statements, while statements, for statements, etc.

Multi-Line Statements

A statement may span over several lines. To break a long statement over multiple lines, you can wrap the expression inside parentheses, braces, and brackets. This is the preferred style for handling multi-line expressions. Another way to wrap multiple lines is by using a
backslash (\) at the end of every line to indicate line continuation.

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 −

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 allows the use of quotation marks to indicate string literals. You can use single, double, or triple quotes but you must start and end the string with the same type. You would use the triple quotes when your string runs across several lines.

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 −

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

Comments in Python

When writing a program, you’ll find it helpful to put some notes within your code to describe what it does. A comment is very handy when you have to review or revisit your program. It will also help another programmer who might need to go over the source code.
You can write comments within your program by starting the line with a hash (#) symbol. A hash symbol tells the Python interpreter to ignore the comment when running your code.

For multi-line comments, you can use a hash symbol at the beginning of each line. Alternatively, you can also wrap multi-line comment with triple quotes.

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are 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 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

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 −

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

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 −

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



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
496 views

Advertisements