Auto AdSense

Tuesday, 17 November 2015

Let the image float to the left/right of a paragraph - HTML Programs

<html>
<body>

<p>
<img src="smiley.gif" alt="Smiley face" style="float:left" width="32" height="32"> A paragraph with an image. The image will float to the left of this text.
</p>

<p>
<img src="smiley.gif" alt="Smiley face" style="float:right" width="32" height="32"> A paragraph with an image. The image will float to the right of this text.
</p>

<p><b>Note:</b> Here we have used the CSS "float" property to align the image; as the align attribute is deprecated in HTML 4, and is not supported in HTML5.</p>

</body>
</html>

Output


Smiley face A paragraph with an image. The image will float to the left of this text.
Smiley face A paragraph with an image. The image will float to the right of this text.
Note: Here we have used the CSS "float" property to align the image; as the align attribute is deprecated in HTML 4, and is not supported in HTML5.

Note: Due to inclusion of code to blogpost, images not able to display. But the code will work properly

Aligning images - HTML Programs

<html>
<body>

<h4>Image with default alignment (align="bottom"):</h4>
<p>This is some text. <img src="smiley.gif" alt="Smiley face" width="32" height="32"> This is some text.</p>

<h4>Image with align="middle":</h4>
<p>This is some text. <img src="smiley.gif" alt="Smiley face" align="middle" width="32" height="32"> This is some text.</p>

<h4>Image with align="top":</h4>
<p>This is some text. <img src="smiley.gif" alt="Smiley face" align="top" width="32" height="32"> This is some text.</p>

<p><b>Note:</b> The align attribute is deprecated in HTML 4, and is not supported in HTML5. Use CSS instead.</p>

</body>
</html>

Output



Image with default alignment (align="bottom"):

This is some text. Smiley face This is some text.

Image with align="middle":

This is some text. Smiley face This is some text.

Image with align="top":

This is some text. Smiley face This is some text.
Note: The align attribute is deprecated in HTML 4, and is not supported in HTML5. Use CSS instead.

Note: Due to inclusion of code to blogpost, images not able to display. But the code will work properly

Insert images - HTML Programs

<html>
<body>
<p>
An image:
<img src="html/home.png" alt="home" width="32" height="32"></p>

<p>
A moving image:
<img src="smiley.gif" alt="you are the best" width="48" height="48"></p>

<p>
Note that the syntax of inserting a moving image is no different from a non-moving image.
</p>

</body>
</html>

Output


An image: home
A moving image: you are the best
Note that the syntax of inserting a moving image is no different from a non-moving image.

Note: Due to inclusion of code to blogpost, images not able to display. But the code will work properly

Wednesday, 3 June 2015

Insert horizontal lines - HTML Programs

<html>
<body>
<p>The hr tag defines a horizontal rule:</p>
<hr><p>This is a paragraph</p>
<hr><p>This is a paragraph</p>
<hr><p>This is a paragraph</p>
</body>
</html>

Output


The hr tag defines a horizontal rule:

This is a paragraph

This is a paragraph

This is a paragraph

How to mark deleted and inserted text - HTML Programs

<html>
<body>

<p>My favorite color is <del>blue</del> <ins>red</ins>!</p>

<p>Notice that browsers will strikethrough deleted text and underline inserted text.</p>

</body>
</html>

Output

My favorite color is blue red!
Notice that browsers will strikethrough deleted text and underline inserted text.

Text direction - HTML Programs

<html>
<body>
<p>
If your browser supports bi-directional override (bdo), the next line will be written from the right to the left (rtl):
</p>

<bdo dir="rtl">
Here is some Hebrew text
</bdo>
</body>
</html>

Output



If your browser supports bi-directional override (bdo), the next line will be written from the right to the left (rtl):
Here is some Hebrew text

Tuesday, 26 May 2015

Abbreviations and acronyms - HTML Programs

<html>
<body>

<p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p>
<p>Can I get this <abbr title="as soon as possible">ASAP</abbr>?</p>

<p>The title attribute is used to show the spelled-out version when holding the mouse pointer over the acronym or abbreviation.</p>
</body>
</html>

Output



The WHO was founded in 1948.
Can I get this ASAP?
The title attribute is used to show the spelled-out version when holding the mouse pointer over the acronym or abbreviation.

Insert contact information - HTML Programs

<html>
<body>

<address>
Written by W3Schools.com<br>
<a href="mailto:us@example.org">Email us</a><br>
Address: Box 564, Disneyland<br>
Phone: +12 34 56 78
</address>

</body>
</html>

Output


Written by W3Schools.com
Email us
Address: Box 564, Disneyland
Phone: +12 34 56 78

Different computer-output tags - HTML Programs

<html>
<body>

<code>Computer code</code>
<br>
<kbd>Keyboard input</kbd>
<br>
<samp>Sample text</samp>
<br>
<var>Computer variable</var>
<br>

<p><b>Note:</b> These tags are often used to display computer/programming code.</p>

</body>
</html>

Output



Computer code
Keyboard input
Sample text
Computer variable
Note: These tags are often used to display computer/programming code.

Preformatted text (how to control line breaks and spaces) - HTML Programs

<html>
<body>

<pre>
This is
preformatted text.
It preserves      both spaces
and line breaks.
</pre>
The pre tag is good for displaying computer code:<br />


<pre>
for i = 1 to 10
     print i
next i
</pre>
</body>
</html>

Output


This is
preformatted text.
It preserves      both spaces
and line breaks.
The pre tag is good for displaying computer code:
for i = 1 to 10
     print i
next i

Text formatting - HTML Programs

<html>
<body>
<p><b>This text is bold</b></p>
<p><strong>This text is strong</strong></p>
<p><em>This text is emphasized</em></p>
<p><i>This text is italic</i></p>
<p><small>This text is small</small></p>
<p>This is<sub> subscript</sub> and <sup>superscript</sup></p>

</body>
</html>

Output

This text is bold
This text is strong
This text is emphasized
This text is italic
This text is small
This is subscript and superscript

Draw a border around form-data - HTML programs

<html>
<body>

<form action="">
<fieldset>
<legend>Personal information:</legend>
Name: <input type="text" size="30"><br>
E-mail: <input type="text" size="30"><br>
Date of birth: <input type="text" size="10">
</fieldset>
</form>

</body>
</html>

Output



Personal information: Name:
E-mail:
Date of birth:

Create a button - HTML Programs

<html>
<body>

<form action="">
<input type="button" value="Hello world!">
</form>

</body>
</html>

Output

Text area (a multi-line text input field) - HTML Programs

<html>
<body>

<textarea rows="10" cols="30">
The cat was playing in the garden.
</textarea>

</body>
</html>

Output

Sunday, 3 May 2015

Drop-down list with a pre-selected value - HTML Programs

<html>
<body>

<form action="">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected>Fiat</option>
<option value="audi">Audi</option>
</select>
</form>

</body>
</html>

Output





Simple drop-down list - HTML Programs

<html>
<body>

<form action="">

<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</form>

</body>

</html>

Output







Radio buttons - HTML Programs

<html>
<body>
<form action="">
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>

<p><b>Note:</b> When a user clicks on a radio-button, it becomes checked, and all other radio-buttons with equal name become unchecked.</p>


</body>

</html>

Output


Male
Female
Note: When a user clicks on a radio-button, it becomes checked, and all other radio-buttons with equal name become unchecked.

Checkboxes - HTML Programs

<html>
<body>
<form action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>

</body>

</html>

Output


I have a bike
I have a car

Create password field - HTML Programs

<html>
<body>
<form action="">
Username: <input type="text" name="user"><br>
Password: <input type="password" name="password">
</form>

<p><b>Note:</b> The characters in a password field are masked (shown as asterisks or circles).</p>


</body>

</html>

Output


Username:
Password:
Note: The characters in a password field are masked (shown as asterisks or circles).

Create text fields - HTML Programs

<html>
<body>

<form action="">

First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>

<p><b>Note:</b> The form itself is not visible. Also note that the default width of a text field is 20 characters.</p>


</body>

</html>

Output


First name:
Last name:
Note: The form itself is not visible. Also note that the default width of a text field is 20 characters.

HTML Images - HTML Programs

<html>
<body>

<img src="home.png" width="104" height="142">
</body>
</html>

Output


Note: Due to inclusion of code to appx file, images not able to display. But the code will work properly

HTML links - HTML Programs

<html>
<body>

<a href="https://www.youtube.com/user/Myedutainmentplace">
This is a link</a>

</body>
</html>

Output

This is a link

HTML paragraphs - HTML Programs

<html>
<body>

<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>

</body>
</html>

Output

This is a paragraph.
This is a paragraph.
This is a paragraph.

HTML headings - HTML Programs

<html>
<body>

<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>

</body>
</html>

Output

This is heading 1

This is heading 2

This is heading 3

This is heading 4

This is heading 5
This is heading 6

A very simple HTML document - HTML Programs

<html>
<body>

<h3>My First Heading</h3>


<p>My first paragraph.</p>


</body>

</html>

Output:

My First Heading

My first paragraph.

Monday, 27 April 2015

C Program to find Lucky Number

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
long int sumf(long int x)
{
    long int s;
    for(s=0;x>0;s+=x%10,x/=10);
    return s;
}
void main()
{
    long int sum=0;
    int a[26],i,k;
    char s[99];
    l1:
    printf("\n Enter your name without spaces:");
gets(s);
for(i=0;i<strlen(s);i++)
{
if(s[i]>=65&&s[i]<=90)
a[i]=s[i]+32;
else
a[i]=s[i];
}
  for(i=0;i<strlen(s);i++)
  {
  if(a[i]<97||a[i]>122)
  {
  printf("\n Invalid Character Please Try again");
  goto l1;
}
}
    for(i=0;s[i]!='\0';i++)
        sum=sum+a[i];
    while(sum>=10)
        sum=sumf(sum);
    k=sum;
    printf("\n\n\n\t Your lucky number\n\t according to the name is : %ld ",sum);
    printf("\n\n Enter your date of birth : ");
    scanf("%ld",&sum);
    while(sum>=10)
        sum=sumf(sum);
    printf("\n\n\t Your lucky number\n\t according to the date of birth is : %ld ",sum);
    if(k==sum)
        printf("\n\n\t You are the Luckiest Person");
}

Saturday, 4 April 2015

Tower of Hanoi Solutions upto 10 disks

        The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower, and sometimes pluralized) is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.



The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  • No disk may be placed on top of a smaller disk.

With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks.

Saturday, 24 January 2015

Python Programs - Sending Email using SMTP



  • Sending Email
    Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending e-mail and routing e-mail between mail servers.
    Python provides smtplib module which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
    Syntax:
    import smtplib

    smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

    Here is the detail of the parameters:
    1. host: This is the host running your SMTP server. You can specifiy IP address of the host or a domain name. This is optional argument.
    2. port: If you are providing host argument then you need to specifiy a port where SMTP server is listening. Usually this port would be 25.
    3. local_hostname: If your SMTP server is running on your local machine then you can specify just localhost as of this option.
    An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message.
    It takes three parameters:
    1. The sender - A string with the address of the sender.
    2. The receivers - A list of strings, one for each recipient.
    3. The message - A message as a string formatted as specified in the various RFCs.
  • Example
    #!/usr/bin/python

    import smtplib

    sender = 'from@fromdomain.com'
    receivers = ['to@todomain.com']

    message = """From: From Person < from@fromdomain.com >
    To: To Person < to@todomain.com >
    Subject: SMTP e-mail test

    This is a test e-mail message.
    """

    try:
       smtpObj = smtplib.SMTP('localhost')
       smtpObj.sendmail(sender, receivers, message)
       print "Successfully sent email"
    except SMTPException:
       print "Error: unable to send email"

Python Programs - Regular Expressions - Search Function






  •       #!/usr/bin/python
    import re

    line = "Cats are smarter than dogs";

    matchObj = re.search( r'(.*) are(\.*)', line, re.M|re.I)

    if matchObj:
       print "matchObj.group() : ", matchObj.group()
       print "matchObj.group(1) : ", matchObj.group(1)
       print "matchObj.group(2) : ", matchObj.group(2)
    else:
       print "No match!!"
  • Output
    matchObj.group(): Cats are
    matchObj.group(1) : Cats
    matchObj.group(2) :

Python Programs - Regular Expressions - Match Function



  • #!/usr/bin/python
    import re

    line = "Cats are smarter than dogs";

    matchObj = re.match( r'(.*) are(\.*)', line, re.M|re.I)

    if matchObj:
       print "matchObj.group() : ", matchObj.group()
       print "matchObj.group(1) : ", matchObj.group(1)
       print "matchObj.group(2) : ", matchObj.group(2)
    else:
       print "No match!!"
  • Output
    matchObj.group(): Cats are
    matchObj.group(1) : Cats
    matchObj.group(2) :

Python Tuples



  • Accessing Values in Tuples:
    #!/usr/bin/python

    tup1 = ('physics', 'chemistry', 1997, 2000);
    tup2 = (1, 2, 3, 4, 5, 6, 7 );

    print "tup1[0]: ", tup1[0]
    print "tup2[1:5]: ", tup2[1:5]
    Output
    tup1[0]: physics
    tup2[1:5]: [2, 3, 4, 5]
    Updating Tuples:
    #!/usr/bin/python

    tup1 = (12, 34.56);
    tup2 = ('abc', 'xyz');

    # Following action is not valid for tuples
    # tup1[0] = 100;

    # So let's create a new tuple as follows
    tup3 = tup1 + tup2;
    print tup3;
    Output
    (12, 34.56, 'abc', 'xyz')
    Delete Tuple Elements:
    #!/usr/bin/python

    tup = ('physics', 'chemistry', 1997, 2000);

    print tup;
    del tup;
    print "After deleting tup : "
    print tup;
    Output
    ('physics', 'chemistry', 1997, 2000)
    After deleting tup :
    Traceback (most recent call last):
    File "test.py", line 9, in < module >
    print tup;
    NameError: name 'tup' is not defined
    No Enclosing Delimiters:
    #!/usr/bin/python

    print 'abc', -4.24e93, 18+6.6j, 'xyz';
    x, y = 1, 2;
    print "Value of x , y : ", x,y;
    print var;
    Output
    abc -4.24e+93 (18+6.6j) xyz
    Value of x , y : 1 2

Python Strings



  • Accessing Values in Strings:
    #!/usr/bin/python

    var1 = 'Hello World!'
    var2 = "Python Programming"

    print "var1[0]: ", var1[0]
    print "var2[1:5]: ", var2[1:5]
  • Output
    var1[0]: H
    var2[1:5]: ytho
  • Updating Strings:
    #!/usr/bin/python

    var1 = 'Hello World!'

    print "Updated String :- ", var1[:6] + 'Python'
  • Output
    Updated String :- Hello Python
  • String Formatting Operator:
    #!/usr/bin/python

    print "My name is %s and weight is %d kg!" % ('Zara', 21)
  • Output
    My name is Zara and weight is 21 kg!
  • Triple Quotes:
    #!/usr/bin/python

    para_str = """this is a long string that is made up of
    several lines and non-printable characters such as
    TAB ( \t ) and they will show up that way when displayed.
    NEWLINEs within the string, whether explicitly given like
    this within the brackets [ \n ], or just a NEWLINE within
    the variable assignment will also show up.
    """
    print para_str;
  • Output
    this is a long string that is made up of
    several lines and non-printable characters such as
    TAB ( ) and they will show up that way when displayed.
    NEWLINEs within the string, whether explicitly given like
    this within the brackets [
    ], or just a NEWLINE within
    the variable assignment will also show up.
  • Raw String:
    #!/usr/bin/python

    print 'C:\\nowhere'
  • Output
    C:\nowhere
  • Unicode String:
    #!/usr/bin/python

    print u'Hello, world!'
  • Output
    Hello, world!      

Python Lists



  • Accessing Values in Lists:
    #!/usr/bin/python

    list1 = ['physics', 'chemistry', 1997, 2000];
    list2 = [1, 2, 3, 4, 5, 6, 7 ];

    print "list1[0]: ", list1[0]
    print "list2[1:5]: ", list2[1:5]
  • Output
    list1[0]: physics
    list2[1:5]: [2, 3, 4, 5]
  • Updating Lists:
    #!/usr/bin/python

    list = ['physics', 'chemistry', 1997, 2000];

    print "Value available at index 2 : "
    print list[2];
    list[2] = 2001;
    print "New value available at index 2 : "
    print list[2];
  • Output
    Value available at index 2 :
    1997
    New value available at index 2 :
    2001
  • Delete List Elements:
    #!/usr/bin/python

    list1 = ['physics', 'chemistry', 1997, 2000];

    print list1;
    del list1[2];
    print "After deleting value at index 2 : "
    print list1;
  • Output
    ['physics', 'chemistry', 1997, 2000]
    After deleting value at index 2 :
    ['physics', 'chemistry', 2000]

Python Files I/O






  • Reading Keyboard Input:
    Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are:
    raw_input
    input
    • The raw_input Function:
      #!/usr/bin/python

      str = raw_input("Enter your input: ");
      print "Received input is : ", str
      Output
      Enter your input: Hello Python
      Received input is : Hello Python
    • The input Function:
      #!/usr/bin/python

      str = input("Enter your input: ");
      print "Received input is : ", str
      Output
      Enter your input: [x*5 for x in range(2,10,2)]
      Recieved input is : [10, 20, 30, 40]
  • Opening and Closing Files:
    Syntax:
    file object = open(file_name [, access_mode][, buffering])

    Here is paramters detail:
    1. file_name: The file_name argument is a string value that contains the name of the file that you want to access.

    2. access_mode: The access_mode determines the mode in which the file has to be opened ie. read, write append etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r)

    3. buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
  • The file object atrributes:
    #!/usr/bin/python

    # Open a file
    fo = open("foo.txt", "wb")
    print "Name of the file: ", fo.name
    print "Closed or not : ", fo.closed
    print "Opening mode : ", fo.mode
    print "Softspace flag : ", fo.softspace
    Output
    Name of the file: foo.txt
    Closed or not : False
    Opening mode : wb
    Softspace flag : 0
  • The close() Method:
    Syntax:
    fileObject.close();
    #!/usr/bin/python

    # Open a file
    fo = open("foo.txt", "wb")
    print "Name of the file: ", fo.name

    # Close opend file
    fo.close()
    Output
    Name of the file: foo.txt
  • Reading and Writing Files:
    • The write() Method:
      The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.

      The write() method does not add a newline character ('\n') to the end of the string:
      Syntax:
      fileObject.write(string);

      Here passed parameter is the content to be written into the opend file.
      Example:
      #!/usr/bin/python

      # Open a file
      fo = open("foo.txt", "wb")
      fo.write( "Python is a great language.\nYeah its great!!\n");

      # Close opend file
      fo.close()

      The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content

      Python is a great language.
      Yeah its great!!
    • The read() Method:
      Syntax:
      fileObject.read([count]);
      #!/usr/bin/python

      # Open a file
      fo = open("foo.txt", "r+")
      str = fo.read(10);
      print "Read String is : ", str
      # Close opend file
      fo.close()

      This would produce following result:

      Read String is : Python is
  • File Positions:
    #!/usr/bin/python

    # Open a file
    fo = open("foo.txt", "r+")
    str = fo.read(10);
    print "Read String is : ", str

    # Check current position
    position = fo.tell();
    print "Current file position : ", position

    # Reposition pointer at the beginning once again
    position = fo.seek(0, 0);
    str = fo.read(10);
    print "Again read String is : ", str
    # Close opend file
    fo.close()
    This would produce following result:

    Read String is : Python is
    Current file position : 10
    Again read String is : Python is
  • Renaming and Deleting Files:
    • The rename() Method:
      The rename() method takes two arguments, the current filename and the new filename.
      Syntax:
      os.rename(current_file_name, new_file_name)
      Example:
      Following is the example to rename an existing file test1.txt:

      #!/usr/bin/python
      import os

      # Rename a file from test1.txt to test2.txt
      os.rename( "test1.txt", "test2.txt" )
    • The delete() Method:
      Syntax:
      os.delete(file_name)
      Example:
      Following is the example to delete an existing file test2.txt:

      #!/usr/bin/python
      import os

      # Delete file test2.txt
      os.delete("text2.txt")
  • Directories in Python:
    • The mkdir() Method:
      Syntax:
      os.mkdir("newdir")
      Example:
      Following is the example to create a directory test in the current directory:

      #!/usr/bin/python
      import os

      # Create a directory "test"
      os.mkdir("test")
    • The chdir() Method:
      Syntax:
      os.chdir("newdir")
      Example:
      Following is the example to go into "/home/newdir" directory:

      #!/usr/bin/python
      import os

      # Changing a directory to "/home/newdir"
      os.chdir("/home/newdir")
    • The getcwd() Method:
      Syntax:
      os.getcwd()
      Example:

      Following is the example to give current directory:
      #!/usr/bin/python
      import os

      # This would give location of the current directory
      os.getcwd()
    • The rmdir() Method:
      Syntax:

      os.rmdir('dirname')
      Example:
      Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the directory otherwise it would search for that directory in the current directory.

      #!/usr/bin/python
      import os

      # This would remove "/tmp/test" directory.
      os.rmdir( "/tmp/test" )

Python Dictionary






  • Accessing Values in Dictionary:
    #!/usr/bin/python
    dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

    print "dict['Name']: ", dict['Name'];
    print "dict['Age']: ", dict['Age'];
  • Output
    dict['Name']: Zara
    dict['Age']: 7
  • Updating Dictionary:
    #!/usr/bin/python
    dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

    dict['Age'] = 8; # update existing entry
    dict['School'] = "DPS School"; # Add new entry


    print "dict['Age']: ", dict['Age'];
    print "dict['School']: ", dict['School'];
  • Output
    dict['Age']: 8
    dict['School']: DPS School
  • Delete Dictionary Elements:
    #!/usr/bin/python

    dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

    del dict['Name']; # remove entry with key 'Name'
    dict.clear(); # remove all entries in dict
    del dict ; # delete entire dictionary

    print "dict['Age']: ", dict['Age'];
    print "dict['School']: ", dict['School'];
  • Output
    This will produce following result. Note an exception raised, this is because after del dict dictionary does not exist any more:

    dict['Age']:
    Traceback (most recent call last):
    File "test.py", line 8, in < module >
    print "dict['Age']: ", dict['Age'];
    TypeError: 'type' object is unsubscriptable
  • Properties of Dictionary Keys:
    (a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. Following is a simple example:

    #!/usr/bin/python

    dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

    print "dict['Name']: ", dict['Name'];

    When the above code is executed, it produces following result:

    dict['Name']: Manni

    (b) Keys must be immutable. Which means you can use strings, numbers, or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example:

    #!/usr/bin/python

    dict = {['Name']: 'Zara', 'Age': 7};

    print "dict['Name']: ", dict['Name'];

    When the above code is executed, it produces following result:

    Traceback (most recent call last):
       File "test.py", line 3, in < module >
       dict = {['Name']: 'Zara', 'Age': 7};
    TypeError: list objects are unhashable

Python Date/Time

 


  • What is Tick?
    Python's time and calendar modules help track dates and times.
    Time intervals are floating-point numbers in units of seconds.
    Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).
    There is a popular time module available in Python which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch).
  • Example:
    #!/usr/bin/python
    import time; # This is required to include time module.

    ticks = time.time()
    print "Number of ticks since 12:00am, January 1, 1970:", ticks

    This would produce a result something as follows:

    Number of ticks since 12:00am, January 1, 1970: 7186862.73399
  • Getting current time -:
    #!/usr/bin/python
    localtime = time.localtime(time.time())
    print "Local current time :", localtime
  • Output
    Local current time : (2008, 5, 15, 12, 55, 32, 0, 136, 1)
  • Getting formatted time -:
    #!/usr/bin/python
    import time;

    localtime = time.asctime( time.localtime(time.time()) )
    print "Local current time :", localtime
  • Output
    Local current time : Tue Jan 13 10:17:09 2009
  • Getting calendar for a month -:
    #!/usr/bin/python
    import calendar

    cal = calendar.month(2008, 1)
    print "Here is the calendar:"
    print cal;
  • Output
    Here is the calendar:
    January 2008
    Mo Tu We Th Fr Sa Su
    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

Python Object Oriented - Overriding Methods






  •       #!/usr/bin/python

    class Parent: # define parent class
       def myMethod(self):
         print 'Calling parent method'

    class Child(Parent): # define child class
       def myMethod(self):
         print 'Calling child method'

    c = Child() # instance of child
    c.myMethod() # child calls overridden method
  • Output
    Calling child method

Python Object Oriented - Overloading Operators






  • #!/usr/bin/python

    class Vector:
       def __init__(self, a, b):
         self.a = a
         self.b = b

       def __str__(self):
         return 'Vector (%d, %d)' % (self.a, self.b)
       def __add__(self,other):
         return Vector(self.a + other.a, self.b + other.b)

    v1 = Vector(2,10)
    v2 = Vector(5,-2)
    print v1 + v2
  • Output
    Vector(7,8)

Python Object Oriented - Data Hiding



  • #!/usr/bin/python

    class JustCounter:
       __secretCount = 0

       def count(self):
         self.__secretCount += 1
         print self.__secretCount

    counter = JustCounter()
    counter.count()
    counter.count()
    print counter.__secretCount
  • Output
    1
    2
    Traceback (most recent call last):
    File "test.py", line 12, in < module >
    print counter.__secretCount
    AttributeError: JustCounter instance has no attribute '__secretCount'
  • Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it would work for you:

    .........................
    print counter._JustCounter__secretCount
    Output
    1
    2
    2

Python Object Oriented - Class Inheritance






  •  #!/usr/bin/python

    class Parent: # define parent class
    parentAttr = 100
    def __init__(self):
       print "Calling parent constructor"

    def parentMethod(self):
       print 'Calling parent method'

    def setAttr(self, attr):
       Parent.parentAttr = attr

    def getAttr(self):
       print "Parent attribute :", Parent.parentAttr

    class Child(Parent): # define child class
    def __init__(self):
       print "Calling child constructor"

    def childMethod(self):
       print 'Calling child method'
    c = Child() # instance of child
    c.childMethod() # child calls its method
    c.parentMethod() # calls parent's method
    c.setAttr(200) # again call parent's method
    c.getAttr() # again call parent's method
  • Output
    Calling child constructor
    Calling child method
    Calling parent method
    Parent attribute : 200
  • Similar way you can drive a class from multiple parent classes as follows:

    class A: # define your class A
    .....

    class B: # define your calss B
    .....

    class C(A, B): # subclass of A and B
    .....

Python Object Oriented - Classes






  • Creating Classes:
    The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows:
    class ClassName:
    'Optional class documentation string'
    class_suite

    The class has a documentation string which can be access via ClassName.__doc__.

    The class_suite consists of all the component statements, defining class members, data attributes, and functions.
    Example:
    class Employee:
    'Common base class for all employees'
    empCount = 0

    def __init__(self, name, salary):
       self.name = name
       self.salary = salary
       Employee.empCount += 1

    def displayCount(self):
       print "Total Employee %d" % Employee.empCount

    def displayEmployee(self):
       print "Name : ", self.name, ", Salary: ", self.salary
  • Creating instance objects:
    "This would create first object of Employee class"
    emp1 = Employee("Zara", 2000)
    "This would create second object of Employee class"
    emp2 = Employee("Manni", 5000)
  • Accessing attributes:
    You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows:

    emp1.displayEmployee()
    emp2.displayEmployee()
    print "Total Employee %d" % Employee.empCount

Python Programs - Multithreading - Synchronizing Threads:






  • Synchronization
    #!/usr/bin/python

    import threading
    import time

    class myThread (threading.Thread):
       def __init__(self, threadID, name, counter):
         self.threadID = threadID
         self.name = name
         self.counter = counter
         threading.Thread.__init__(self)
       def run(self):
         print "Starting " + self.name
         # Get lock to synchronize threads
         threadLock.acquire()
         print_time(self.name, self.counter, 3)
         # Free lock to release next thread
         threadLock.release()

      def print_time(threadName, delay, counter):
         while counter:
           time.sleep(delay)
           print "%s: %s" % (threadName, time.ctime(time.time()))
           counter -= 1

    threadLock = threading.Lock()
    threads = []

    # Create new threads
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)

    # Start new Threads
    thread1.start()
    thread2.start()

    # Add threads to thread list
    threads.append(thread1)
    threads.append(thread2)

    # Wait for all threads to complete
    for t in threads:
       t.join()
    print "Exiting Main Thread"
  • Output
    Starting Thread-1
    Starting Thread-2
    Thread01: Thu Jan 22 16:04:38 2009
    Thread01: Thu Jan 22 16:04:39 2009
    Thread01: Thu Jan 22 16:04:40 2009
    Thread02: Thu Jan 22 16:04:42 2009
    Thread02: Thu Jan 22 16:04:44 2009
    Thread02: Thu Jan 22 16:04:46 2009
    Exiting Main Thread

Python Multithreaded Programming






  • Starting a New Thread
    #!/usr/bin/python

    import thread
    import time

    # Define a function for the thread
    def print_time( threadName, delay):
       count = 0
       while count < 5:
         time.sleep(delay)
         count += 1
         print "%s: %s" % ( threadName, time.ctime(time.time()) )

    # Create two threads as follows
    try:
       thread.start_new_thread( print_time, ("Thread-1", 2, ) )
       thread.start_new_thread( print_time, ("Thread-2", 4, ) )
    except:
       print "Error: unable to start thread"

    while 1:
       pass
  • Output
    Thread-1: Thu Jan 22 15:42:17 2009
    Thread-1: Thu Jan 22 15:42:19 2009
    Thread-2: Thu Jan 22 15:42:19 2009
    Thread-1: Thu Jan 22 15:42:21 2009
    Thread-2: Thu Jan 22 15:42:23 2009
    Thread-1: Thu Jan 22 15:42:23 2009
    Thread-1: Thu Jan 22 15:42:25 2009
    Thread-2: Thu Jan 22 15:42:27 2009
    Thread-2: Thu Jan 22 15:42:31 2009
    Thread-2: Thu Jan 22 15:42:35 2009

Python Program - Creating Thread using Threading Module



  • Threading Module
    #!/usr/bin/python

    import threading
    import time

    exitFlag = 0

    class myThread (threading.Thread):
       def __init__(self, threadID, name, counter):
         self.threadID = threadID
         self.name = name
         self.counter = counter
         threading.Thread.__init__(self)
       def run(self):
         print "Starting " + self.name
         print_time(self.name, self.counter, 5)
         print "Exiting " + self.name
    def print_time(threadName, delay, counter):
       while counter:
         if exitFlag:
           thread.exit()
           time.sleep(delay)
           print "%s: %s" % (threadName, time.ctime(time.time()))
           counter -= 1

    # Create new threads
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)

    # Start new Threads
    thread1.start()
    thread2.run()

    while thread2.isAlive():
       if not thread1.isAlive():
         exitFlag = 1
       pass
      print "Exiting Main Thread"
  • Output
    Starting Thread-2
    Starting Thread-1
    Thread-1: Thu Jan 22 15:53:05 2009
    Thread-2: Thu Jan 22 15:53:06 2009
    Thread-1: Thu Jan 22 15:53:06 2009
    Thread-1: Thu Jan 22 15:53:07 2009
    Thread-2: Thu Jan 22 15:53:08 2009
    Thread-1: Thu Jan 22 15:53:08 2009
    Thread-1: Thu Jan 22 15:53:09 2009
    Exiting Thread-1
    Thread-2: Thu Jan 22 15:53:10 2009
    Thread-2: Thu Jan 22 15:53:12 2009
    Thread-2: Thu Jan 22 15:53:14 2009
    Exiting Thread-2
    Exiting Main Thread

Python Functions






  • def functionname( parameters ):
      "function_docstring"
      function_suite
      return [expression]
    Example
    def printme( str ):
      "This prints a passed string into this function"
      print str
      return

    #!/usr/bin/python

    # Function definition is here
    def printme( str ):
      "This prints a passed string into this function"
      print str;
      return;

    # Now you can call printme function
    printme("I'm first call to user defined function!");
    printme("Again second call to the same function");
  • Output
    I'm first call to user defined function!
    Again second call to the same function
  • Pass by reference vs value:
    #!/usr/bin/python

    # Function definition is here
    def changeme( mylist ):
       "This changes a passed list into this function"
       mylist.append([1,2,3,4]);
       print "Values inside the function: ", mylist
       return

    # Now you can call changeme function
    mylist = [10,20,30];
    changeme( mylist );
    print "Values outside the function: ", mylist
  • Output
    Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
    Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

  • There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written.
    #!/usr/bin/python
    # Function definition is here
    def changeme( mylist ):
       "This changes a passed list into this function"
       mylist = [1,2,3,4]; # This would assig new reference in mylist
       print "Values inside the function: ", mylist
       return
    # Now you can call changeme function
    mylist = [10,20,30];
    changeme( mylist );
    print "Values outside the function: ", mylist
  • Output
    Values inside the function: [1, 2, 3, 4]
    Values outside the function: [10, 20, 30]

Python Programs - Function Arguments






  •             You can call a function by using the following types of formal arguments::
    Required arguments

    Keyword arguments

    Default arguments

    Variable-length arguments
  • Required arguments:
    To call the function printme() you definitely need to pass one argument otherwise it would give a syntax error as follows:

    #!/usr/bin/python

    # Function definition is here
    def printme( str ):
       "This prints a passed string into this function"
       print str;
       return;

    # Now you can call printme function
    printme();
  • Output
    Traceback (most recent call last):
      File "test.py", line 11, in < module >
       printme();
    TypeError: printme() takes exactly 1 argument (0 given)
  • Keyword arguments:
    This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
    You can also make keyword calls to the printme() function in the following ways:

    #!/usr/bin/python

    # Function definition is here
    def printme( str ):
       "This prints a passed string into this function"
      print str;
      return;

    # Now you can call printme function
    printme( str = "My string");
  • Output
    My string
  • Default arguments:
    #!/usr/bin/python

    # Function definition is here
    def printinfo( name, age = 35 ):
     "This prints a passed info into this function"
     print "Name: ", name;
     print "Age ", age;
     return;

    # Now you can call printinfo function
    printinfo( age=50, name="miki" );
    printinfo( name="miki" );
  • Output
    Name: miki
    Age 50
    Name: miki
    Age 35
  • Variable-length arguments:
    Syntax:
    def functionname([formal_args,] *var_args_tuple ):
     "function_docstring"
     function_suite
     return [expression]

    Example:
    #!/usr/bin/python

    # Function definition is here
    def printinfo( arg1, *vartuple ):
      "This prints a variable passed arguments"
      print "Output is: "
      print arg1
      for var in vartuple:
        print var
    return;

    # Now you can call printinfo function
    printinfo( 10 );
    printinfo( 70, 60, 50 );
  • Output
    Output is:
    10
    Output is:
    70
    60
    50

Python Programs - Database - Update Operation:






  • Update Table
    #!/usr/bin/python

    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # Prepare SQL query to UPDATE required records
    sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
         WHERE SEX = '%c'" % ('M')
    try:
       # Execute the SQL command
       cursor.execute(sql)
       # Commit your changes in the database
       db.commit()
    except:
       # Rollback in case there is any error
       db.rollback()

    # disconnect from server
    db.close()

Python Program - Database - READ Operation






  • READ Operation
    READ Operation on any databasse means to fetch some useful information from the database.
    Once our database connection is established, we are ready to make a query into this database.
    We can use either fetchone() method to fetch single record or fetchall method to fetech multiple values from a database table.
    1. fetchone(): This method fetches the next row of a query result set.
      A result set is an object that is returned when a cursor object is used to query a table.
    2. fetchall(): This method fetches all the rows in a result set.
      If some rows have already been extracted from the result set, the fetchall() method retrieves the remaining rows from the result set.
    3. rowcount: This is a read-only attribute and returns the number of rows that were affected by an execute() method.
  • Example:
    Following is the procedure to query all the records from EMPLOYEE table having salary more than 1000.

    #!/usr/bin/python

    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # Prepare SQL query to INSERT a record into the database.
    sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d'" % (1000)
    try:
       # Execute the SQL command
       cursor.execute(sql)
       # Fetch all the rows in a list of lists.
       results = cursor.fetchall()
       for row in results:
         fname = row[0]
         lname = row[1]
         age = row[2]
         sex = row[3]
         income = row[4]
         # Now print fetched result
         print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
         (fname, lname, age, sex, income )
    except:
       print "Error: unable to fecth data"
    # disconnect from server
    db.close()

    This will produce following result:

    fname=Mac, lname=Mohan, age=20, sex=M, income=2000

Python Program - Database - Performing Transactions:






  • Transaction
    Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties:
    1. Atomicity: Either a transaction completes or nothing happens at all.
    2. Consistency: A transaction must start in a consistent state and leave the system is a consistent state.
    3. Isolaion: Intermediate results of a transaction are not visible outside the current transaction.
    4. Durability: Once a transaction was committed, the effects are persistent, even after a system failure.
    5. The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
  • Example:
    # Prepare SQL query to DELETE required records
    sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
    try:
       # Execute the SQL command
       cursor.execute(sql)
       # Commit your changes in the database
       db.commit()
    except:
       # Rollback in case there is any error
       db.rollback()
  • COMMIT Operation:
    Commit is the operation which gives a green signal to database to finalize the changes and after this operation no change can be reverted back.
    Example
    db.commit()
  • ROLLBACK Operation:
    If you are not satisfied with one or more of the changes and you want to revert back those changes completely then use rollback method.
    Example
    db.rollback()
  • Disconnecting Database:
    To disconnect Database connection, use close() method.
    db.close()

    If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB.
    However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.