A Quick Start Introduction to Python Programming - 1

Monday, September 8, 2008

Python is one of the popular, highly portable scripting languages, which infact is recommended by many hackers as the first programming language to start with. Though there are lots of valuable resources online for python programming, this one is a small contribution from my side. Being a python fan myself, I just can't resist the temptation to write my own beginner's guide.

Well, I am not going to write a comprehensive introduction to python programing here, all I am going to do is to quick start you to python programming using some 10 sample python scripts, which will get you to a good start, all these example scripts will covers basics of python from datatypes, functions/doc strings, OOPS, objects, exception handling, etc. Once you get a grasp of these code, you will get more comfortable with the language or appreciate how well python is designed that it should be a compelling skill for you to learn further, just ten scripts, nothing more.

Lets start here.


1. Data types in python, lists, dictionaries and tuples

Lists, dictionaries and tuples are the three most important datetypes in python, a python list is an array of objects ("Everything in python is an object" which I will come back to later), so the elements of the list can be an int, char, a class instance object, a list, tuple, a dictionary, etc. Lets look at a sample code followed by its explanation.

Listing 1: data_types.py


#
# Data types in python
# data_types.py
# Author: S.Prasanna
#

# Initialize a list, dictionary and a tuple
import traceback

list_datatype = []
dict_datatype = {}
tuple_datatype = ()

print "Printing python datatypes...."
print "Type of list_datatype =", type(list_datatype)
print "Type of dict_datatype =", type(dict_datatype)
print "Type of tupls_datatype =", type(tuple_datatype)

#List datatype
print "\nExample of python list...."
list_datatype = [1, "hello"]
print "List =" , list_datatype
list_datatype.append("new item")
print "List after appending new item =" , list_datatype
list_datatype.remove("new item")
print "List after removing new item =", list_datatype
print "List[1] =", list_datatype[1]
print "Length of List =", len(list_datatype)

print "Printing list contents using for loop...."
for item in list_datatype:
print item

#Dictionary datatype
print "\nExample of python dictionary...."
dict_datatype ["index1"] = "Element 1"
dict_datatype [1] = "Element 2"
print "Dict =", dict_datatype
print "Length of dictionary =" , len(dict_datatype)

print "Printing dictionary contents using for loop...."
for (key, value) in dict_datatype.items():
print "Key = ", key, " Value = " , value

#Tuple Datatype (Immutable list)
print "\nExample of python tuple...."
tuple_datatype = ("tuple1", "tuple2", ("tuple3", "tuple4"))
print "Tuple datatype =", tuple_datatype
print "Length of tuple =" , len(tuple_datatype)

print "Printing tuple contents using for loop...."
for item in tuple_datatype:
print item

try:
print "Modifying the element of the tuple, tuple_datatype[2]"
tuple_datatype[2] = ("tuple5", "tuple6")
except:
print "Exception in modifying tuple contents, tuples are immutable datatypes."
traceback.print_exc()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61


Explanation:

Lines 10 - 12: Initializes three data types, a list, a dictionary and a tuple to empty objects of the respective types, for example to initialize an empty list one should use list_datatype = [], for dictionaries its {}and for tuples, its ().
Lines 15 - 17: Prints the type of the three objects list, dictionary and the tuple, type is a built-in function in python to print the type pf any objects, for example type(10) will be an 'int' and type("10") will be a str or a string.

Lines 20 - 28: The list is initialized to some data elements, then an additional element is added using the append method on lists, and an item is removed using the remove method. The len function in python is used to find the length of any python objects, here its used to print the length (the number of elements in the list).

Lines 30 - 32: The items of the list are printed in a for loop, the syntax, for item in list_datatype: iterates through every element in the list and prints them, the for loop is applicable to other iteratable data types as well.

In short a list in python is similar to an array of python objects where one can add, remove elements at any index, and can iterate through the elements in the list as well.

Lines 34 - 43: Here we are initializing a dictionary (or associative arrays you would call it another language) with key value pairs, which can be any python object. The dict_datatype.items() returns a tuple of key value pairs, which is used in the for loop to print the dictionary items.

Lines 46 - 53: Here we are initializing a tuple, a tuple in python is a non mutable list, in other words, you cannnot add/ remove/ modify items in the tuple, they are similar to contants in C and one can be sure that they cannot be modified throught the code execution, trying to modify a tuple will result in an exception.

Line 55 - 60: Here we are trying to modify a tuple element, which will result in an exception, we will see exception handling in a different section, but for now don't dig too much into it, all you need to know is don't modify a tuple.

See the below output to see how lists, dictionaries and tuples work in python.

Sample Output:

IDLE 1.2.2 ==== No Subprocess ====
>>>
Printing python datatypes....
Type of list_datatype =
Type of dict_datatype =
Type of tupls_datatype =

Example of python list....
List = [1, 'hello']
List after appending new item = [1, 'hello', 'new item']
List after removing new item = [1, 'hello']
List[1] = hello
Length of List = 2
Printing list contents using for loop....
1
hello

Example of python dictionary....
Dict = {1: 'Element 2', 'index1': 'Element 1'}
Length of dictionary = 2
Printing dictionary contents using for loop....
Key = 1 Value = Element 2
Key = index1 Value = Element 1

Example of python tuple....
Tuple datatype = ('tuple1', 'tuple2', ('tuple3', 'tuple4'))
Length of tuple = 3
Printing tuple contents using for loop....
tuple1
tuple2
('tuple3', 'tuple4')
Modifying the element of the tuple, tuple_datatype[2]
Exception in modifying tuple contents, tuples are immutable datatypes.
Traceback (most recent call last):
File "C:\python\data_types.py", line 57, in
tuple_datatype[2] = ("tuple5", "tuple6")
TypeError: 'tuple' object does not support item assignment
>>>

Note: To execute this code, use python's default editor IDLE, which comes with the python package, press F5 to run the module.

2. Functions and doc strings

In this section, we will see functions and doc strings in python.



#
# Functions and doc strings in python
# functions_doc_strings.py
# Author: S.Prasanna
#

def div_num (a,b):
""" This function is used to divide two numbers
and return the results
"""
if b == 0:
return "Divide by zero operation."
else:
return a/b

if __name__ == "__main__":

print "Printing the doc string of an user defined function div_num"
print div_num.__doc__
print "20/10 =" , div_num(20,10)
print "20/0 =", div_num(20,0)

print "\nPrinting the doc string of a python module (module os)"
import os
print os.__doc__

print "\nPrinting the doc string of attribute os.write of os module"
print os.write.__doc__

print "\nPrinting the attributes of OS module"
print dir(os)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Explanation:

Lines 6 - 13:

Here we declare a function div_num (a function starts with a def keyword followed by the function name and parameters) which returns the division of two numbers (an integer) or a string when the dividend is zero. Python return types are dynamic as with other scripting languages, the return type may be any python object, in our case, a string when the dividend is zero or an integer otherwise.

Also one can see how to use if and else statements in python, all conditional statements (also for, while, etc) terminates with a : (colon), and the most important thing about coding in python is "Python uses indentation to separate blocks", which means all statements within a block or which belongs to a block are indented (see where the function statements start or where the statement after the if loop starts).

Lines 7 - 8 are called doc strings of a function where you can specify what the function does, the doc string starts with """ and ends with """ and may span multiple lines as well.

Lines 14 - 20:

Line 14 defines the start of main namespace (__name__ == "__main__" here), which is similar to main method of languages like java, here we invoke the div_num function which prints the division results based on the input parameters, also line 17 prints the doc string of the function div_num using div_num.__doc__ attribute.

Line 21 - 30: Here we import a python module os which has OS specific utility functions (similar to java we use import statement here also for importing standard packages) and print its summary using its __doc__ attribute (line 23), if you wnat to see what a module's function does, one can use the __doc__ attribute of that module's function (see what os.write function does with os.write.__doc__ attribute).

Line 29: Here we see all attributes of a module like the module's constants, functions, doc strings, etc, using the built in function dir in python.

Output:

IDLE 1.2.2 ==== No Subprocess ====
>>>
Printing the doc string of an user defined function div_num
This function is used to divide two numbers
and return the results
20/10 = 2
20/0 = Divide by zero operation.

Printing the doc string of a python module (module os)
OS routines for Mac, NT, or Posix depending on what system we're on.

This exports:
- all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
- os.path is one of the modules posixpath, ntpath, or macpath
- os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
- os.curdir is a string representing the current directory ('.' or ':')
- os.pardir is a string representing the parent directory ('..' or '::')
- os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
- os.extsep is the extension separator ('.' or '/')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms. Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).


Printing the doc string of attribute os.write of os module
write(fd, string) -> byteswritten

Write a string to a file descriptor.

Printing the attributes of OS module
['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'UserDict', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fstat', 'fsync', 'getcwd', 'getcwdu', 'getenv', 'getpid', 'isatty', 'linesep', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'sys', 'system', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'urandom', 'utime', 'waitpid', 'walk', 'write']

3. Executing UNIX commands

In this section, we will see a simple python script through which one can execute UNIX commands.

Listing 3: unix_commands.py


#
# Executing UNIX commands from python
# unix_commands.py
# Author: S.Prasanna
#

import commands

print "Executing date command in Unix...."
command_result = commands.getstatusoutput("date")
print "date command result =", command_result
print "Return status of date =", command_result[0] >> 8
print "Output of date =", command_result[1]

1
2
3
4
5
6
7
8
9
10
11
12
13
14

Explanation:

The above script imports a module named commands and executes the date command using the getstatusoutput method, which returns a tuple of command status code and command output. When you print something comma separated in python, it will append a space character for you by default (Note that I am right shifting the process exit code by 8 to get the process return code as both are a little different).

Output:

bash-3.00# python unix_commands.py
Executing date command in Unix....
date command result = (0, 'Sun Sep 7 23:31:30 PDT 2008')
Return status of date = 0
Output of date = Sun Sep 7 23:31:30 PDT 2008

Continued here. A Quick Start to Introduction to Python Programming - 2.


8 comments:

Anonymous said...

Dear Prasanna,
This is Swananda from Bangalore, i have gone through your blog. It is really informative. I have also done a project in GPS(embedded system). Also i would like to say that i am very much interested in socket programming. Hope your blog will help me.
I have written a simple socket program, but i am faciong with some silly problems.
It would be great if you please send me your e-mail ID. My e-mail id is swananda.laha@gmail.com

Wish to get a feedback from you.
Regards
Swananda

Prasanna Seshadri said...

Hi,

Good to see your interest in socket programming, my contact can be found here

http://www.pythonprasanna.com/#Contact

Let us see if I can be of any help to you in resolving your problem, but do go through the socket programming tutorial I have written, it may also be of help to you.

Swananda said...

Hi Prasanna,
Thanks for your reply, I will definitely go through your "socket programming tutorial", but right now i am trying to understand the python scripting.
I am sending the portion of the code with which i am facing a problem. My recv() function is returning a -ve value. I am not being able understand why. Other portion of the code is working fine. Moreover it would be great if you could please tell me how to invoke winsock2. Here goes the code:

#include "stdafx.h"
#include "stdio.h"
#include "windows.h"
#include "winsock2.h"
//#include "winsock.h"
#include "stdlib.h"
#include "string.h"
#include "conio.h"
#include "malloc.h"

#define NETWORK_ERROR -1;
#define NETWORK_OK 0;

//int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
int main(void)
{

int nret=0;
static char ipaddr[16];
char buf[1000]="",buf1[100]="",buf2[100]="",buf3[100]="",buf4[100]="",buf5[100]="",buf6[100]="";

WSADATA ws;
//WSAStartup(MAKEWORD(2,0),&ws);
WSAStartup(0x0101,&ws);
//buf[1000]="";
sprintf(buf1,"\nWinsock Version Requested: %d.%d",LOBYTE(ws.wVersion),HIBYTE(ws.wVersion));
sprintf(buf2,"\nWinsock Version Available: %d.%d",HIBYTE(ws.wHighVersion),LOBYTE(ws.wHighVersion));
sprintf(buf3,"\nCurrent Winsock Implementation: %s",&ws.szDescription);
sprintf(buf4,"\nSystem Status: %s",&ws.szSystemStatus);
sprintf(buf5,"\nMaximum Sockets: %lu",ws.iMaxSockets);
sprintf(buf6,"\nMaximum Message size: %lu",ws.iMaxUdpDg);
strcat(strcat(strcat(strcat(strcat(strcat(buf,buf1),buf2),buf3),buf4),buf5),buf6);
//MessageBox(NULL,buf,"Information",0);
printf("%s",buf);

SOCKET commsock;
commsock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(commsock==INVALID_SOCKET)
{
printf("\n\nSOCKET ERROR %d!Cannot Create Socket.",WSAGetLastError());
}
else
{
printf("\n\nSocket Created !");
}
printf("\n\nEnter the IP to connect to: ");
//scanf("%s",ipaddr);
gets(ipaddr);

SOCKADDR_IN sa;
sa.sin_family=AF_INET;
sa.sin_addr.S_un.S_addr=inet_addr(ipaddr);
sa.sin_port=htons(43);

nret=connect(commsock,(SOCKADDR*)&sa,sizeof(sa));
printf("\nConnecting.......");
if(nret==SOCKET_ERROR)
{
printf("\n\nSOCKET ERROR: %d! Cannot connect to IP: %s",WSAGetLastError(),ipaddr);
closesocket(commsock);
}
else
{
printf("\n\nConnection Succeeded to IP: %s",ipaddr);
}

static char sendbuffer[20];
static char recvbuffer[3000];
char *p;

printf("\n\nEnter the site to connect to: ");
scanf("%s",sendbuffer);
printf("\nLength of String %d",strlen(sendbuffer));

nret=send(commsock,sendbuffer,strlen(sendbuffer),0);
if(nret==SOCKET_ERROR)
{
printf("\n\nSOCKET ERROR: %d ",WSAGetLastError());
WSACleanup();
return NETWORK_ERROR;
}

nret=recv(commsock,recvbuffer,strlen(recvbuffer),0);
if(nret!=SOCKET_ERROR)
{
printf("\n\nInformation Received for the Site:\n%s ",recvbuffer);
return NETWORK_OK;
WSACleanup();
}
else
{
printf("\n\nSOCKET ERROR %d: Requested Information cannot be retrieved.",WSAGetLastError());
}

closesocket(commsock);
getch();

}

Prasanna Seshadri said...

Hi,

From what I see the code looks fine, but I need to see the server part of the socket code, do mail me that part, its possible that there is no data to receive, from this code one can't debug much unless you brief me about what exactly you are trying to do, where you are trying to connect, the server side code, remember to mail me that would be better for me to see.

Swananda said...

Hi Prasanna,
Thanks for your reply.
There is no server part of the code, as i am requesting the Whois server to get the details about a particular website.
Ping the following:
C:\>ping whois.networksolutions.com
and you will get the ip as 205.178.188.12

Swananda

Prasanna Seshadri said...

I think there is a problem with your send command, nret=send(commsock,sendbuffer,strlen(sendbuffer),0);

You are not giving the proper query string I suspect, thats why you didn't get the exact response.

Swananda said...

Hi Prasanna,
Thanks again, for the reply.
Actually sometimes i received the message from the server but not the entire one, some portions of it was missing. Leter on i didn't received any message.
It would be great if you try once.

Swananda

Prasanna Seshadri said...

hen probably you need to invoke recv call till the entire length of the message is received, try to do it in a loop.


Copyright © 2016 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.