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.
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.
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.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined
After defining/initialising them
Programming in Python interpreter
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
'hai' # double quotes are also used,i.e. "hai".
len(arguments) : using len() function, we can find the length of a string
>>> len('Hello world')
str(arguments) : we can convert a value into an string using str() function
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.
>>> a=input() # 'a' takes the value from input function
STRING CONCATENATION :
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
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:'
... print 'sum:',b+c
... print 'Subtraction'
... print 'Enter two numbers:'
... print 'subtraction:', b-c
>>> operation(1) # for addition, value '1' is passed
Enter two numbers:
>>> operation(2) # for subtraction '2' is passed
Enter two numbers:
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 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']
Command line arguments
In Python programming, the command ‘sys.argv contains the command line arguments i.e, the program itself being sys.argv, the first argument as sys.argv 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
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']
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.
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 are called before they are defined, i.e. function-name(parameter1,parameter2,…..) with n parameters.
print repeat('Yay', False) # 'repeat' function is called
Now the definition of the function is
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.
# 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
result = result + '!!!'
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.
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