Python programming Basics


Python is a dynamic and interpreted language. In source code, the data types, variables and even the parameters are not declared. Thus, due to this it makes python short code and flexible. While python checks all values at runtime. To see how the python code works, is to use of python interpreter. It is a fast way, which gives results immediately as we type in it. By working with interpreter, shows that python does not declare variable types and it raises exceptions at runtime. Python is also case-sensitive.

Python Interpreter

working with the python interpreter is an interactive fashion. Whatever we type in, i.e. the small python codes it gives the result immediately. This helps us to understand the python syntax and helps us in a lot ways during programming. It shows how to use the syntax properly and avoids exceptions. Actually, the python interpreter is the shell mode. Some examples of programming in the python interpreter :

Open a terminal and type python as follows:

amith@sonyvaio ~ $ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>a='hai'
>>>a+str(1)
'hai1'

The python interpreter raises exceptions in case of the variables, functions, modules etc which are not defined. so we have to define them before using.

>>> k
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined

After defining/initialising  them
>>> k=1
>>> k
1

Programming in Python interpreter

 Basic Programming

PRINTING :  Printing a string or value using ‘print’ command

>>> print 'hai'
hai              # string printed
>>> print 3
3                # value printed

INITIALIZATION :  Intializing a value or string to a variable and print

>>> a=10
>>> b='hai'
>>> b
'hai'   # double quotes are also used,i.e. "hai".
>>> a
10

BASIC FUNCTIONS

len(arguments) :  using len() function, we can find the length of  a string

>>> len('Hello world')
11
>>> a='hello'
>>> len(a)
5

str(arguments) :  we can convert a value into an string using str() function

>>> str(33)
'33'

input(statements ) :   function is used to read a value or a string from the users input. Here, the statements means, standard output statements for printing out.

>>> input()
'great'
'great'
>>> a=input()  # 'a' takes the value from input function
33
>>> a
33
>>>

STRING CONCATENATION :

>>> 'Hello'+'world'
'Helloworld'
>>> a='good'
>>> b='bye'
>>> a+b
'goodbye'

FUNCTIONS :

Defining a function by calling the syntax

  def function_name() :

for example, define a function to add two numbers

>>> def add(a,b):     # defining function name with two parameters
...       print a+b   # adds & prints the result
...

after defining the add function now call the function
>>> add(10,12)   # passing values to 'add' fuction
22
>>>

Use of ‘if -else’ syntax within a function

for example, a ‘operation function’ is defined for addition and subtraction

>>> def operation(a):
...        if a==1:
...          print 'Addition'
...          print 'Enter two numbers:'
...          b=input()
...          c=input()
...          print 'sum:',b+c
...        else:
...          print 'Subtraction'
...          print 'Enter two numbers:'
...          b=input()
...          c=input()
...          print 'subtraction:', b-c
...


>>> operation(1)  # for addition, value '1' is passed
Addition
Enter two numbers:
2
3
sum: 5
>>> operation(2)  # for subtraction '2' is passed
Subtraction
Enter two numbers:
6
3
subtraction: 3
>>>

Python Program

Usually the source code containing the program is written in a file with .py extension is the script file. Python files are created with any editor,  an paticular  example, say ‘ vim ‘.

amith@SONY-VAIO:~$ vim a.py

Python program follows little different syntax from other. It never uses curly brackets for encapsulating the function body or further, for loops. Instead uses spaces after the starting of next line from the if, while loops. Before starting to write the code, remember using of comment statements.

comment statements

comment statements are used to make the code readable and also make us understand what each function does, if we use comment lines at beginning of function definition. They begin with a ‘#’ and extend to the end of line.

Programming in Python files

Firstly, specific the path of the python in your system, at the beginning in the comment line, which you are using. Afterwards you can or not use, the comment lines for further specifying the rest of the program. call the main function and then define the main function

A simple program to print whatever we give along with the running command of the script. (command line arguments)

#!/usr/bin/python   # path of python within system


import sys          # here modules are imported, i.e. 'sys' module
def main():         # main function definition


 print 'a',sys.argv      # main fuction body


if __name__ == '__main__':   # standard boilerplate for calling functions
 main()                     # calling main function


Running the above program

Firstly, change the permission of the file, so that every user can execute the file.

amith@SONY-VAIO:~$ chmod -c 777 a.py
mode of `a.py' changed to 0777 (rwxrwxrwx)
amith@SONY-VAIO:~$ python a.py hello
a ['a.py', 'hello']
amith@SONY-VAIO:~$

Command line arguments

In Python programming, the command ‘sys.argv  contains the command line arguments i.e, the program itself being sys.argv[0], the first argument as sys.argv[1] and so on. For using ‘sys.argv’,  sys module has to be imported

For example, an program that prints the statement passed along while running it

import sys
print sys.argv

now running the file with above code, prints the every statement used along with running command.

amith@SONY-VAIO:~$ python c.py hello world  
['c.py', 'hello', 'world']
amith@SONY-VAIO:~$

Python Module

The source code written in an file is called script file. The python module deals with the  script file, i.e. the script file is considered as module. For code re-usability and shortening of code, python use file created earlier as an module in another python files. So instead of writing code for a particular function, we can refer the module corresponding  to that function. so every python file may be regarded as an module. In modules, while running the code, it checks from the top to bottom of the program. Since a python module can be imported into other programs. so the module is imported at firstly in the program. Now, after that checking for any function call. By seeing the boilerplate function for calling the any function, then checks for the corresponding defining of the called function.  while running the program directly,  ‘__name__’ is by default set to ‘__main__’. Hence therefore boilerplate functions are provided to call different functions below it.

Indentation

Most interesting feature of python is indentation, which affects its meaning. while beginning from the main function, the parent function to its children should have same indentation throughout. After the ‘if’ or ‘while’, thus instead of curl brackets, spaces are used here as indentation for beginning and ending of a function or loop. The same pattern should follow throughout, otherwise it is flagged as an error.

Functions

Functions are called before they are defined, i.e.  function-name(parameter1,parameter2,…..) with n parameters.

for example:

def main():
  print repeat('Yay', False)   # 'repeat' function is called

Now the definition of the function  is

def function-name(parameter1,parameter2,.....):

“”””    body””””””

we can use return syntax within the body, for returning any parameter back to the function call. The first line of a function can be a documentation string (“doc-string”) that describes what the function does. The doc-string can be a single line, or a multi-line description. Variables defined in the function are local to that function.

for example

# Defines a "repeat" function that takes 2 arguments.
def repeat(s, exclaim):
  """Returns the string s repeated 3 times.
  If exclaim is true, adds exclamation marks.
  """
  result = s + s + s
  if exclaim:
    result = result + '!!!'
  return result

Variables

In python, there are no specific type for variables in python. Thus by giving names to the variables it becomes easy to understand the code and avoiding less errors.

Importing Modules

As explained in python modules, that the modules can used in any program. It helps in code re-usability contributing to code optimisation. By importing a module into a program, we can use the functions of the module in the program. The modules are considered to be objects and the functions inside the modules are called its attributes or methods.

for example, if we want to use the exit function to exit from the program. ‘sys’ module contains the ‘exit’ function, thus we have to import the sys into the program before using the function. Now after importing, apply the methods or function ie exit

  import sys    # module imported


  sys.exit(0)   # using module function

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: