Posts

Showing posts from March, 2018

Using time module

The time module provides the current date and time using time() function The time.time() returns the number of second elapsed from 1/1/1970 12:00 am till current date and time called as ticks >>> import time >>> time.time() 1522211915.914467 We can also convert these ticks into actual date and time using function time.localtime() >>> time.localtime(time.time()) time.struct_time(tm_year=2018, tm_mon=3, tm_mday=28, tm_hour=10, tm_min=10, tm_sec=0, tm_wday=2, tm_yday=87, tm_isdst=0) It returns a structure having different fields for date and time which we can convert into date or time format >>> t=time.localtime(time.time()) >>> currentdate='%02d-%02d-%d' % (t.tm_mday,t.tm_mon,t.tm_year) >>> currentdate '28-03-2018' >>> currenttime='%02d-%02d-%02d' % (t.tm_hour,t.tm_min,t.tm_sec) >>> currenttime '10-12-05' We can also use this structure inside the functions and ...

Using pickle module

The pickle module is used to serialize and de-serialize the data available in collections like and dictionary Use dump() function to save data from memory to the disc in some file (serialization) Use load() function load data from disc to memory (de-serialization) >>> names=["Vikas","Kapil","Neeraj"] >>> names ['Vikas', 'Kapil', 'Neeraj'] >>> import pickle >>> f1=open("names","wb") >>> pickle.dump(names,f1) >>> f1.close() >>> f2=open("names","rb") >>> mynames=pickle.load(f2) >>> f2.close() >>> mynames ['Vikas', 'Kapil', 'Neeraj'] >>> names==mynames True

Exception Handling in Python

A system to trap the runtime error when the program is in execution. Use try and except keywords to trap some runtime error Python provides a built-in class Exception to trap the error message Use raise keyword to send some error message using the Exception class Example 1 def factorial(n):     if(n<0):         raise Exception("Sorry! Number must be >=0")     f=1     i=1     while i<=n:         f=f*i         i=i+1     return f try:     n=int(input("Enter a number : "))     print("Factorial of",n,"is",factorial(n)) except Exception as e:     print("Error : ",e) Example 2: Custom Exception class InvalidNumberException(Exception):     def __init__(self,message):    ...

Using SQLite Database with Python

Image
Download and install SQLite 3 in your machine from https://www.sqlite.org/download.html Create a folder in some drive like D: as sqlite and drop sqlite3.exe file into it Create a folder db into it Open IDLE Import the sqlite3 module and create the database >>> import sqlite3 >>> sqlite3.connect("d:/sqlite/db/pythonsqlite.db") Start the SQLite3, open the database connection and create required table. e.g. CREATE TABLE book (  bookno integer PRIMARY KEY,  title text NOT NULL,  author text NOT NULL,  price real NOT NULL ); Save records into book table #saving records into book table import sqlite3 cn=sqlite3.connect("d:/sqlite/db/pythonsqlite.db") cursor = cn.cursor() while True:     bookno=int(input("Enter book no "))     title=input("Title ")     author=input("Author ")     price=float(input("Price "))     sql="insert into book values ({},'{}','{}...

File Handling in Python

File and folder Related Functions Use  os  module os.rename(oldname,newname)                       rename file or folder os.remove(filename)                                       remove a file os.mkdir(dirname)                                          make directory os.rmdir(dirname)                                           remove a directory os.chdir(dirname)   ...

Using MySQL as Database with Python

Image
Sample Application Create database as library Create table as book with four columns 1. bookno, int 2. title, varchar, 100 3. author, varchar, 100 4. price, float Enter some sample records  Inserting records into database table : savebook.py #inserting record import MySQLdb cn=MySQLdb.connect(host='localhost',user='root',passwd='',database='library',port=3306) cursor = cn.cursor() bookno=int(input("Enter book no ")) title=input("Title ") author=input("Author ") price=float(input("Price ")) sql="insert into book values ({},'{}','{}',{})".format(bookno,title,author,price) cursor.execute(sql) cn.commit()   cn.close()        Show all records present in the table book: showbooks.py import MySQLdb cn=MySQLdb.connect(host='localhost',user='root',passwd='',db='library') cursor = cn.cursor() cursor.execute(...