Python Notes

 

PYTHON

 

Introduction:

Python is an object-oriented, high level language, interpreted, dynamic and multipurpose programming language.

Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and other scripting languages.

Python features:

1.Easy to use

2.Expressive language

3.interpreted language

4.Cross-Platform language

5.Free and Open source

6.Object-Oriented  language

7.Extensible

8.Large standard library

9.GUI programming

10. Integrated

 

Python versions:

Python Version

Released Date

Python 1.0

January 1994

Python 1.5

December 31, 1997

Python 1.6

September 5, 2000

Python 2.0

October 16, 2000

Python 2.1

April 17, 2001

Python 2.2

December 21, 2001

Python 2.3

July 29, 2003

Python 2.4

November 30, 2004

Python 2.5

September 19, 2006

Python 2.6

October 1, 2008

Python 2.7

July 3, 2010

Python 3.0

December 3, 2008

Python 3.1

June 27, 2009

Python 3.2

February 20, 2011

Python 3.3

September 29, 2012

 

DIFFERENCE BETWEEN PYTHON AND JAVA:

 

JAVA

PYTHON

1.It is fast,secure and reliable general purpose computer programming language.

1.A readable,efficient and powerfull high level programming language.

2.It is statically typed and faster than python.

2.Dynamically typed and slower than java.

3.java legacy systems are typically larger and numerous.

3.python has less legacy problem.

4.Longer lines of code when compared to python.

4.Shorter lines of code when compared to java.

5.Most popular and widely used database.

5.Access layers are weaker than java’s JDBC.

6.popular for mobile and web applications.

6.Popular for data science,ML,AI,IOT.

7.It is a compiled language.

7.It is interpreted language.

8.It is an object oriented language.

8.It is a scripting language.

 

Python Applications:

1.Console based applications

Ex:IPython

2.Audio or Video based applications

Ex:Timplayer,cplayer

3.3D CAD applications

Ex:Fandango

4.Web applications

Ex:PythonWikiEngines,pocoo,PythonBlogSoftware etc…

5.Enterprise applications

Ex:OpenErp,Tryton,Picalo etc..

6.Applications for Images

Ex:VPython,Gogh,imgSeek etc…

Basic Example:

>>> a=”hello world"

>>> print(a)

Python 3.4 Example

>>> a=("hello world")

>>> print (a)

 

Python Variables

Variable is a name of the memory location where data is stored.

1.Assigning values to the variable:

Eg:

>>>a=10

>>>name=’sushma’

>>>salary=20000

>>>print a

>>>print name

>>>print salary

 

 

2.Multiple Assignment:

a)Assigning single value to multiple variables:

Eg:

>>>a=b=c=40

>>>print a ->40

>>>print b ->40

>>>print c ->40

b)Assigning multiple values to multiple variables:

Eg:

>>>x,y,z=2,3,5

>>>print x ->2

>>>print y ->3

>>>print z ->5

Tuples

  • Tuple is another form of collection where different type of data can be stored.
  • It is similar to list where data is separated by commas. Only the difference is that list uses square bracket and tuple uses parenthesis.
  • Tuples are enclosed in parenthesis and cannot be changed.

Eg:

>>>tuple=(‘sushma’,200,45.67,’mani’)

>>>tuple1=(‘kumar’,20)

>>>tuple+tuple1

Dictionary

 

  • Dictionary is a collection which works on a key-value pair.
  • It works like an associated array where no two keys can be same.
  • Dictionaries are enclosed by curly braces ({}) and values can be retrieved by square bracket([ ]).

Eg:

>>>dictionary={‘dept’:’java devp’,’name’:’sushma’,’id’:20}

>>>dictionary.keys()

>>>dictionary.values()

 

Python Tokens

There are following tokens in Python:

  • Keywords.
  • Identifiers.
  • Literals.
  • Operators

Keywords:

True

False

None

and

as

asset

def

class

continue

break

else

finally

elif

del

except

global

for

if

from

import

raise

try

or

return

pass

nonlocal

in

not

is

lambda

 

Identifiers:

Identifiers are the names given to the fundamental building blocks in a program.

These can be variables ,class ,object ,functions , lists , dictionaries etc.

Rules:

I. An identifier is a long sequence of characters and numbers.

II.No special character except underscore ( _ ) can be used as an identifier.

III.Keyword should not be used as an identifier name.

IV.Python is case sensitive. So using case is significant.

V.First character of an identifier can be character, underscore ( _ ) but not digit.

 

 

 

Literals:

1.String literals:

We can use both single as well as double quotes for a String.

There are two types of Strings supported in Python:

a).Single line String- Strings that are terminated within a single line are known as Single line Strings.

Eg:

>>>text1=’india’

b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.

There are two ways to create Multiline Strings:

1). Adding black slash at the end of each line

Eg:

>>> text1='hello\

user'

>>> text1

2).Using triple quotation marks:-

Eg:

>>> str2='''''welcome

to

SSSIT        ''’

>>> print str2

2.Numeric Literals:

Int(signed integers):

Numbers( can be both positive and negative) with no fractional part.

eg: 100

long(long integers):

Integers of unlimited size followed by lowercase or uppercase L eg: 87032845L

Float(floating point):

Real numbers with both integer and fractional part eg: -26.2

Complex(complex):

In the form of a+bj where a forms the real part and b forms the imaginary part of complex number.eg: 3+14j

3.Boolean literals:

A Boolean literal can have any of the two values: True or False

4.special literals:

Python contains one special literal i.e., None.

None is used to specify to that field that is not created. It is also used for end of lists in Python.

Eg:

>>> val1=10

>>> val2=None

>>> val1

>>> val2

>>> print val2

5.literal collections:

List:

  • List contain items of different data types. Lists are mutable i.e., modifiable.
  • The values stored in List are separated by commas(,) and enclosed within a square brackets([ ]). We can store different type of data in a List.
  • Value stored in a List can be retrieved using the slice operator([ ] and [:]).
  • The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.

Eg:

>>> list=['mani',678,20.4,'kumar']

>>> list1=[456,'sowmya']

>>> list

>>> list[1:3]

>>>list+list1

>>>list1*2

Python operators

1.Arithmetic operators:

·        //  àperform floor division(gives integer value after division)

·        +  àAddition

·        -   àSubtraction

·        *  àMultiplication

·        /   àDivision

·        % àTo return remainder after division(Modules)

·        ** àperform exponent(raise to power)

 

2.Relational operators:

·        <àless than

·        >àGreater than

·        <= àLess than or equal to

·        >= àGreater than or equal to

·        == àEqual to

·        != à Not equal to

·        <>àNot equal to(similar to !=)

 

3.Assignment operators:

 

·        = àAssignment

·        /=àDivide and assign

·        +=àAdd and assign

·        -= à subtract and assign

·        *= àmultiply and assign

·        %= àmodulus and assign

·        **= àexponent and assign

·        //= àfloor design and assign

 

4.Logical operators:

·        andàlogical AND(when both conditions are true output will true)

·        oràLogical OR(if any one condition is true output will true)

·        not àLogical NOT(compliment the condition(reverse))

 

5.Memebership operators:

·        in àReturns true if a variable is in sequence of another variable,else false

·        not inàReturns true if a variable is not in sequence of another variable,else false

 

6.Identity operators:

·        isàReturns true if identity of two operands are same,else false

·        is notàReturns true if identity of two operands are not same,else false

 

Python comments

 

There are two types of comments

1.single line comments(#)

2.multi line comments(‘”………………”’)

 

TAKING INPUT FROM KEYBOARD IN PYTHON

àThere are two inbuilt functions to read the input from the keyboard.

·        raw_input(prompt)

·        input(prompt)

1.raw_input():

àIt supports in python 2.x.

àThis function takes exactly what is typed from the keyboard,converted it to string and then return it to the variable in which we want to store.

Example:

Name=raw_input(“enter your name:”)

print Name

output:

enter your name:sushma

sushma

NOTE:

‘raw_input()’ function is deprecated in python 3.x.

 

2.input():

This function automatically identifies whether user entered a string (or) list.If the input provided is not correct then either syntax error (or) exception is raised by python.

                             Whatever you enter as input, input function convert it into a string.If you enter an integer value still input() function convert it into an integer in your  code using ‘type casting’.

Example:

>>> num=input("enter number:")

enter number:234

>>> print("type of number:",type(num))

type of number: <class 'str'>

>>> print(num)

234

>>> name=input("enter name:")

enter name:sushma

>>> print("type of name:",type(name))

type of name: <class 'str'>

>>> print(name)

Sushma

Taking input from console in python:

Taking input from console using ‘input()’ function.

1.Typecasting the input to integer:

 Example:

>>> num1=int(input())

23

>>> num2=int(input())

34

>>> num3=int(input())

67

>>> print(num1)

23

>>> print(num2)

34

>>> print(num3)

67

 

2.Typecasting the input to float:

Example:

>>> num1=float(input())

45.678

>>> num2=float(input())

78.906

>>> num3=float(input())

45.890

>>> print(num1)

45.678

>>> print(num2)

78.906

>>> print(num3)

45.89

 

3.Typecasting the input to float:

All kind of input can be converted to string type whether they are float (or) integer.We make use of keyword str for typecasting.

Example:

>>> name=str(input())

sushma

>>> print(name)

sushma

 

Taking multiple inputs from user in python:

In python user can take multiple values (or) inputs in one line by two methods.

·        Using split() method

·        Using list comprehension

1.Using split() method:

This function helps in getting a multiple inputs from user.It breaks the input by the specific separator.If separator is not provided then any white space is a separator.

Syntax:

input().split(separator,maxsplit)

 

Type-1:

Example:

x,y=input("enter two values:").split()

print("x value is:",x)

print("y value is:",y)

output:

enter two values:89 78

x value is: 89

y value is: 78

 

#type-2:taking two inputs at a time

a,b=input("enter a two values:").split()

print("first number is {} and second number is {}".format(a,b))

print()

output:

enter a two values:45 56

first number is 45 and second number is 56

#type-3:taking multiple inputs at a time

#and typecasting using list function

list1=list(map(int,input("enter values:").split()))

print("list of students:",list1)

print()

output:

enter values:45 67 45 34 23

list of students: [45, 67, 45, 34, 23]

 

2.using list comprehension:

We can create lists just like mathematical statements one line only.It is also used in getting multiple inputs from a user.

Example:

#type-1:taking three inputs at a time

x,y,z=[int(x) for x in input("enter 3 values:").split()]

print("x value is:",x)

print("y value is:",y)

print("z value is:",z)

 

#type-2:

x,y=[int(x) for x in input("enter 2 values:").split()]

print("x value is {} and y value is {}".format(x,y))

print()

 

#type-3:

x=[int(x) for x in input("enter list fo values:").split()]

print("no.of list is:",x)

 

output:

enter 3 values:23 34 45

x value is: 23

y value is: 34

z value is: 45

enter 2 values:78 89

x value is 78 and y value is 89

 

enter list fo values:23 34 45 56

no.of list is: [23, 34, 45, 56]

 

‘end’ parameter in print:

print() function comes with a parameter called ‘end’.By default, the value of this parameter is ‘\n’. i.e the new line character.you can end a print statement with any character/string using this parameter.

Example:

 print("welcome to",end="")

print("new thoughts",end="")

print()

 

print("python",end="@")

print("new thoughts")

output:

welcome tonew thoughts

python@new thoughts

 

‘sep’ parameter in print():

à’sep’ parameter is implemented in python.3.x (or) later

àIt is used for formatting the output strings

àprint() function in python is space by default (softspace feature),which can be modified and can be made to any character,integer (or) string as per our choice.

Example:

print('s','u','s',sep='')

print('17','05','1990',sep='-')

print('sushma','alla',sep='@')

print()

 

print('s','u',sep='',end='')

print('s')

print('17','05',sep='-',end='-1990\n')

print('sushma','alla',sep='',end='@')

print("sowmya")

output:

sus

17-05-1990

sushma@alla

 

sus

17-05-1990

sushmaalla@sowmya

 

Output formatting:

(a)formatting output using string modulo operator(%):

The % operator can also be used for string formatting.It interprets  the left argument much like a printf()-style format string to be applied to the right argument.

Example:

print("id:%.2d,salary:%5.2f"%(1,89.34567))

print("total students:%3d,girls:%2d"%(240,120))

print("% 10.3E"%(356.089765))

print()

output:

id:01,salary:89.35

total students:240,girls:120

 3.561E+02

 

(b)Formatting output using format method:

Format method of string requires more manual effort.This method let us concatenate elements within an output through positional formatting.

Example:

print('iam learning {}'.format('python'))

print('{0} and {1}'.format('sushma','alla'))

print("no:{0:2d},portal:{1:8.2f}".format(12,00.546))

output:

iam learning python

sushma and alla

no:12,portal:    0.55

 

Control structures

If statement:

Syntax:

If(condition):

Statements

Example:

a=10

if a>5:

    print "given number is greater than 5"

 

if else statement:

Syntax:

If(condition):

statements

else:

statements

Example:

num=45

if num>10:

    print "given number is greater than 10"

else:

    print "given number is not greater than 10"

 

Nested if else statement:

Syntax:

if statement:

body

else:

if statement:

body

else:

body

Example:

marks=90

if marks<40 and marks>=0:

    print('failed')

elif marks<60 and marks>=40:

    print('c grade')

elif marks<80 and marks>=60:

    print('b grade')

elif marks<=100 and marks>=80:

    print('a grade')

else:

    print('invalid input')

for loop:

Syntax:

For<variable> in <sequence>:

Example:

for a in range(0,10):

    print(a)

Nested for loops:

Syntax:

for  <expression>:

for <expression>:

Body

Example:1

for i in range(0,5):

    for j in range(0,i+1):

        print("*",end="")

    print()

output:

*

**

***

****

Example:2

k=1

for i in range(0,5):

    for j in range(0,k):

        print("*",end="")

    k=k+2

    print()

output:

==

*

***

*****

*******

 

Example:3

 n=1

for i in range(0,5):

    for j in range(0,i+1):

        print(n,end="")

        n=n+1

    print()

output:

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15

 

Example:4

for i in range(0,5):

    num=1

    for j in range(0,i+1):

        print(num,end="")

        num=num+1

    print()

output:

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5  

 

Example:5

val=65

for i in range(0,5):

    for j in range(0,i+1):

        ch=chr(val)

        print(ch,end="")

        val=val+1

    print()

   

output:

A

B C

D E F

G H I J

K L M N O

 

Example:6

val=65

for i in range(0,5):

    for j in range(0,i+1):

        ch=chr(val)

        print(ch,end="")

    val=val+1

    print()

output:

A

B B

C C C

D D D D

E E E E  E

  

While loop:

Syntax:

While<expression>:

Body

Example:

x=0

while x<5:

    x=x+1

    print(x)

 

Break statement:

It is a jump statement that is used to pass the control to the end of the loop.

Example:

for i in [1,2,3,4,5,6,7]:

    if i==6:

        print "element found"

        break

    print i

Python Pass:

When you do not want any code to execute,pass statement is used.

Syntax:

Pass

Example:

for i in [1,2,3,4,5,6,7]:

    if i==5:

        pass

 

        print ("pass when value is",i)

    print i

ARRAYS

It is a collection of elements  of a single data type.

Example:

Array of integers

Array of strings

àIn python,there is no native array data structures.so,we can use python lists instead of an array.

àIf you want to create real arrays in python,you need to use NumPy’s array data structures.For mathematical problems NumPy array is more efficient.

Creating an array:

Example:

Arr=[10,20,30,40];

Arr1=[‘sushma’,’mani’,’anil’,’sowmya’]

àIndex is the position of element in an array,arrays aree zero-indexed.The elements position starts with zero and end with n-1.

Example:

Arr=[40,60,70,80]

print(arr[1])

print(arr[3])

àArrays supports negative indexing.This means the Index valuue of -1 give the last element,and -2 gives the second of last element of an array.

10

20

30

40

 

                -4                   -3                -2                -1

 

Example:

>>> arr=[67,78,34,12]

>>> print(arr[-2])

34

>>> print (arr[-4])

67

 

METHODS:

1.len():It is used to find out the length of the given array.

Example: 

>>> arr1=[12,23,34,45,56,67]

>>> print(len(arr1))

6

>>> arr2=['sushma','mani','anil','somu']

>>> print(len(arr2))

4

2.append(): To add  a new element to an array.

Example:

>>> arr1=[23,56,67,78,89,90]

>>> arr1.append(45)

>>> print arr1

[23, 56, 67, 78, 89, 90, 45]

 

3.remove():It allows us to to delete elements from an array.Similarly,we can use ‘del’ operator and pop() methods to remove elements in an array.

Example:

>>> names=['sushma','mani','anil','somu']

>>> del names[1]

>>> print names

['sushma', 'anil', 'somu']

>>> names.remove('somu')

>>> print names

['sushma', 'anil']

>>> names.pop()

'anil'

>>> print names

['sushma']

4.Modifying elements of an array:

We can change values of elements within an array using indexing and assignment operator(=).we select the position of any element using indexing and use assignment operator to provide a new value for the element.

Example:

>>> fruits=['apple','mango','grapes','guva']

>>> fruits[1]='pineapple'

>>> fruits[-1]='orange'

>>> print fruits

['apple', 'pineapple', 'grapes', 'orange']

 

Python operators to modify  elements in an array:

1.’+’ operator:It is used to concatenate(combine) two arrays.

Example:

>>> concat=[1,2,3]

>>> concat+=[4,5,6]

>>> print concat

[1, 2, 3, 4, 5, 6]

 

2.’*’ operator:It is used to repeat the elements multiple times.

Example:

>>> arr=['mani']

>>> arr=arr*5

>>> print arr

['mani', 'mani', 'mani', 'mani', 'mani']

 

Slicing an array:

It allows to access pieces of an array.This is done by using indexes separated by a colon[x:y].

Example:

>>> arr=['hcl','microsoft','oracle','sun','apple','samsung']

>>> print arr[1:4]

['microsoft', 'oracle', 'sun']

>>> print arr[0:]

['hcl', 'microsoft', 'oracle', 'sun', 'apple', 'samsung']

>>> print arr[:3]

['hcl', 'microsoft', 'oracle']

>>> print arr[-3:]

['sun', 'apple', 'samsung']

>>> print arr[-3:-1]

['sun', 'apple']

 

Creating multidimensional arrays:

It is an array within an array.This means an array holds different arrays inside it.

Example:

>>> mul=[[1,2],[2,3],[3,4],[4,5]]

>>> print mul[0]

[1, 2]

>>> print mul[3]

[4, 5]

>>> print mul[2][1]

4

>>> print mul[3][0]

4

 

Matrix representation in python:

Accessing elements of the matrix in python by using list index:

Example:

>>> a=[['mani',89,78,90,95,94],

            ['sush',100,97,92,94,88],

            ['anil',99,98,90,89,83]]

>>> print a[0]

['mani', 89, 78, 90, 95, 94]

>>> print a[0][1]

89

>>> print a[1][2]

97

 

Negative indexing in python:

Example:

>>> a=[['mani',89,78,90,95,94],['sush',100,97,92,94,88],['anil',99,98,90,89,83]]

>>> print a[-1]

['anil', 99, 98, 90, 89, 83]

>>> print a[-1][-2]

89

>>> print a[-2][-3]

92

 

Slicing a matrix in python using colon(:) and numpy:

Example:

from numpy import *

>>> a=[['mani',89,78,90,95,94],['sush',100,97,92,94,88],['anil',99,98,90,89,83]]

print(a[:3,[0,1]])

 

Changing elements of a matrix:

Example:

>>> a=[['mani',89,90,78,98,99],['sushma',90,87,86,98,97],['anil',98,90,97,96,94]]

>>> b=a[0]

>>> print b

['mani', 89, 90, 78, 98, 99]

>>> b[1]=75

>>> print b

['mani', 75, 90, 78, 98, 99]

>>> a[2]=['somu',87,84,98,92,91]

>>> print a

[['mani', 75, 90, 78, 98, 99], ['sushma', 90, 87, 86, 98, 97], ['somu', 87, 84, 98, 92, 91]]

>>> a[0][4]=95

>>> print a

[['mani', 75, 90, 78, 95, 99], ['sushma', 90, 87, 86, 98, 97], ['somu', 87, 84, 98, 92, 91]]

 

Adding a new row in the matrix in python using append():

Example:

from numpy import *

>>> a=[['mani',89,90,78,98,99],['sushma',90,87,86,98,97],['anil',98,90,97,96,94]]

a=append(a,[[‘somu’,82,79,88,97,99]],0)

print a

 

Add a new column in the matrix for economics marks using insert():

Example:

from numpy import *

>>> a=[['mani',89,90,78,98,99],['sushma',90,87,86,98,97],['anil',98,90,97,96,94]]

a=insert(a,[6],[[73],[80],[85]],axis=1)

print a

 

Adding a row with concatenation operator(+):

Example:

>>> a=[['anil',90,89,98,97,92]]

>>> a=a+[['somu',82,98,90,92,87]]

>>> print a

[['anil', 90, 89, 98, 97, 92], ['somu', 82, 98, 90, 92, 87]]

 

STRINGS

 

Python strings are immutable(not modify). In python string is enclosed with single and double quotes.

·        Strings are stored as individual characters in a contiguous memory location.

·        The benefit of using string is that it can be accessed from both the directions in forward  and backward.

1.   Forward indexing starts with 0,1,2,3…

2.   Backward indexing starts with -1,-2…….

String operators are 3 types:

1.Basic operators:

There are 2 types of basic operators

1.”+”(concatenation operator):It concatenate two strings and forms a new string.

2.”*” operator(Replication operator): It is used to repeat a string number of times.

It uses two parameters for operations.

One is integer value and the other one is string.

Eg1:”alla”+”sushma”

Eg2:5*”sushma”

4*’17’

 

 

2.Membership operator:

There are two types of membership operators:

a)in:it return true if a character or the entire substring is present in the specified string,otherwise false.

b)not in:it return true if a character or entire substring does not exist in the specified string,otherwise false.

Eg:>>>str1=”sushma”

>>>str2=”sss”

>>>str3=”sush”

>>>str4=”mmm”

>>>str2 not in str1

>>>str3 in str1

>>>str4 not in str1

 

3.Relational operators:(<,>,<=,>=,==,!=,<>)

The strings are compared based on the ASCII value or Unicode(dictionary order).

Eg:

>>>”sushma”==”sushma”

>>>”Mani”>=”mani”

 

Slice Notation:

It can be defined as substring which is the part of string.Therefore further substring can be obtained from a string.

Syntax:

<string_name>[startindex:endindex]

<string_name>[:endIndex]

<string_name>[startIndex:]

Eg:

>>>str=”manikumar”

>>>str[0:6]àmaniku

>>>str[3:6]àiku

>>>str[:5]àmanik

>>>str[2:]ànikumar

 

String methods:

1.capitalize():It capitalizes the first character of the string.

Eg:

>>>”manikumar”.capitalize()

2.count(string,begin,end):Counts no of times substring occurs in a string between begin and and end index.

Eg:

msg=”Welcome to datapro”;

substr1=”m”;

print(msg.count(substr1,4,16))à1

substr2=”a”

print (msg.count(substr2))à2

3.endswith(suffix,begin=0,end=n):returns a Boolean value if the string terminates With given suffix between begin and end.

Eg:

string1=”Datapro private limited”;

substring1=”solution”;

substring2=”private limited”

print(string1.endswith(substring1));àfalse

print (string1.endswith(substring2,3,26));àtrue

4.find(substring,beginIndex,endIndex):It returns the index value of the string where Substring is found between begin index and End index.

Eg:

str=”welcome to datapro”;

substr1=”come”;

substr2=”datapro”;

print (str.find(substr1));à3

print (str.find(substr2));à12

print (str.find(substr2,25));à12

5.index(substring,beginIndex,endIndex):same as find() except it raises an exception,If string is not found.

Eg:

str=”welcome to datapro”;

substr1=”datapro”;

print str.index(substr1);

print str.index(substr1,26);

 

6.isalnum():It returns true if characters in the string are alphanumeric i.e.,

Alphabets or numbers and there is atleast 1 character.otherwise It returns false.

Eg:

str="welcome to datapro”;

print(str.isalnum());àfalse

str1=”datapro123”;

print(str1.isalnum());àtrue

7.isalpha():It returns true when all the characters are alphabets and there is atleast one character,otherwise false.

Eg:

string1=”helloworld”;

print (string1.isalpha());àtrue

string2=”python2.3.4”;

print(string2.isalpha());àfalse

8.isdigit():It returns true if all the characters are digits and there is atleast one character,otherwise false.

Eg:

string1=”helloworld”;

print (string1.isdigit());àfalse

string2=”45465454”;

print(string2.isdigit());àtrue

9.islower():It returns true if the characters of a string are in lower case,otherwise false.

Eg:

string1=”SUSHMA”;

print (string1.islower());àfalse

string2=”sushma”;

print(string2.islower());àtrue

 

10.isupper():It returns true if character of a string are in upper case,otherwise false.

Eg:

string=”welcome”;

print(string.isupper());àfalse

string1=”WELCOME”

print(string1.isupper());àtrue

11.isspace():It returns true if the characters of a string are whitespace,otherwise false

Eg:

string=” “;

print(string.isspace());àtrue

string1=”hello world”;

print(string1.isspace());àfalse

12.len(string): It returns the length of the string.

Eg:

string=” “;

print (len(string1));à1

string2=”hello world”;

print(len(string2));à11

13.lower():It converts all the characters of a string to lower case.

Eg:

string=”SUSHMA”;

print(string.lower());àsushma

14.upper():It converts all the characters of a string to upper case.

Eg:

string=”sushma”;

print(string.upper());àSUSHMA

15.startswith(str,begin=0,end=n):Returns a Boolean value if the string starts with given str between begin and end.

Eg:

string1=”welcome india”;

print(string1.startwith(“welcome”));àtrue

string2=”welcome”;

print(string2.startwith(‘come’,3,7));àfalse

16.swapcase(): Inverts case of all characters in a string.

Eg:

string=”Hello World”;

print(string.swapcase());àhELLO wORLD

17.lstrip():Remove all leading whitespaces of a string.It can also be used to remove particular character from leading.

Ex:

string1=”      hello world”;

print(string1.lstrip());àhello world

string2=”%%%%hello world”;

print(string2.lstrip(‘%’));àhello world

18.rstrip():Remove all trailing white spaces of a string.It can also be used to remove particular character from trailing.

Eg:

string1=”hello world       “;

print(string1.rstrip());

string2=”hello world@@@@@@”;

print(string2.rstrip(‘@’));

 

String Template class in Python:

Here, Template class allows us to create simplified syntax for output specification. The format uses placeholder names formed by ‘$’ with python identifiers(alphanumeric characters and underscores). Writing  ‘$$’ creates a single escaped ‘$’.

Example:

>>> from string import Template

>>> t=Template('x is $x')

>>> print(t.substitute({'x':4}))

x is 4

 

Note:

substitute():It raises a keyError when a placeholder is not supplied in a dictionary (or) a keyword argument.

safe_substitute():It will leave placeholders unchanged if data is missing.

 

Example:

>>> from string import Template

>>> student=[('sushma',87),('somu',90),('anil',97)]

>>> t=Template('hi $name, you have got $marks marks')

>>> for i in student:

          print(t.substitute(name=i[0],marks=i[1]))

 

output:     

hi sushma, you have got 87 marks

hi somu, you have got 90 marks

hi anil, you have got 97 marks

 

String formatting in python using %:

The formatting using ‘%’ is similar to that of ‘printf’ in c-programming.

%d-integer

%f-float

%s-string

%x-hexadecimal

%o-octal

 

Example:

variable='15'

string="value as string=%s"%(variable)

print(string)

print("value as raw data=%r"%(variable))

variable=int(variable)

string="variable as integer=%d"%(variable)

print(string)

print("variable of float=%f"%(variable))

print("variable as hexadecimal=%x"%(variable))

print("variable as octal=%o"%(variable))

output:

value as string=15

value as raw data='15'

variable as integer=15

variable of float=15.000000

variable as hexadecimal=f

variable as octal=17

DOCStrings:

It provide a convenient way of associating documentation with modules,functions,classes and methods.

Rules:

·        The docstrings line should begin with a capital letter and end with a period.

·        The first line should be a short description.

·        If there are more lines in the documentation strings, the second line should be blank, visually separating the summary from the rest of the description.

àdocstrings are declared using “””triple double quotes”””. All functions should have a docstrings.

àdocstrings can be accessed using the __doc__ method of the object using the help function.

 

Example:

def my_function():

    """ docstrings does nothing really"""

    return None

print("using __doc__:")

print(my_function().__doc__)

print("using help:")

help(my_function()) 

output:

using __doc__:

None

using help:

Help on NoneType object:

 

class NoneType(object)

 |  Methods defined here:

 | 

 |  __bool__(self, /)

 |      self != 0

 | 

 |  __new__(*args, **kwargs) from builtins.type

 |      Create and return a new object.  See help(type) for accurate signature.

 | 

 |  __repr__(self, /)

 |      Return repr(self).

 

One-line Docstrings:

These docstrings are fit in one line.The closing quotes are on the same line as the opening quotes.This looks better for one-lines.

Example:

def pow(a,b):

    """ returns arg1 raised to power arg2."""

 

    return a**b

print(pow.__doc__)  

output:

returns arg1 raised to power arg2.

Multi-line Docstrings:

It consists of a summary line just like a one-line docstring, followed by a blank line,followed by a more colabrate description.The summary line may be on the same line as the opening quotes (or) on the next line.

Example:

def my_fun(arg1):

    """

     Summary line

 

     extended description of function

 

     Parameters:

     arg1(int):description of arg1

 

     returns:

     int:Description of return value

   """

    return arg1

print(my_fun.__doc__)

 

Docstrings using classes:

Example:

class ComplexNumber:

      """

      This is a class for mathematical operations on complex numbers.

 

      Attributes:

      real(int):The real part of complex number.

      imag(int):The imaginary part of complex  number.

 

      """

      def __init__(self,real,imag):

          """

 

          Constructor created.

 

          paramaters:

          real(int)

          imag(int)

          """

      def add(self,num):

        

         """

         To add complex numbers.

 

         Parameters:

         num(ComplexNumbers):The complex number to be added.

 

         Returns:

         ComplexNumber:A complex number which contain the sum

         """

         re=self.real+num.real

         im=self.imag+num.imag    

         return ComplexNumber(re,im)

help(ComplexNumber)#to access class docstrings

help(ComplexNumber.add)#to access methods docstrings.

 

 

 

 

FUNCTIONS

A function is a self block of code.A function can be called as a section of a program that is written once and can be executed whenever required in the program,thus making code reusability.

One way to categorize functions in Python is:

1. Built-in functions: these functions pre-defined and are always available.

2. Functions defined in modules: these functions are pre-defined in particular modules and can only be used when the corresponding module is imported.

 3. User defined functions: these are defined by the programmer.

Types of Built-in-function:

·        Math functions: abs(x), round(x, n) 

·        Type conversion functions:bool(x), float(x), int(x), long(x), str(x)

·        Input functions: raw_input(x), input(x)

Defining a function:

Keyword def is used to start the function definition.Def specifies the starting of fuction block.

Syntax:

def <function_name>([parameters]):

</function_name>

Example:

def sum(a,d):

 

Example:

def example():

print(‘basic function’)

z=3+10

print(z)

 

FUNCTION PARAMETERS PRG:

 

def simple_addition(num1,num2):

answer=num1+num2

print(“num1 is”,num1)

print(“num2 is”,num2)

print(answer)

simple_addition(5,3)

 

return statement:

It is used to send back the control to the caller with the expression.

In case no expression is given after return it will return none.

 

Example:

def return_sum(x,y):

    c=x + y

    return c

res=return_sum(4,5)

print(res)

Anonymous Function:

Anonymous functions are the functions that are not bond to name.

Anonymous functions are created by using a keyword “lambda”.

Lambda takes any number of arguments and returns an evaluated expression.

Lambda is created without using the def keyword.

Syntax:

Lambda arg1,arg2,arg3,?,argsn:expression

Example:

double=lambda x:x*2

print(double(5))

 

 

MATHEMATICAL FUNCTIONS

NUMERIC FUNCTIONS:

1.ceil():

This funtion returns the smallest intergral value greater than the number .If number is already interger,same number is returned.

2.Floor():

It returns greatest intergral value smaller than the number is returned.

Egs:

Import math

>>>a=2.345

>>>print(math.ceil(a))à3

>>>print(math.floor(a))à2

3.fabs():

It returns absolute value of the number

4.factorial():

It returns the factorial of the number.An error message is displayed if number is not integral.

Eg:

import math

a=-10

b=5

print(math.fabs(a))à10.0

print(math.factorial(b))à120

5.copysign(a,b):

It returns the number with value of “a” but the sign of “b”.the returned value is float type.

6.gcd():It is used to compute the greatest common divisor of 2 number mentioned in its arguments.

Eg:

import math

A=-10

B=5.5

C=15

D=5

Print(math.copysign(5.5,-10))à-5.5

Print(math.gcd(5,15))à5

LOGARTHMIC AND POWER FUNCTIONS

7.Exp(a):It returns the value of raised to the power a(e**a)

8.log(a,b):

It returns the logorthimic value of “a” with base “b”.if base is not mentioned the computed value is of natural log.

Eg:

Import math

print(math.exp(4))

print(math.log(2,3))

output:

==

54.598150033144236

0.6309297535714574

9. log2(a):It computes value of log “a” with base “2”.

10.log10(a):It computes of log “a” with base “10”;

Eg:

import math

print(math.log2(16))à4.0

print(math.log10(1000))à3.0

11.pow(a,b):

It is used to compute value of “a” raised to the power “b”(a**b).

12.sqrt():

It returns the square root of the number.

Eg:

Import math

 print(math.pow(3,2))à9.0

print(math.sqrt(25))à5.0

TRIGONOMETRIC AND ANGULAR FUNCTION

13.sin():It returns the sine of value passed as argument .the value passed in this funtion should be in radians.

14.cos(): It returns the cosine of value passed as argument.

Eg:

Import math

A=math.pi/6

Print(math.sin(a))

Print(math.cos(a))

Output:

0.49999999999999994

0.8660254037844387

15.tan():it returns the tangent of value passed in arguments.

16.hypot(a,b):It returns the hypotenuse of the values passed in arguments.it returns the value of sqrt(a*a+b*b).

eg:

import math

a=math.pi/6

b=6

c=5

print(math.tan(a))

print(math.hypot(b,c))

output:

0.5773502691896257

7.810249675906654

17.degrees():

It is used to convert argument value from radians to degree.

18.radians():

It is used to convert argument value from degree to radians.

Eg:

Import math

a=mah.pi/6

b=30

print(math.degrees(a))

print(math.radians(b))

output:

29.999999999999996

0.5235987755982988

>>> 

 

 

SPECIAL FUNTIONS AND CONSTANTS

19.gamma():

It is used to return the gamma functions of the arguments

Eg:

Import math

a=10

print(math.gamma(a))à362880.0

20.pi=This is an inbuilt constant that outputs the value of pi(3.141592).

21.e:it is  an inbuilt constat that output the values of e(2.718281).

Eg:

import math

print(math.pi)

print(math.e)

Output:

3.141592653589793

2.718281828459045

22.inf:

It is a positive floating point infinity constants it is use to denote the negative floating point infinity.it is defined in python 3.5 

23.isinf():it is used to check whether the value is an infinity or not.

24. nan: This constant denoted “not a number “ in python .It is defined in python 3.5

25.isnan:It returns true if the number  is “nan” else return false

eg:

import math

>>> a=99

>>> b=-23

>>> print(math.isnan(a)));

False        

>>> print(math.isnan(b));

False

TYPE CONVERSION FUNTIONS

1.int(a,base):It converts  any data type to interger .”base” specifies the base in which string is data type is string.

2.float ():It is used to convert any data type to a floating point number.

Ex:

s=”10010”

c=int(s,2)

print(c)à18

e=float(s)

print(e)à10010.0

3.ord():It is used to convert a character to integer

4.hex():It converts integer to hexadecimal string

5.oct():This function is to convert integer to octal string.

Example:

S=”4”

c=ord(s)

print(c)à52

c=hex(56)

print(c )à0x38

c=oct(56)

print( c)à0o70

 

5.tuple():It is used to convert to a tuple.

6.set():It returns the type after converting to set.

7.list():It is used to convert any data type to a list type.

Example:

s=”mani”

c=tuple(s)

print(c )

c=set(s)

print( c)

c=list(s)

print( c)

output:

('m', 'a', 'n', 'i')

{'m', 'i', 'n', 'a'}

['m', 'a', 'n', 'i']

 

8.dict():It is used to convert a tuple of order(key,value) into a dictionary.

9.str():It used to convert integer into a string.

10.complex(real,imag):It converts real numbers to complex(real,imag) number.

Example:

a=1

b=2

tup=((‘a’,1),(‘f’,2),(‘g’,3))

c=complex(1,2)

print( c)

c=str(a)

print( c)

c=dict(tup)

print( c)

output:

(1+2j)

1

{'a': 1, 'f': 2, 'g': 3}

 

OOPS CONCEPTS IN PYTHON

 

Major principles of object-oriented programming system are given below:

·        objects and classes

·        Method

·        Inheritance

·        Polymorphism

·        Data abstraction

·        Encapsulation

Object:

An object is a instance of class.

(or)

An object is anything that exists physically in the real world.it contains variables and methods.

 

Class:

A class is a model or plan for creating objects.

(Or)

A class represents common behavior of group of objects.

Syntax:

class  className:

<statement-1>

………….

………….

<statement-n>

Example:

class person:

          def  name(self):

                   print("this is sushma")

          def company(self):

                   print("datapro private limited")

p=person()

p.name()

p.company()

Method:

Method is a function that is associated with an object.In python,method is not unique to class instance.Any object type can have methods.

 

Inheritance:

Creating a new class from already existing class is called Inheritance.

Reusability of code is main advantage in inheritance.

 

Polymorphism:

Poly means many, morphism means forms.It is derived from latin and greek words.

The ability to exits in many froms is called polymorphism.

In programming if the same method or variable or object performs various tasks is called polymorphism.

 

Encapsulation:

Taking data and methods as a single unit is called encapsulation.

A class is an example for encapsulation.

The main advantage of encapsulation is that it is possible to use same names for the members of two different classes.

 

Abstraction:

It means hiding of data

Hiding of unnecessary data from the user is called abstraction.

It is used to hide internal details and show only functionalities.

 

Class method vs static method in Python:

Class Method:

It receives the class as implicit first argument,just like an instance method receives the instance.

Syntax:

Class c(object):

        @classmethod

        def fun(cls,arg1,arg2,-----):

         -------------

àA class method is a method which is bound to the class and not the object of the class.

àThey have the access to the state of the class as it takes a class parameter that points to the class  and not the object instances.

àIt can modify a class state that would apply across all the instances of the class.

 

Static Method:

It does not receive an implicit first argument.

Syntax:

Class c(object):

            @staticmethod

           def fun(arg1,arg2,……):

            -------

            --------

àIt cannot access (or) modify class state.

àIt is present in a class because it makes  sense for the method to be present in class.

 

Example:  

 from datetime import date

class Person:

 

      def __init__(self,name,age):

          self.name=name

          self.age=age

      @classmethod

      def frombirthyear(cls,name,year):

         

          return cls(name,date.today().year-year)

      @staticmethod

      def isadult(age):

          return age>18

person1=Person('sushma',21)

person2=Person.frombirthyear('sushma',1996)

print person1.age

print person2.age

print Person.isadult(22)

 

 

INTERVIEW QUESTION:

What is the difference between class method and static method?

CLASS METHOD

STATIC METHOD

1.It take class as first parameter.

1.It needs no specific parameters.

2.It can access (or) modify class state.

2.It can’t access (or) modify it.

3.we use @classmethod decorator in python to create a class method.

3.we use @staticmethod decorator to create a static method in python.

4.we use class method to create factory methods.Factory method return class object(similar to a constructor) for different use cases.

4.we generally use static methods to create utility functions.

 

 

Class (OR) Static variables in python:

These variables are shared by all objects.Instance (or) non-static variables are different for different objects.

àAll variables which are assigned a value in class declaration are class variables.

àvariables which are assigned values inside class methods are instance methods.

Example:

class Student:

      branch='mca'

      def __init__(self,name,roll):

          self.name=name

          self.roll=roll

a=Student('sushma',1)

b=Student('mani',2)

print(a.branch)

print(b.branch)

print(a.name)

print(b.name)

print(a.roll)

print(b.roll)

print(Student.branch)

 

str() vs repr()

àBoth are used to get a string representation of object.

Example for str():

>>> s='hello greeks.'

>>> print(str(s))

hello greeks.

>>> print(str(2.0/11.0))

0.18181818181818182

Example for repr():

>>> s='hello,greeks.'

>>> print(repr(s))

'hello,greeks.'

>>> print(repr(2.0/11.0))

0.18181818181818182

 

Difference between str() and repr()?

str()

repr()

1.It is used for creating output for end user.

1.It is used for debugging and development.

2.str’s is to be readable.

2.repr’s goal is to be ‘unambiguous’.

3.It is used to compute the ‘informal’ string representation of an object(printing the object).

3.It compute the ‘official’ string representation of an object(all information about the object).

4.The print statement and str() built-in function uses _str_ to display the string representation of the object.

4.repr() built-in function uses _repr_ to display the object.

 

Example:

>>> import datetime

>>> today=datetime.datetime.now()

>>> print(str(today))

2018-11-15 12:15:02.157978

>>> print(repr(today))

datetime.datetime(2018, 11, 15, 12, 15, 2, 157978)

 

Note:

 àstr() displays today’s date in a way that the user can understand the date and time.

àrepr() prints official representation of a datetime object.

 

How to make them work for our own defined classes:

A user defined class should also have a _repr_ if we needed detailed information for debugging.

Example:

class complex:

    def __init__(self,real,imag):

        self.real=real

        self.imag=imag

    def __repr__(self):

        return 'rational(%s,%s)'%(self.real,self.imag)

    def __str__(self):

        return '%s+i%s'%(self.real,self.imag)

t=complex(10,20)

print(str(t))

print(repr(t))

output:

10+i20

rational(10,20)

 

DECORATORS

In python,functions are first class objects.

àFunctions are objects , they can be referenced to, passed to a variable and returned from other functions as well.

àFunctions can be defined inside another function and can also be passed as argument to another function.

 

Definition Of Decorators:

àIt is very powerful tool in python.

àIt allows programmers to modify the behavior of functions (or) classes.

àIt allows us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it.

àHere, functions are taken as the argument into another function and then called inside the wrapper function.

Example:

@gfg_decorator

def h_decorator():

     print(‘gfg’)

 

Note:

àgfg_decorator is a callable function, will add some code on the top of another callable function.

àh_decorator can return the wrapper function.

 

Example:Decorator can modify the behaviour

def h_decorator(func):#step-2

    def inner1():#step-3,step-6

        print("this is before function execution")#step-7

        func()#step-8

        print("after function execution")#step-11

    return inner1#step-4

def fun_to_be_used():#step-9

    print("inside the function!!!")#step10

fun_to_be_used=h_decorator(fun_to_be_used)#step-1

fun_to_be_used()#step-5,step-12

output:

this is before function execution

inside the function!!!

after function execution

 

Example:Find out execution time of function using decorator

import time

import math

def cal_time(func):

    def inner(*args,**kwargs):

        begin=time.time()

        func(*args,**kwargs)

        end=time.time()

        print("time taken:",func.__name__,end-begin)

    return inner

@cal_time

def fact(num):

    time.sleep(4)

    print(math.factorial(num))

fact(9)

output:

362880

time taken: fact 4.050818920135498

Example:function returning values

def h_dec(func):

    def inner(*args,**kwargs):

        print("before execution")

        returned_val=func(*args,**kwargs)

        print("after execution")

        return returned_val

    return inner

@h_dec

def sum(a,b):

    print("inside the function")

    return a+b

a,b=34,45

print("sum=",sum(a,b))

output:

before execution

inside the function

after execution

sum= 79

 

Example:

def attach_data(func):

    func.data=3

    return func

@attach_data

def add(x,y):

    return x+y

print(add(23,64))

print(add.data)

output:

==

87

3

 

Class attributes:

It belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility.

Example:

class sampleclass:

    count=0

    def increase(self):

        sampleclass.count+=1

s1=sampleclass()

s1.increase()

print(s1.count)

s2=sampleclass()

s2.increase()

print(s2.count)

print(sampleclass.count)

output:

1

2

2

Instance attributes:

àThese are not shared by objects.

àEvery object has its own copy of the instance attribute.

Attributes of an instance:

1.var():

It displays the attributes of an instance in the form of an dictionary.

2.dir():

It displays more attributes than various functions,as it is not limited to instead to instances. It displays the class attributes as well.

Example:

class stu:

    def __init__(self):

        self.name='manikumar'

        self.branch='CSE'

    def display(self):

        print(self.name)

        print(self.branch)

s1=stu()

print("dictionary form:",vars(s1))

print(dir(s1))

output:

dictionary form: {'name': 'manikumar', 'branch': 'CSE'}

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'branch', 'display', 'name']

 

 

 

 

 

CONSTRUCTORS

 

·        A constructor is a special type of method that is called when it instantiates an object using the definition found in the class.It is normally used to initialize to the instance variables.

·        It is class function that begins with double underscore(__).The name of the constructor is always same __init__().

·        While creating an object,a constructor can accept arguments if necessary.

 

Example:

class cName:

    count=0

    def __init__(self,name,age):

        self.name=name

        self.age=age

        cName.count+=1

    def display(self):

        print "name:",self.name

        print "age:",self.age

    def totalco(self):

        print "total names %d" % cName.count

 

c1=cName("sam",24)

c2=cName("raghav",27)

c1.display()

c1.totalco()

c2.display()

 

 

 

 

 

 

INHERITANCE

 

Deriving a new class from already existing class is called inheritance.

The already existing class is called base class or parent class or super class.

The newly created class is called derived class or child class or sub class.

We always create an object to sub class (or) derived class only

Syntax:

Class DerivedClassName(BaseClassName):

<statement-1>

………………

………………

<statement-n>

Example:

class person:

    def __init__(self,first,last):

        self.firstName=first

        self.lastName=last

    def getName(self):

        return self.firstName+ " " +self.lastName

class Employee(person):

    def __init__(self,first,last,staffNum):

        person.__init__(self,first,last)

        self.staffNum=staffNum

    def getEmployee(self):

        return self.getName()+ " : " +self.staffNum

class Boss(person):

    def __init__(self,first,last,title):

        person.__init__(self,first,last)

        self.title=title

    def getBoss(self):

        return self.getName()+ ": Employee ID: "+self.title

 

person_1=person("sushma","alla")

Employee_1=Employee("sushma","alla","345")

Employee_2=Employee("mani","kumar","63")

Boss_1=Boss("allasushma","mani.com","CEO")

 

print(person_1.getName())

print(Employee_1.getEmployee())

print(Employee_2.getEmployee())

print(Boss_1.getBoss())

 

Multilevel Inheritance:

 

You can inherit a derived class from another derived class.

Example:

class person:

    def display(self):

        print("hello,this is class person")

class employee(person):

    def printing(self):

        print("hello,this is derived class")

class programmer(employee):

    def show(self):

        print("hello,this is another derived class")

 

p1=programmer()

p1.display()

p1.printing()

p1.show()

Multiple inheritance:

Deriving a child class from more than one base class is called multiple inheritance.

 

Syntax:

Class DerivedClassName(Base1,Base2,Base3):

<statement-1>

…………..

…………..

<statement-n>

 

Or

class Base1:

pass

class Base2:

pass

class MultiDerived(Base1,Base2):

pass

 

Example:

class land_animal:

    def printing(self):

        print("this animal lives on land")

class water_animal:

    def display(self):

        print("this animal lives in water")

class frog(land_animal,water_animal):

    pass

f1=frog()

f1.printing()

f1.display()

       

Method Overriding:

One or more methods with same name,same parameters is called method overriding.

Example:

class parent():

    def __init__(self,last_name,eye_color):

        print("parent constructor called")

        self.last_name=last_name

        self.eye_color=eye_color

    def show_info(self):

        print("last name-"+self.last_name)

        print("eye color-"+self.eye_color)

 

class child(parent):

    def __init__(self,last_name,eye_color,number_of_toys):

        print("child constructor called")

        parent.__init__(self,last_name,eye_color)

        self.number_of_toys=number_of_toys

 

    def show_info(self):

         print("last name-"+self.last_name)

         print("eye color-"+self.eye_color)

         print("number of toys-"+str(self.number_of_toys))

 

billy_cyrus=parent("sush","pink")

miley_cyrus=child("sush","pink",6)

miley_cyrus.show_info()

 

       

 

POLYMORPHISM

 

Polymorphism means “many forms”.

Polymorphism simply means that we can call the same method name with parameters,and depending on the parameters,it will do different things.

 

Example:

class Car:

    def __init__(self, name):   

        self.name = name

 

    def drive(self):            

        raise NotImplementedError("Subclass must implement abstract method")

 

    def stop(self):            

        raise NotImplementedError("Subclass must implement abstract method")

 

class Sportscar(Car):

    def drive(self):

        return 'Sportscar driving!'

 

    def stop(self):

        return 'Sportscar breaking!'

 

class Truck(Car):

    def drive(self):

        return 'Truck driving slowly because heavily loaded.'

 

    def stop(self):

        return 'Truck breaking!'

 

 

cars = [Truck('Bananatruck'),

        Truck('Orangetruck'),

        Sportscar('Z3')]

 

for car in cars:

    print car.name + ': ' + car.stop()

 

Metaprogramming with metaclasses

 

àIn nutshell we can say metaprogramming is code which manipulates code.

Example for metaclasses:

>>> num=345

>>> print("type of num:",type(num))

type of num: <class 'int'>

>>> lst=[3,4,5]

>>> print("list type:",type(lst))

list type: <class 'list'>

>>> name="manikumar"

>>> print("type of name:",type(name))

type of name: <class 'str'>

Note:

In python,object of int class (or) str class, so we can make a new type by creating a class of that type.

 

Example:

class student:

    pass

stu=student()

print("type of object:",type(stu))

output:

type of object: <class '__main__.student'>

Metaclasses:

àA class is also an object, and just like any other object it’s instance of something called metaclass.

àA special class ‘type’ creates these class object.

àThe ‘type’ class is defined default metaclass which is responsible for making classes.

Example:

class student:

    pass

print("type of stu class:",type(student))

output:

type of stu class: <class 'type'>

Note:

Classes are also an object, they can be modified in same way. We can add (or) substract fields (or) methods in class in same way we did with other objects.

 

Example:

class test:pass

test.x=45

test.foo=lambda self:print('hello')

obj=test()

print(obj.x)

obj.foo()

output:

45

Hello

 

When to use metaclasses:

àIt propogate down the inheritance hierarchies.

àIf we want to change classes automatically.

àIt is used for API developers.

 

Custom metaclasses:

àcustom metaclasses have to inherit type metaclasses and usually override

·        __new__():This method which is called before __init__().It creates the object and return it.

·        __init__():It initialize the created object passed as parameter.

àWe can create classes using type() function directly in following ways:

1.When called with only one argument, it returns the type. We have seen it before in above examples.

2.When called with 3 parameters, it creates a class.Following arguments are passed are passed to it.

·        Class name

·        Tuple having base classes inherited by class

·        Class Dictionary

Example:

def t_method(self):

    print("test class method!")

class Base:

    def myfun(self):

        print("inherited method!")

Test=type('Test',(Base, ),dict(x='sushma',my_method=t_method))

print("type of test class:",type(Test))

test_obj=Test()

print("Type of test_obj:",type(test_obj))

test_obj.myfun()

test_obj.my_method()

print(test_obj.x)

output:

type of test class: <class 'type'>

Type of test_obj: <class '__main__.Test'>

inherited method!

test class method!

sushma

                  

 

 

 

LISTS

 

·        Lists are the data structures that is capable of holding different type of data.

·        It is mutable(modify) i.e., python  will not create a new list if we modify an element in the list.

·        Different operations like insertions and deletions can be performed on lists.

·        It is enclosed between square brackets “[ ]”.

·        The elements are stored in the index basis with starting index as 0.

 

Example:

data=[‘I’,’n’,’d’,’I’,’a’];

data1=[“mani”,”sushma”];

Prg:

data1=[1,2,3,4];

data2=[‘x’,’y’,’z’];

print data1[0]à1

print data1[0:2]à1,2

print data1[0:]à1,2,3,4

print data2[:2]àx,y

 

List Operations:

1.Adding Lists:

Lists can be added by using the concatenation operator(+) to join two lists.

Example:

list1=[“sushma”,”alla”]

list2=[“mani”,”kumar”]

list3=list1+list2

print list3à[“sushma”,”alla”,”mani”,”kumar”]

 

2.Replicating lists:

It means repeating.It can be performed by using ‘*’ operator by a specific number of times.

Example:

list1=[‘x’,’y’]

Print list1*2

 

3.List slicing:

A subpart of a list can be retrieved on the basis of index.This subpart is known  as list slice.

Example:

list1=[10,20,30,40]

print list1[3]

list1[2]=60

print list1

 

Other operations:

1.Updating elements in a list:

To update or change the value of particular index of a list,assign the value to that particular index of the list.

Syntax:

<list_name>[index]=<value>

Example:

data1=[34,56,78,89,90]

print “values of list are:”

print data1

data1[3]=”20”

print “value of list are:”

print data1

 

2.Appending elements to the list:

This method is used to add n element at the end of the existing elements.

Syntax:

<list_name>.append(item)

Example:

list1=[“sushma”,”manikumar”]

print “elements in the list are:”

print list1

list1.append(“sowmya”)

print “list after appending:”

print list1

 

3.Deleting elements from the list:

It is used to delete an element from the list.It can also be used to delete all items from startIndex to endIndex.

Example:

list1=[45,”sushma”,’mani’,67,89]

del list1[4]

print list1

del list1[0:5]

print list1

Functions and methods of lists:

1.min(list):returns the minimum value from the list given.

Example:

list=[“sushma”,”mani”,45,78]

Print “minimum value in list:”,min(list)

 

2.max(list):Returns the largest value in the given list.

Example:

list=[“sushma”,”mani”,45,78]

print “maximum value in list:”,max(list)

 

3.len(list):It returns number of elements in a list.

Example:

 

list=[“sushma”,”mani”,45,78]

print “no of elements in the list:”,len(list)

 

Built in methods in lists:

1.index(object):Returns the index value of the object.

Example:

data=[“sushma”,”mani”,56,78,90]

Print “index of 78:”,data.index(78)

 

2.count(object):It returns the number of times an object is repeated in list.

Example:

data=[67,78,90,67,34,67]

data.count(67)

 

3.pop()/pop(index):Returns the last object or the specified indexed object.It removes the popped object.

Example:

data=[786,’sushma’,’mani’,45,78]

data.pop()

data.pop(5)

print data

 

4.insert(index,object):Insert an object at the given index.

Example:

data=[‘sushma’,’mani’,89,90]

data.insert(2,”world”)

print data

 

5.extend(sequence):It adds the sequence to existing list.

Example:

data1=[23,34,45]

data2=[89,90]

data1.extend(data2)

print data1

 

6.remove(object):It removes the object from the given list.

Example:

data=[“sushma”,”mani”,”sowmya”,”sandhya”]

data1.remove(“sandhya”)

print data1

 

 

7.reverse():Reverse the position of all the elements of a list.

Example:

list1=[10,20,30,40,50]

list1.reverse()

print list1

 

8.sort():It is used to sort the elements of the list.

Example:

list1=[“sushma”,”mani”,34,12]

list1.sort()

print list1

 

TUPLE

 

A tuple is a sequence of immutable objects, therefore tuple cannot be changed.

Tuple is similar to list.

 

Example:

data1=(10,20,30,40)

print data1[0]à10

print data1[0:2]à10,20

print data1[-3:-1]à40,30

print data1[0:]à10,20,30,40

 

Tuple Operations:

1.AddingTuple:It can be added by using the concatenation operator(+) to join two tuples.

Example:

data1=(20,30,”sushma”)

data2=(‘3’,’4’,’5’)

data3=data1+data2

print data1

print data2

print data3

 

2.Replicating tuple:

It means repeating.It can be performed by using ‘*’ operator by a specific number of times.

Example:

tuple1=(3,4,5);

tuple2=(6,7,8);

print tuple1*2à(3,4,5,3,4,5)

print tuple2*3à(6,7,8,6,7,8,6,7,8)

 

3.Tuple slicing:A subpart of a tuple can be retrieved on the basis of index.This subpart is known as tuple slice.

Example:

data1=(20,30,40,60)

print data1[0:2]

print data1[4]

print data1[:-1]

 

Other operations:

1.Updating elements in a tuple:

Elements of the tuple cannot be updated.This is due to the fact that tuples are immutable. Whereas the tuple can be used to form a new tuple.

Example:

data=(‘h’,’j’,’v’,’r’)

data[0]=’a’

print data

 

 

2.Deleting elements from tuple:

Deleting individual element from a tuple is not supported.However the whole of the tuple can be deleted using the del statement.

Example:

data=(10,20,”sushma”,45.678)

print data

del data

print data

Functions of Tuple:

1.min(tuple):Returns the minimum value from a tuple.

Example:

data=(10,’e’,6,9)

print min(data)

 

2.max(tuple):Returns the maximum value from the tuple.

Example:

data=(45,67,’sushma’,’t’)

print max(data)

3.len(tuple):Gives the length of a tuple.

Example:

data=(10,30,34,56,23,12,12)

print len(data)

 

4.cmp(tuple1,tuple2):Compare the two tuples.

Explanation:If elements are of the same type, perform the comparison and return the result.If elements are different types, check whether they are numbers.

 

·        If numbers, performs comparison.

·        If either element is a number, then the other element is returned.

·        Otherwise, types are sorted alphabetically.

·        If we reached the end of one of the lists,the longer list is “larger”. If both list are same it returns 0.

 

Example:

data1=(10,30,’sushma’,90,78)

data2=(20,10,’mani’,45.67)

print  cmp(data1,data2)

print cmp(data2,data1)

data3=(20,10,’mani’,45.67)

printcmp(data2,data3)

 

5.tuple(sequence):converts the sequence into tuple.

Example:

dat=[‘mani’,’kumar’,’sush’]

data=tuple(dat)

print data

 

uses of tuples:

1.Processing of tuples are faster than lists.

2.It makes the data safe as tuples are immutable and hence cannot be changed.

3.Tuples are used for string formatting.

 

 

PYTHON DICTIONARY

 

·        It is an unordered set of key and value pair.

·        It is an container that contains data,enclosed within curly braces.

·        The pair i.e.,key and value is known as item.

·        The key passed in the item must be unique.

·        It is known as “Associative array”.

·        It is mutable(modify) i.e., value can be updated.

·        Value can be updated while key cannot be changed.

 

Example:

name={}

name[1]=’charan’

name[2]=’manikumar’

name[‘name1’]=’sowmya’

name[4]=’tulasi’

print(name[2])àmanikumar

print(name[‘name1’])àsowmya

print(name[1])àcharan

print(name)

 

Accessing values:

A Dictionaries value can be accessed by their keys.

Syntax:

[key]

 

Example:

data1={‘id’:101,’name’:’sushma’,’profession’:’software trainer’}

data2={‘id’:102,’name’:’mani kumar’,’profession’:’software developer’}

data1[‘id’]à101

data2[‘id’]à102

data2[‘name’]àmanikumar

 

Updation:

The item i.e., key-value pair can be updated.Updating means new item can be added.The values can be modified.

Example:

data1={‘id’:101,’name’:’sushma’,’profession’:’software trainer’}

data2={‘id’:102,’name’:’mani kumar’,’profession’:’software developer’}

data1[‘profession’]=’manager’

data2[‘salary’]=40000

print data1

print data2

 

Deletion:

Del statement is used for performing deletion operation.

An item can be deleted from a dictionary using the key.

Syntax:

Del[key]

Example:

data1={‘id’:101,’name’:’sushma’,’profession’:’software trainer’}

del data1[‘profession’]

print data1

del data1

print data1

FUNCTIONS:

1.len(dictionary):Gives number of items in a dictionary.

 

Example:

data1={‘id’:101,’name’:’sushma’,’profession’:’software trainer’}

print data

print len(data)

 

2.cmp(dictionary1,dictionary2):Compares the two dictionaries.

If, dictionary1==dictionary2,returns 0

dictionary1<dictionary2,returns -1

dictionary1>dictionary2, returns 1

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

data2={103:’charan’,104:’kalyan’,105:’santhosh’}

print cmp(data1,data2)

 

3.str(dictionary):Gives the string representation of a string.

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

print str(data1)

 

METHODS:

1.keys():Return all the keys element of a dictionary.

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

print data1.keys()

 

2.values():Return all the values element of a dictionary.

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

print data1.values()

 

3.items():Returns all the items(key-value pair) of a dictionary.

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

print data1.items()

 

4.update(dictionary2):It is used to add items of dictionary2 to first dictionary.

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

data2={104:’charan’}

data1.update(data2)

print data1

 

5.clear():It is used to remove all items of a dictionary.It returns an empty dictionary.

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

print data1

data1.clear()

print data1

 

6.fromkeys(sequence,value1)/fromkeys(sequence):It is used to create a new dictionary from the sequence where sequence elements forms the key and all keys share the values? Value1?.In case value1 is not given,it set the values of keys to be none.

Example:

sequence=(‘id’,’number’,’email’)

data={}

data1={}

data=data.fromkeys(sequence)

print data

data1=data1.fromkeys(sequence,100)

print data1

 

7.copy(): It returns an ordered copy of the data.

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

data2=data1.copy()

print data2

 

8.has_key(key):It returns a Boolean value.True in case if key is present in the dictionary,else false.

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

print data1.has_key(103)

print data1.has_key(‘profession’)

 

9.get(key):Returns the values of the given key.If key is not present it returns none.

Example:

data1={100:’sushma’,102:’mani kumar’,103:’anil’}

print data.get(102)

print data.get(‘name’)

 

SETS

 

It is an unordered collection of item.sets are immutable(not modifyable).sets will not  store duplicate elements.Sets  are created by placing all the elements inside curly braces({}).

 

Example-1:

>>> set1={1,2,3}

>>> print(set1)

{1, 2, 3}

>>> set2={12.34,"anil",(1,2,3)}

>>> print(set2)

{'anil', 12.34, (1, 2, 3)}

>>> set3=set([4,5,6,7])

>>> print(set3)

{4, 5, 6, 7}

>>> 

 

Example-2:

>>> a={}

>>> print(type(a))

<class 'dict'>

>>> a=set()

>>> print(type(a))

<class 'set'>

 

Methods:

1.add():It add single element in the sets.

Example:

>>> set={1,3}

>>> set.add(2)

>>> print(set)

{1, 2, 3}

 

2.update():This method can take tuples,lists,strings (or) other sets as its arguments.

Example:

>>> set1={67,78,89}

>>> set1.update([12,13,14])

>>> print(set1)

{67, 12, 13, 78, 14, 89}

 

3.union(s):

It return a union of two sets. Using OR operator between 2 sets is the same as   writing set1.union(set2).

Example:

>>> names={'sushma','mani','keerthi'}

>>> desg={'software','software','student'}

>>> employee=names.union(desg)

>>> print(employee)

{'sushma', 'keerthi', 'mani', 'student', 'software'}

 

4.intersect():

It returns an interaction of two setts. The ‘&’ operator  comes can also be used in this case.

Example:

Victims=people.intersection(vampires)

5.difference():

It returns a set containing all the elements of  invoking set not of the second set.we can use ‘-‘operator here.

6.clear():

Empties the whole set.

 

Note:

àsets doesnot maintain elements in any particular order.

àonly instances of immutable types can be added to a python set.

 

FROZEN SET:

These are immutable objects that only support methods and operators that produce a result without affecting the frozenset (or) sets to which they are applied.

Example:

>>> set1=set(['a','b','c','d'])

>>> set1.add('d')

>>> print("normal set")

normal set

>>> print(set1)

{'c', 'b', 'a', 'd'}

>>> set2=frozenset(['e','f','g'])

>>> print("frozenset")

frozenset

>>> print(set2)

frozenset({'e', 'g', 'f'})

 

Operators:

1.key in s(#containment check)

2.key not in s(non-containment check)

3.s1==s2(s1 is equivalent to s2)

4.s1!=s2(s1 is not-equivalent to s2)

5.Relational operators

·        Case-1:s1 is subset of s2(s1<s2)

·        Case-2:s1 is proper subset of s2(s1>=s2)

·        Case-3:s1 is proper superset of s2(s1<=s2)

·        Case-4:s1 is proper superset of s2

6.s1|s2(the union of s1 &s2)

7.s1&s2(the intersection of s1&s2)

8.s1_s2(the set of elements in s1 but not s2)

9.s1^s2(the set of elements in precisely one of s1 (or) s2)

 

Example:

set1=set()

set2=set()

for i in range(1,6):

    set1.add(i)

for i in range(3,8):

    set2.add(i)

print("set1=",set1)

print("set2=",set2)

print("\n")

 

set3=set1|set2

print("union of set1&set2:set3=",set3)

 

set4=set1&set2

print("intersection of set1&Set2:set4=",set4)

print("\n")

 

if set3>set4:

    print("set3 is superset of set4")

 

elif set3<set4:

    print("set3 is subset of set4")

else:

    print("set3 is same as set4")

 

if set4<set3:

    print("set4 is subset of set3")

    print("\n")

 

set5=set3-set4

print("elements in set3 and not in set4:set5=",set5)

print("\n")

 

if set4.isdisjoint(set5):

    print("set4 and set5 have nothing in common\n")

set5.clear()

print("after applying clear on set5:")

print("set5=",set5)

 

output: 

set1= {1, 2, 3, 4, 5}

set2= {3, 4, 5, 6, 7}

 

 

union of set1&set2:set3= {1, 2, 3, 4, 5, 6, 7}

intersection of set1&Set2:set4= {3, 4, 5}

 

 

set3 is superset of set4

set4 is subset of set3

 

 

elements in set3 and not in set4:set5= {1, 2, 6, 7}

 

 

set4 and set5 have nothing in common

 

after applying clear on set5:

set5= set()

 

   

 

   

 

 

 

 

PYTHON DATE AND TIME

 

It helps to retrieve current date and time and manipulation using buit-in methods.

Methods in time module:

1)Retrieving Time:

To retrieve time,python provides pre-defined function localtime(), it receives a parameter time.

time() is a function that returns the current system time in number of ticks since 12:00 am,January 1st,1970.

Time() function contains 9 attributes

 

ATTRIBUTES

DESCRIPTION

tm_year

It returns the current year

tm_mon

It returns current month

tm_mday

It returns the current month day

tm_hour

It returns the current hour

tm_min

It returns current minute

tm_sec

It returns the current seconds

tm_wday

It returns the week day

tm_yday

It returns the year day

tm_isdst

It returns -1,0 (or) 1.

 

Example:

>>>import time

>>> localtime=time.localtime(time.time())

>>> print localtime

time.struct_time(tm_year=2018, tm_mon=5, tm_mday=21, tm_hour=17, tm_min=25, tm_sec=53, tm_wday=0, tm_yday=141, tm_isdst=0)

 

2)Formatted time in python:

It uses pre-defined function like asctime().This function returns a formatted time which includes day,month,date,time and year.It returns 24 character of a string.

Example:

>>>import time

>>> localtime=time.asctime(time.localtime(time.time()))

>>> print localtime

Mon May 21 17:28:56 2018

 

 

3)sleep(time) method:

It is used to stop the execution of script for the given interval of time.

Example:

>>> import time

>>> localtime=time.asctime(time.localtime(time.time()))

>>> print localtime

Mon May 21 17:33:19 2018

>>> time.sleep(10)

>>> localtime=time.asctime(time.localtime(time.time()))

>>> print localtime

Mon May 21 17:34:36 2018

 

4)strptime(string str,format f) method:

It returns tuples with 9 time attributes.It receives an string of date and a time format.

ATTRIBUTE

DESCRIPTION

%a

Weekday name

%b

Month name

%c

Date and time

%e

Day of a month

%m

Month in digit

%n

New line character

%S

Second

%t

Tab character

%d

Day of the month

%y

Year

%H

Hours

%M

minute

 

Example:

>>> import time

>>> timerequired=time.strptime("26 jun 14","%d %b %y")

>>> print timerequired

time.struct_time(tm_year=2014, tm_mon=6, tm_mday=26, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=177, tm_isdst=-1)

 

5)mktime() method:

It returns second in floating point since epoch.

Example:

>>> import time

>>> t=(2014,2,17,17,3,38,1,48,0)

>>> second=time.mktime(t)

>>> print second

1392636818.0

 

6)strftime() method:

It returns time in particular format.If time is not given,current time in seconds is fetched.

Example:

>>> import time

>>> t=(2014,6,26,17,3,38,1,48,0)

>>> t=time.mktime(t)

>>> print time.strftime("%b %d %y %H:%M:%S",time.gmtime(t))

 

>>> 

 

 

 

 

 

PYTHON CALENDAR MODULE

It provides many functions and methods to work on calendar.

methods

description

prcal(year)

It prints the whole calendar of the year.

firstweekday()

It returns the first week day.It is by default 0 which specifies Monday

Isleap(year)

It returns a Boolean value i.e true or false.True  in case given year is leap else false.

monthcalendar(year,month)

It returns the given month with each week as one list.

leapdays(year1,year2)

It returns number of leap days from year1 to year2.

prmonth(year,month)

It prints the given month of the given year.

 

Example:

>>> import calendar

>>> calendar.prcal(2018)

 

Example:2

>>> import calendar

>>> print calendar.firstweekday()

0

 

Example:3

>>> import calendar

>>> print calendar.isleap(2004)

True

 

Example:4

>>> import calendar

>>> print calendar.monthcalendar(2018,5)

[[0, 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, 0, 0, 0]]

 

Example:5

>>> import calendar

>>> print calendar.prmonth(2018,5)

      May 2018

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

 

 

                      

 

 

FILES INPUT/OUTPUT

 

“print” statement:

It is used to take string as input and place that string to standard output.

Syntax:

a=10

print a

 

Input from Keyboard:

There are two built-in functions to accept values from keyboard.

1.input()

2.raw_input()

 

1.input():It is used to take input from the user,whatever expression is given by the user,it is evaluated and result is returned back.

Syntax:

input(“Expression”)

Example:

n=input(“enter your expression”);

print “The evaluated expression is”,n

 

2.raw_input(): It is used to take input from the user.It takes the input from the standard input in the form of a string and reads the data from a line at once.

Syntax:

raw_input(?statement?)

Example:

id=int(raw_input(“enter employee id:”))

name=raw_input(“enter name:”)

sal=float(raw_input(“enter salary:”))

bonus=float(raw_input(“enter bonus:”))

company=raw_input(“enter company name:”)

 

print “empid:”,id

print “Name:”,name

print “Salary:”,sal

print “Bonus:”,bonus

print “Company:”,company

 

File Handling:

A file is an external storage on hard disk from where data can be stored and retrieved.

 

Operations on files:

1.Opening a file:To open a file use open() function.It returns an object of file which is used with other functions.

Syntax:

obj=open(filename,mode,buffer)

 

2.Closing a file:Once you are finished with the operations on file ate the end you need to close the file.It is done by the close() method.

Syntax:

File object.close()

 

3.Writing to a file:write() method is used to write a string into a file.

Syntax:

File object.write(string str)

 

4.Reading from a file: read() method is used to read data from the file.

Syntax:

File object.read(value)

 

Attributes of File:

·        Name:Returns the name of the file.

·        Mode:Returns the mode in which file is being opened.

·        Closed:Returns Boolean value.True,in case if file is closed else false.

 

Example:

obj=open(“python.txt”,”w”)

print obj.name

print  obj.mode

print obj.closed

 

Modes of a file:

Mode         Description

r     It opens in reading mode.It is default mode of a file.Pointer is at          beginning  of the file.

rb      It opens in reading mode for binary formate.It is the default mode.Pointer is at beginning of the file.

r+      Opens file for reading and writing.

rb+    Opens file for reading and writing in binary format.

w       Opens file in writing mode.If file already exists,then overwrite the         file else create a new file.

wb    Opens a file in writing mode in binary format.

w+    Opens a file for reading and writing.

wb+  Opens file for reading and writing in binary formate.

a       Opens a file in appending mode.

ab     Opens file in appending mode in binary format.

a+     Opens file in reading and appending mode.

ab+   Opens a file in reading and appending mode in binary format.

 

 

Methods:

1.rename():It is used to rename a file.It takes two arguments,existing_file_name and New_file_name.

Syntax:

os.rename(existing_file_name,new_file_name)

2.remove():It is used to delete a file.It takes one argument.Pass the name of the file which Is to be deleted as the argument of method.

Syntax:

os.remove(file_name)

3.mkdir():It is used to create a directory.A directory contains the files.It takes one argument which is the name of the directory.

Syntax:

os.mkdir(“file_name”)

4.chdir():It is used to change the current working

Example: (creating file and reading file)

obj=open("sush.txt","w") 

obj.write("today we are discussing files concepts") 

obj.close() 

obj1=open("sush.txt","r") 

s=obj1.read() 

print s 

obj1.close() 

obj2=open("sush.txt","r") 

s1=obj2.read(20) 

print s1 

obj2.close() 

 

Example: (appending data into file)

strings = ['sush', 'mani', 'satya']

 

# Open the file for (a)ppending, (+) creating it if it didn't exist

f = open('sush.txt', 'a+')

 

for s in strings:

    f.write(s + "\n")

 

Example: (copying data from one file to another file)

File1 = open('sush.txt','r')

File2 = open('mani.txt','w')

Reader = File1.read()

File2.write(Reader)

File1.close()

File2.close()

 

 

 

EXCEPTION HANDLING

 

àAn exception is  an event,which occurs during the execution of a program that disrupts the normal flow of the program’s instructions.

àTypes  of exceptions:

·        Exception

·        ArthmeticError

·        OverflowError

·        ZeroDivisionError

·        AssertionError

·        ImportError

·        IndexError

·        KeyError

·        IOError

·        ValueError

·        TypeError

·        NameError

àIf you have some suspicious code that may raise an exception, you can defined you program by placing the suspicious code in a “try:” block.

àAfter the “try:” block,include an “except:” statement,followed by a block of code which handles the problem as elegantly as possible.

Syntax:

try:  

    malicious code  

except Exception1:  

    execute code  

except Exception2:  

   execute code  

....  

....  

except ExceptionN:  

    execute code  

else:  

    In case of no exception, execute the else block code. 

 

Example:

1.>>>1/0(zero division  error)

2.>>>’abc’+2 (TypeError)

 

Program-1:

x=input("enter number1:")

y=input("enter number2:")

z=int(x)/int(y)

print("Division is:",z)

 

Program-2:

x=input("enter number1:")

y=input("enter number2:")

try:

    z=int(x)/int(y)

except Exception as e:

    print("exception occured:",e)

print("Division is:",z)

 

Program-3:

import sys

 

randomList = ['a', 5, 2]

 

for entry in randomList:

    try:

        print("The entry is", entry)

        r = 15/int(entry)

        break

    except:

        print("Oops!",sys.exc_info()[0],"occured.")

        print("Next entry.")

        print()

print("The reciprocal of",entry,"is",r)

 

Program-4:

#!/usr/bin/python

 

try:

   fh = open("test.txt", "r")

   fh.write("This is my test file for exception handling!!")

except IOError:

   print "Error: can\'t find file or read data"

else:

   print "Written content in the file successfully"

   fh.close()

Finally Block:

In case if there is any code which the user want to be executed, whether exception occurs or not then that code can be placed inside the finally block. Finally block will always be executed irrespective of the exception.

Syntax:

try:  

   Code  

finally:   

    code which is must to be executed.  

Example:

try:  

    a=10/0;  

    print "Exception occurred"  

finally:  

    print "Code to be executed"  

 

Custom Exception:

class ErrorInCode(Exception):  

     def __init__(self, data):  

   self.data = data  

     def __str__(self):  

        return repr(self.data)  

  

try:  

    raise ErrorInCode(2000)  

except ErrorInCode as ae:  

    print "Received error:", ae.data

 

NZEC Error:

NZEC(non zero exit code) as the name suggests occurs when your code is failed to return ‘ZERO’, It means it is successfully executed otherwise it will return someother number depending on the type of error.

When NZEC error occurs?

Generally multiple inputs are separated by commas and we read then using input() (or) int(input()), but most of the online coding platforms while testing gives input separated by space and in these cases int(input()) is not able to read the input properly and shows error like NZEC.

Example(worng code):

n=int(input())#when we work this code in IDE Then it displays NZEC error

k=int(input())

print(n,” “,k)

Example(correct code):

n,k=raw_input().split(" ")

n=int(n)

k=int(k)

print(n," ",k)

 

Reasons for NZEC error:

·        Infinite recursion (or) if you have run out of stack memory.

·        Input and output both are Not exactly same as the test case.

·        This type of error is also shown when your program is performing basic programming mistakes like dividing by ‘Zero’.

·        Check for the values of your variables, they can be vulnerable to integer flow.

Defining clean-up actions using finally clause:

àBefore leaving the ‘try’ statement, “finally” clause is always executed whether any exception is raised (or) not.

àWhenever an exception occurs and it is not being handled by the “except” clause, first “finally” will occur and then the error is raised as default.

 

Example:

Code-1:The below code works normally and clean-up action is taken at the end

def divide(x,y):

    try:

        result=x//y

    except ZeroDivisionError:

        print("sorry!you are dividing by zero")

    else:

        print("your answer:",result)

    finally:

        print("finally block")

divide(15,2)       

output:

your answer: 7

finally block

 

code-2:

code raises error and is carefully handled in the except clause:

def divide(x,y):

    try:

        result=x//y

    except ZeroDivisionError:

        print("sorry!you are dividing by zero")

    else:

        print("your answer:",result)

    finally:

        print("finally block")

divide(56,0)     

output:

sorry!you are dividing by zero

finally block

 

code-3:

In below code raise error but we don’t have any except clause to handle it. So,clean up action is taken first and then the error is raised by default by the compiler.

 

def divide(x,y):

    try:

        result=x//y

    except ZeroDivisionError:

        print("sorry!you are dividing by zero")

    else:

        print("your answer:",result)

    finally:

        print("finally block")

divide(15,"2")     

output:

finally block

Traceback (most recent call last):

  File "D:/pythonprgs/finally3.py", line 10, in <module>

    divide(15,"2")

  File "D:/pythonprgs/finally3.py", line 3, in divide

    result=x//y

TypeError: unsupported operand type(s) for //: 'int' and 'str'

 

 

            

MODULES

àModules are python files which contain different classes, functions, definitions,Variables which we can  reuse.

àIt should always end with a .py extension.

àPython itself is having a vast module library with the default installation.

    Example:

    Import math

àimport statement used for module import.

àwe  place import  statement in top of python file.

Example:

# Fibonacci numbers module

 

def fib(n):    # write Fibonacci series up to n

    a, b = 0, 1

    while b < n:

        print b,

        a, b = b, a+b

 

def fib2(n):   # return Fibonacci series up to n

    result = [ ]

    a, b = 0, 1

    while b < n:

        result.append(b)

        a, b = b, a+b

    return result

output:

>>> import fibo

>>> fibo.fib(20)

1 1 2 3 5 8 13

>>> fibo.fib2(34)

[1, 1, 2, 3, 5, 8, 13, 21]

>>> fibo.__name__

'fibo'

>>> fib=fibo.fib(30)

1 1 2 3 5 8 13 21

As keyword in module:

Syntax:

import module­_name as new_name

àCall methods of modules using alias name

Example:

new_name.method1

Example:

>>> import fibo as fibo1

>>> fibo1.fib(34)

1 1 2 3 5 8 13 21

 

How to import only specific method of module 

Syntax:

from module1 import method1

Example:

>>> from fibo import fib,fib2

>>> fib2(60)

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

All functions import of module

Syntax:

from module-name import *

Example:

>>> from fibo import *

>>> fib(40)

1 1 2 3 5 8 13 21 34

Function in modules:

àThe modules we have used so far are: sys, math, time

àThere are 100s of “standard” modules in Python:

·        Generation of random numbers and probability distributions

·         Accessing files and directories

·          Web development

·          Network programming

·         Graphics, etc.

à  A module is simply a file (just like the files that you have been creating your programs in) that contains related Python statements and function definitions.

à Programmers can define their own modules. There are 1000s of third-party modules available for Python.

dir() function:

It is used to find out which names a module defines.It returns a sorted list of strings.

Example:

import fibo,sys

dir(fibo)

dir(sys)

Example2:

import __builtin__

dir(__builtin__)

Module search path:

When a module named spam is imported,the interpreter first searches for built-in module with that name.If not found , it then searches for a file named sys.path  is initialized from these location:

·        The directory containing the current directory (or) input script.

·        PYTHONPATH(a list of directory names, with in the same syntax as the shell variable PATH).

·        The installation-dependent default.

 

TK Widgets

1.Button: Similar to a Label but provides additional functionality for mouse-overs, presses, and releases,as well as keyboard activity/events.

 

Example:

import tkinter

top = tkinter.Tk()

quit = tkinter.Button(top, text='Hello World!',

               command=top.quit)

quit.pack()

tkinter.mainloop()

 

2.Label: Used to contain text or images

 

Example:

import tkinter

top = tkinter.Tk()

hello = tkinter.Label(top, text='Hello World!')

hello.pack()

quit = tkinter.Button(top, text='QUIT', command=top.quit,

       bg='red', fg='white')

quit.pack(fill=tkinter.X, expand=1)

tkinter.mainloop()

 

3.Geomatery Managers:

Example:

from tkinter import *

root = Tk()

w = Label(root, text="Red", bg="red", fg="white")

w.pack()

w = Label(root, text="Green", bg="green", fg="black")

w.pack()

w = Label(root, text="Blue", bg="blue", fg="white")

w.pack()

mainloop()

 

Example1:

from Tkinter import *

root = Tk()

w = Label(root, text="Red", bg="red", fg="white").pack(side=LEFT)

w = Label(root, text="Green", bg="green", fg="black").pack(side=LEFT)

w = Label(root, text="Blue", bg="blue", fg="white").pack(side=LEFT)

mainloop()

 

4.Message

The Message widget is used to display text. This is a widget not a text window.

options:

anchor     

padx

aspect      

pady

background/bg

 relief

borderwidth/bd

takefocus

cursor

text

font

 textvariable

foreground/fg

 width

highlightbackground

highlightcolor

highlightthickness

justify

Example:

from tkinter import *

master =Tk()

msg = Message(master, text=' The best way to predict the future is to invent it. AlanKay')

msg.config(font=('times',14))

msg.pack()

mainloop()

 

5.Entry

used to enter or display a single line of text

To enter multiple lines of text, use the Text widget.

OPTIONS:

anchor

aspect

background/bg

relief

borderwidth/bd

 takefocus

cursor text

font

textvariable

foreground/fg

width

highlightbackground

validate

highlightcolor

validatecommand

highlightthickness

justify

 

methods:

get()

set()

delete(first,last/END)

insert(index)

insert(index,string)

icursor(index)

index(index)

Example:

from tkinter import *

master = Tk()

e = Entry(master)

e.pack()

def callback():

     print(e.get())

b = Button(master, text="get", width=10, command=callback)

b.pack()

mainloop()

 

6.Frame Widget

Frames are used as containers for other widgets. Widgets placed in a

frame can use any of the geometry managers (but only one per

frame)

You can have multiple frames per window

Options:

Bg:background color

bd :border width (default=2 pixels)

cursor: cursor to use when hovering over the frame

height :vertical dimension of the frame

highlightbackground :color when frame doesn’t have focus

highlightcolor :color when frame has focus

highlightthickness: thickness of the focus highlight

relief :FLAT, Raised, Sunken, GROOVE, RIDGE;default = FLAT

width: width of the frame

Example:

from tkinter import *

root = Tk()

frame = Frame(root)

frame.pack()

bottomframe = Frame(root)

bottomframe.pack( side = BOTTOM )

redbutton = Button(frame, text="Red", fg="red")

redbutton.pack( side = LEFT)

greenbutton = Button(frame, text="Brown", fg="brown")

greenbutton.pack( side = LEFT )

bluebutton = Button(frame, text="Blue", fg="blue")

bluebutton.pack( side = LEFT )

blackbutton = Button(bottomframe, text="Black", fg="black")

blackbutton.pack( side = BOTTOM)

root.mainloop()

 

7.Checkbuttons and Radiobuttons:

Checkbuttons are used for multiple choice situations, i.e. choosing m of n possible options. This is done by assigning each checkbox a variable of its own.

Radiobuttons are used for choosing one of n possible choices; i.e. a mutually exclusive single choice by giving each button a unique value of the same Tkinter variable.

 

Example:

from tkinter import *

def cb():

   print("beer is", var1.get())

   print ("Wine is", var2.get())

   print ("Water is", var3.get())

win = Tk()

f = Frame(relief=RAISED , borderwidth=5)

var1 = IntVar()

var2 = IntVar()

var3 = IntVar()

c1 = Checkbutton(

     f, text="Beer",

     variable=var1,

     command= (lambda: cb()))

c1.pack(side=TOP)

c2 = Checkbutton(

     f, text="Wine",

    variable=var2,

    command= (lambda: cb()))

c2.pack(side=TOP)

c3 = Checkbutton(

     f, text="Water",

     variable=var3,

     command= (lambda: cb()))

c3.pack(side=TOP)

f.pack()

mainloop()

 

Example2:

from tkinter import *

def change():

    print ('Station = ' , var.get())

root = Tk()

stations = 'mca' , 'mba' , 'btech' , 'msc'

f = Frame(relief=RAISED , borderwidth=5)

var = StringVar()

for station in stations:

    radio = Radiobutton(f, text=station, variable=var ,value=station)

    radio.pack(side=TOP)

f.pack(pady=10)

Button(root,text='New' , command=(lambda: change())).pack(pady=10)

var.set('WAAL') #initalize the set of radio buttons

mainloop()

 

8. Sliders

A slider is a Tkinter object with which a user can set a value by moving an indicator. Sliders can be vertically or horizontally arranged. A slider is created with the Scale

method().

 

Example:

from tkinter import *

master = Tk()

w = Scale(master, from_=0, to=42)

w.pack()

w = Scale(master, from_=0, to=200, orient=HORIZONTAL)

w.pack()

mainloop()

 

9. Listbox

The Listbox widget is used to display a list of alternatives. The listbox can only contain text items, and all items must have the same font and color. Depending on the widget configuration, the user can choose one or more alternatives from the list.

 

Example:

from tkinter import *

master = Tk()

listbox = Listbox(master)

listbox.pack()

listbox.insert(END, "a list entry")

for item in ["one", "two", "three", "four"]:

    listbox.insert(END, item)

mainloop()

 

10. Scrollbar

This widget is used to implement scrolled listboxes,canvases, and text fields.

Patterns

          The Scrollbar widget is almost always used in conjunction with a

             Listbox, Canvas, or Text widget. Horizontal scrollbars can also be

             used with the Entry widget.

          To connect a vertical scrollbar to such a widget, you have to do two things:

                     Set the widget’s yscrollcommand callbacks to the set method of the scrollbar.

                     Set the scrollbar’s command to the yview method of the widget.

Example:

from tkinter import *

master = Tk()

scrollbar = Scrollbar(master)

scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(master, yscrollcommand=scrollbar.set)

for i in range(1000):

    listbox.insert(END, str(i))

listbox.pack(side=LEFT, fill=BOTH)

scrollbar.config(command=listbox.yview)

mainloop()

11. Canvas:

The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets, or frames on a Canvas.

Syntax:

            w = Canvas ( master, option=value, ... )

Parameters:

           master: This represents the parent window.

           options: Here is the list of most commonly used options for this  widget. These options can be used as key-value pairs separated by  commas.

 

Example:

The Canvas widget can support the following standard items:

        arc :

             Creates an arc item.

                  coord = 10, 50, 240, 210

                  arc = canvas.create_arc(coord, start=0,extent=150,fill="blue")

image :

Creates an image item, which can be an instance of either the

BitmapImage or the PhotoImage classes.

           filename = PhotoImage(file = "sunshine.gif")

           image = canvas.create_image(50, 50, anchor=NE,image=filename)

line :

 Creates a line item.

           line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn,options)

oval :Creates a circle or an ellipse at the given coordinates.

           oval = canvas.create_oval(x0, y0, x1, y1, options)

polygon:Creates a polygon item that must have at least three

vertices.

              oval = canvas.create_polygon(x0, y0, x1, y1,...xn, yn,options)

Example:

import tkinter

from tkinter import messagebox

top = tkinter.Tk()

C = tkinter.Canvas(top, bg="blue", height=250, width=300)

coord = 10, 50, 240, 210

arc = C.create_arc(coord, start=0, extent=150, fill="red")

C.pack()

top.mainloop()

 

Example:1

from tkinter import *

 

canvas_width = 500

canvas_height = 150

 

def paint( event ):

   python_green = "#476042"

   x1, y1 = ( event.x - 1 ), ( event.y - 1 )

   x2, y2 = ( event.x + 1 ), ( event.y + 1 )

   w.create_oval( x1, y1, x2, y2, fill = python_green )

 

master = Tk()

master.title( "Painting using Ovals" )

w = Canvas(master,

           width=canvas_width,

           height=canvas_height)

w.pack(expand = YES, fill = BOTH)

w.bind( "<B1-Motion>", paint )

 

message = Label( master, text = "Press and Drag the mouse to draw" )

message.pack( side = BOTTOM )

   

mainloop()

 

BITMAPS:

The method create_bitmap() can be be used to include a bitmap on a canvas. The following bitmaps are available on all platforms:
"error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info", "questhead", "question", "warning".

Example:

from tkinter import *

 

canvas_width = 300

canvas_height =80

 

master = Tk()

canvas = Canvas(master,

           width=canvas_width,

           height=canvas_height)

canvas.pack()

 

bitmaps = ["error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info", "questhead", "question", "warning"]

nsteps = len(bitmaps)

step_x = int(canvas_width / nsteps)

 

for i in range(0, nsteps):

   canvas.create_bitmap((i+1)*step_x - step_x/2,50, bitmap=bitmaps[i])

 

mainloop()

 

image item:

The Canvas method create_image(x0,y0, options ...) is used to draw an image on a canvas. create_image doesn't accept an image directly. It uses an object which is created by the PhotoImage() method. The PhotoImage class can only read GIF and PGM/PPM images from files.

Example:

from tkinter import *

 

canvas_width = 300

canvas_height =300

 

master = Tk()

 

canvas = Canvas(master,

           width=canvas_width,

           height=canvas_height)

canvas.pack()

 

img = PhotoImage(file="images.png")

canvas.create_image(20,20, anchor=NW, image=img)

 

mainloop()

12.Menu widget:

The Menu widget is used to implement toplevel, pulldown, and popup menus.

When to use the Menu Widget?

This widget is used to display all kinds of menus used by an application. Since this widget uses native code where possible, you shouldn’t try to fake menus using buttons and other Tkinter widgets.

 

Example:

from tkinter import *

# Here, we are creating our class, Window, and inheriting from the Frame

# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)

class Window(Frame):

 

    # Define settings upon initialization. Here you can specify

    def __init__(self, master=None):

       

        # parameters that you want to send through the Frame class.

        Frame.__init__(self, master)  

 

        #reference to the master widget, which is the tk window                

        self.master = master

 

        #with that, we want to then run init_window, which doesn't yet exist

        self.init_window()

 

    #Creation of init_window

    def init_window(self):

 

        # changing the title of our master widget     

        self.master.title("GUI")

 

        # allowing the widget to take the full space of the root window

        self.pack(fill=BOTH, expand=1)

 

        # creating a menu instance

        menu = Menu(self.master)

        self.master.config(menu=menu)

 

        # create the file object)

        file = Menu(menu)

 

        # adds a command to the menu option, calling it exit, and the

        # command it runs on event is client_exit

        file.add_command(label="Exit", command=self.client_exit)

 

        #added "file" to our menu

        menu.add_cascade(label="File", menu=file)

 

        # create the file object)

        edit = Menu(menu)

 

        # adds a command to the menu option, calling it exit, and the

        # command it runs on event is client_exit

        edit.add_command(label="Undo")

 

        #added "file" to our menu

        menu.add_cascade(label="Edit", menu=edit)

 

   

    def client_exit(self):

        exit()

 

       

# root window created. Here, that would be the only window, but

# you can later have windows within windows.

root = Tk()

 

root.geometry("400x300")

 

#creation of an instance

app = Window(root)

 

#mainloop

root.mainloop() 

 

 

Calculator Example in python:

# import everything from tkinter module

from tkinter import *

  

# globally declare the expression variable

expression = ""

  

  

# Function to update expressiom

# in the text entry box

def press(num):

    # point out the global expression variable

    global expression

  

    # concatenation of string

    expression = expression + str(num)

  

    # update the expression by using set method

    equation.set(expression)

  

  

# Function to evaluate the final expression

def equalpress():

    # Try and except statement is used

    # for handling the errors like zero

    # division error etc.

  

    # Put that code inside the try block

    # which may generate the error

    try:

  

        global expression

  

        # eval function evaluate the expression

        # and str function convert the result

        # into string

        total = str(eval(expression))

  

        equation.set(total)

  

        # initialze the expression variable

        # by empty string

        expression = ""

  

    # if error is generate then handle

    # by the except block

    except:

  

        equation.set(" error ")

        expression = ""

  

  

# Function to clear the contents

# of text entry box

def clear():

    global expression

    expression = ""

    equation.set("")

  

  

# Driver code

if __name__ == "__main__":

    # create a GUI window

    gui = Tk()

  

    # set the background colour of GUI window

    gui.configure(background="light green")

  

    # set the title of GUI window

    gui.title("Simple Calculator")

  

    # set the configuration of GUI window

    gui.geometry("265x125")

  

    # StringVar() is the variable class

    # we create an instance of this class

    equation = StringVar()

  

    # create the text entry box for

    # showing the expression .

    expression_field = Entry(gui, textvariable=equation)

  

    # grid method is used for placing

    # the widgets at respective positions

    # in table like structure .

    expression_field.grid(columnspan=4, ipadx=70)

  

    equation.set('enter your expression')

  

    # create a Buttons and place at a particular

    # location inside the root window .

    # when user press the button, the command or

    # function affiliated to that button is executed .

    button1 = Button(gui, text=' 1 ', fg='black', bg='red',

                     command=lambda: press(1), height=1, width=7)

    button1.grid(row=2, column=0)

  

    button2 = Button(gui, text=' 2 ', fg='black', bg='red',

                     command=lambda: press(2), height=1, width=7)

    button2.grid(row=2, column=1)

  

    button3 = Button(gui, text=' 3 ', fg='black', bg='red',

                     command=lambda: press(3), height=1, width=7)

    button3.grid(row=2, column=2)

  

    button4 = Button(gui, text=' 4 ', fg='black', bg='red',

                     command=lambda: press(4), height=1, width=7)

    button4.grid(row=3, column=0)

  

    button5 = Button(gui, text=' 5 ', fg='black', bg='red',

                     command=lambda: press(5), height=1, width=7)

    button5.grid(row=3, column=1)

  

    button6 = Button(gui, text=' 6 ', fg='black', bg='red',

                     command=lambda: press(6), height=1, width=7)

    button6.grid(row=3, column=2)

  

    button7 = Button(gui, text=' 7 ', fg='black', bg='red',

                     command=lambda: press(7), height=1, width=7)

    button7.grid(row=4, column=0)

  

    button8 = Button(gui, text=' 8 ', fg='black', bg='red',

                     command=lambda: press(8), height=1, width=7)

    button8.grid(row=4, column=1)

  

    button9 = Button(gui, text=' 9 ', fg='black', bg='red',

                     command=lambda: press(9), height=1, width=7)

    button9.grid(row=4, column=2)

  

    button0 = Button(gui, text=' 0 ', fg='black', bg='red',

                     command=lambda: press(0), height=1, width=7)

    button0.grid(row=5, column=0)

  

    plus = Button(gui, text=' + ', fg='black', bg='red',

                  command=lambda: press("+"), height=1, width=7)

    plus.grid(row=2, column=3)

  

    minus = Button(gui, text=' - ', fg='black', bg='red',

                   command=lambda: press("-"), height=1, width=7)

    minus.grid(row=3, column=3)

  

    multiply = Button(gui, text=' * ', fg='black', bg='red',

                      command=lambda: press("*"), height=1, width=7)

    multiply.grid(row=4, column=3)

  

    divide = Button(gui, text=' / ', fg='black', bg='red',

                    command=lambda: press("/"), height=1, width=7)

    divide.grid(row=5, column=3)

  

    equal = Button(gui, text=' = ', fg='black', bg='red',

                   command=equalpress, height=1, width=7)

    equal.grid(row=5, column=2)

  

    clear = Button(gui, text='Clear', fg='black', bg='red',

                   command=clear, height=1, width=7)

    clear.grid(row=5, column='1')

  

    # start the GUI

    gui.mainloop()

 

MYSQL

àIt is a database system,used for developing web-based software applications.

àIt is used for both small and large applications.

àIt is relational database management system(RDBMS).

àIt is fast reliable and flexible and easy to use.

àIt supports standard sql.

àIt was develop by ‘Michael Widenius’ and ‘David Axmark’ in 1994.

àIt is presently developed,distributed and supported by oracle corporation.

àIt is written in C,C++.

 

Features of MYSQL:

àMYSQL server design is multi-layered with independent modules.

àIt is fully multithreaded by using Kernl threads. It can use multiple CPU’s if they are available.

àIt provides transactional and non-transactional storage engines.

àIt has a high-speed thread-based memory allocation system.

àIt supports in-memory heap table.

àIt handles large databases.

àMYSQL server works in client/server (or) embedded systems.

àIt works on different platforms.

 

Who uses MYSQL?

àsome of the most famous websites like Facebook,Wikipedia,Google,Youtube,Flickr.

àContent management systems(CMS) like WordPress,Drupal,Joomla,PhpDB.

 

TYPES OF SQL COMMANDS:

1.DDL(Data Definition Language):

DDL deals with database schemas and descriptions, of how the data  should reside in the database.

 

(a)CREATE:

To create a database and its objects like(tables,index,views,store procedure,function and triggers.

(b)ALTER:

Alter the structure of the existing database.

(c) DROP:

Delete objects from the database.

(d)TRUNCATE:

Remove all records from a table,including all spaces allocated for the records are removed.

(e)RENAME:

Rename an object.

 

2.DML (Data Manipulation Language):

It deals with data manipulation and includes most common sql statements such as SELECT,INSERT,UPDATE,DELETE etc… and it is used to store,modify,retrieve,delete and update data in a database.

(a)SELECT:

Retrieve  data from a database.

(b)INSERT:

Insert data into a table.

(c) UPDATE:

Updates existing data within a table.

(d)DELETE:

Delete all records from a database table.

(e)MERGE:

Upsrt operation insert (or) update.

(f)CALL:

Call a PL?SQL (or) java Subprogram.

(g)EXPLAIN PLAN:

Interpretation of the data access path.

(h)LOCK TABLE:

Concurrency control

 

3.DCL(Data Control Language):

DCL includes commands such as GRANT and mostly concerned  with rights, permissions and other controls of the database system.

(a)GRANT:

Allows user access privileges to the database.

(b)REVOKE:

Withdraw users access privileges given by using th GRANT command.

 

4.TCL(Transaction control Language):

(a)COMMIT:

Commits a transaction.

(b)ROLLBACK:

Rollback a transaction making points within groups.

(c)SAVEPOINT:

To rollback the transaction making points within groups.

(d)SET TRANSACTION:

Specify characteristics of the transaction.

 

Create database and use database:

Database syntax:

Create database database_name;

Syntax to use database:

Use database_name;

 

Example:

mysql>create database college;

mysql>show databases;

mysql>use college;

database changed

 

Create a table:

 Syntax:

create table table_name(col1 datatype,col2 datatype….);

Example:

create table student(rollno int,name varchar(10),address varchar(5),branch varchar(5));

Table created

 

Describing a table:

Syntax:

 desc table_name;

Example:

desc student;

 

Modifying the structure of the table: 

Alter table command:

It is used to add new columns to a table,remove existing columns and changing column names,types and lengths.

To add new fields in table:

Syntax:

ALTER TABLE table_name add[column] column definition [first/after column];

Example:

alter table student add result int;

desc student;

 

Example:1

 alter table student add id int first;

desc student;

 

Example:2

alter table student add address varchar(10) after name;

desc student;

 

Drop a column:

The drop clause of the ALTER TABLE statement removes a given column from a table and deletes th columns data.A table must have at least on column,so this statement will fail if used on the only column in a table.

Syntax:

ALTER TABLE table_name DROP[COLUMN] column_name;

Example:

alter table student drop column id;

desc student;

Example:2

alter table student drop column branch,drop column result;

desc student;

 

MODIFY,CHANGE,RENAME:

1.modify:

This clause used to change the data types of a existing column.

Syntax:

alter table tablename modify column_name data_type;

Example:

alter table student modify address varchar(12);

desc student;

 

 2.change:

This clause used to change the name of a existing column.

Syntax:

ALTER TABLE table_name change column_name new_column_name data_type;

Example:

alter table student change address location varchar(12);

desc student;

 

3.rename:

This clause used to rename the table name.

Syntax:

ALTER TABLE table_name rename new_name;

Example:

alter table student rename comp;

desc student;

Error 1146(42s02):Table ‘college.student’ doesn’t exist

desc comp;

 

Insert data into tables:

This command usd to insert data into the table.

Syntax:

INSERT into <table-name>values (val1,val2 etc…..);

Example:

insert into student values(11,’mani’,’hyd’);

select * from student;

 

Example:2

insert into student values(12,’sushma’,’hyd’),(13,’anil’,’hyd’);

select * from student;

 

Delete the data from table:

Syntax:

DELETE from <table-name> where (<column-name=’some-value’);

Example:

delete from student where rollno=10;

select * from student;

 

Example:2

delete from student;

select * from student;

 

Limit keyword with delete:

 Using the LIMIT keyword to ensure only the number of rows you specify are deleted.

Example:

delete from student limit 2;

 select  * from student;

 

used to update data into tables:

Syntax:

UPDATE tablename set column_name=value where condition;

Example:

update student set name=’padma’ where id=12;

select * from student;

 

Example:1

update student set name=’mani’;

select * from student;

 

Example:3

update student set id=id+1;

select * from student;

 

NOTE:

Use the LIMIT function to display to control the no.of rows that are affected by your UPDATE statement.

Example:

update student set name=’manikumar’ limit 2;

select * from student;

  

DATABASE PROGRAMMING IN PYTHON

àPython supports various databases like MYSQL,ORACLE,SYBASE,POSTGRESQL, etc…

àPython also supports DDL,DML and Data query statements.

àPython DB API is a widely used module that provides a database application programming interface.

 

Benefits of python for database programming:

1.Python is famous for its portability.

2.It is platform independent.

3.Python supports SQL cursors.

4.Python supports relational database management system.

5.Python database API’s are compatable with various databases, so it is very easy to migrate and port databases application interface.

 

Steps to connect MYSQL database in python using MYSQL connector python:

1.Install MYSQL connector python using pip.

Example:

C:\users\your name\App data\Local\Programs\Python\Python 36-32\Scripts>python –m pip install mysql-connector.

2.use the mysql.connector.connect() method of MYSQL connector python with required parameters to connect MYSQL.

3.use the connection object returned by a connect() method to create a cursor object to perform database operations.

4.The cursor.execute() to execute SQL queries from python.

5.close the cursor object using a cursor.close() and MYSQL database connection using connection.close() after your work completes.

6.Catch exception if any that may occur during this process.

 

Packages:

1.import mysql.connector:

This module API to connect MYSQL.

2.from mysql.connector import error:

It show us an error when we failed to connect database (or) if any other databases object error occurred while working with the database.

Example:

ER_Access_DENIED_Error when username (or) password is wrong.

 

Arguments required to connect the MYSQL database from python:

(a)username:

The default username for the MYSQL database is ‘root’.

(b)password:

Password is given by the user at the time of installing the MYSQL database. If you are using root then you won’t need the password.

(c) hostname:

It is srver name (or) IP address on which MYSQL is running. If you are running on localhost, then you can use localhost, (or) it’s IP,i.e 127.0.0.0

(D)database name:

Database name to which you want to connect here we are using database named ‘Python_DB’.

 

Functions:

(1)mysql.connector.connect:

àThis function we can connect the MYSQL database, this function accepts four required parameters:Host,Database,user and password that we already discussed.

àconnect() function established a connection to the MYSQL database from python application and returnd a MYSQLConnection object.

àconnect() function throw an exception,i.e. database error if one of the required parameters are wrong.

 

(2)conn.is_connected():

It is the function of the MySQLConnection class through which we can verify is our python application connected to MySQL.

 

(3)connection.cursor():

It returns a cursor object, using this object we can execute SQL queries. Cursor objects interact with the MySQL server using a MySQLConnection object.

 

(4)cursor.close():

Using this method we can close the cursor object.Once we close the cursor object, we can not execute any SQL statement.

 

(5)connection.close():

Closing thee MySQL databases connection using a close() function of MySQLConnection class.

 

Program-1:

import mysql.connector

 

mydb = mysql.connector.connect(

  host="localhost",

  user="root",

  passwd="manikumar"

)

 

mycursor = mydb.cursor()

 

mycursor.execute("CREATE DATABASE hospital")

print("Database Created Success..!")

 

Program-2:

import mysql.connector

 

mydb = mysql.connector.connect(

  host="localhost",

  user="root",

  passwd="manikumar",

  database="hospital"

)

 

mycursor = mydb.cursor()

 

mycursor.execute("CREATE TABLE patients(name varchar(10),address varchar(10))")

 

print("Table Created Success")

 

Program-3:

import mysql.connector

 

mydb = mysql.connector.connect(

  host="localhost",

  user="root",

  passwd="manikumar",

  database="hospital"

)

 

mycursor = mydb.cursor()

sql = "INSERT INTO patients(name,address) VALUES (%s,%s)"

val = ('sushma','vizag')

 

mycursor.execute(sql, val)

 

mydb.commit()

 

print(mycursor.rowcount, "record inserted.")

 

Program-4:

import mysql.connector

 

mydb = mysql.connector.connect(

  host="localhost",

  user="root",

  passwd="manikumar",

  database="hospital"

)

 

print("Enter Customer Name : ")

name=input()

print("Enter Customer Address : ")

address=input()

 

 

mycursor = mydb.cursor()

sql = "INSERT INTO patients(name, address) VALUES (%s, %s)"

val = (name, address)

mycursor.execute(sql, val)

 

mydb.commit()

 

print(mycursor.rowcount, "record inserted.")

 

Program-5:

import mysql.connector

 

mydb = mysql.connector.connect(

  host="localhost",

  user="root",

  passwd="manikumar",

  database="hospital"

)

 

mycursor = mydb.cursor()

 

sql = "INSERT INTO patients(name, address) VALUES (%s, %s)"

val = [

  ('Peter', 'usa'),

  ('Amy', 'mumbai'),

  ('Hannah', 'chennai'),

  ('Michael', 'punjab'),

  ('Sandy', 'assam'),

  ('Betty', 'goa'),

  ('Richard', 'haryana'),

  ('Susan', 'gujarat'),

  ('Vicky', 'delhi'),

  ('Ben', 'kolkatha'),

  ('William', 'banglore'),

  ('Chuck', 'ooty'),

  ('Viola', 'mysore')

]

 

mycursor.executemany(sql, val)

 

mydb.commit()

print("Records Inserted")

 

Program-6:

import mysql.connector

 

mydb = mysql.connector.connect(

  host="localhost",

  user="root",

  passwd="manikumar",

  database="hospital"

)

 

mycursor = mydb.cursor()

 

mycursor.execute("SELECT * FROM patients")

 

myresult = mycursor.fetchall()

 

for x in myresult:

  print(x)

 

Program-7:

import mysql.connector

 

mydb = mysql.connector.connect(

  host="localhost",

  user="root",

  passwd="manikumar",

  database="hospital"

)

 

print("Enter name: ")

name=input()

print("Enter address: ")

address=input()

 

mycursor = mydb.cursor()

sql = "UPDATE patients set address=%s where name=%s"

val = (address,name)

mycursor.execute(sql, val)

 

mydb.commit()

 

if(mycursor.rowcount==1):

  print(mycursor.rowcount, "record updated Success.")

else:

  print(mycursor.rowcount, "record updated Failed.")

 

Program-8:

from tkinter import *

import mysql.connector

from tkinter import ttk

from tkinter import messagebox

 

window = Tk()

 

window.title("Faculity Form")

 

window.geometry('550x300')

 

id=""

name=""

experience=0

salary=""

gen=""

 

lbl = Label(window, text="Enter Faculity ID : ",font=("Arial",25))

 

lbl.grid(column=0, row=0)

 

txtid = Entry(window,width=10)

txtid.focus()

txtid.grid(column=1, row=0)

 

lbl1 = Label(window, text="Enter Faculity Name : ",font=("Arial",25))

 

lbl1.grid(column=0, row=1)

 

txtname = Entry(window,width=10)

txtname.grid(column=1, row=1)

 

lbl2 = Label(window, text="Select Faculity Experiance : ",font=("Arial",25))

 

lbl2.grid(column=0, row=2)

 

combo =ttk.Combobox(window)

 

combo['values']= ("1", "2", "3", "4", "5", "6","7", "8", "9", "10","--Select--")

 

combo.current(10) #set the selected item

 

def getExp(eventObject):

       experience=int(combo.get())

      

combo.bind("<<ComboboxSelected>>", getExp)

combo.grid(column=1, row=2)

 

lbl3 = Label(window, text="Enter Faculity Salary : ",font=("Arial",25))

lbl3.grid(column=0, row=3)

 

txtsal = Entry(window,width=10)

txtsal.grid(column=1, row=3)

 

selected = IntVar()

rad1 = Radiobutton(window,text='M', value=1, variable=selected)

rad1.grid(column=0, row=4)

rad2 = Radiobutton(window,text='F', value=2, variable=selected)

rad2.grid(column=1, row=4)

 

def clicked():

   id=txtid.get()

   name=txtname.get()

   salary=txtsal.get()

   experience=combo.get()

   if(selected.get()==1):

       gen="M"

   else:

       gen="F"

   mydb = mysql.connector.connect(

      host="localhost",

      user="root",

      passwd="manikumar",

      database="institute")

   mycursor = mydb.cursor()

   sql = "INSERT INTO faculty(fid,fname,fexp,sal,gen) VALUES (%s,%s, %s,%s,%s)"

   val = (id,name,experience,salary,gen)

   mycursor.execute(sql, val)

   mydb.commit()

   messagebox.showinfo('Faculity Form', 'Successfully Submited')  

 

btn = Button(window, text="Submit", command=clicked)

 

btn.grid(column=0, row=5)

 

window.mainloop()

 

Program-9:

from tkinter import *

from tkinter.filedialog   import askopenfilename 

 

window = Tk()

 

window.title("File Reader")

 

window.geometry('550x300')

 

lbl = Label(window, text="Select your file : ",font=("Arial",25),fg="white",bg="red")

 

lbl.grid(column=0, row=0)

 

txtpath = Entry(window,width=20,font=("Arial",25),fg="white",bg="pink")

txtpath.grid(column=1, row=0)

 

def openwind():

    name= askopenfilename()

    txtpath.insert(0, name)

 

btnBrowse = Button(window, text="***", command=openwind,font=("Arial",25),fg="white",bg="red")

 

btnBrowse.grid(column=2, row=0)

 

obj=Text(window,height=10,width=50)

obj.grid(column=0,row=1)

 

def getFile():

    f = open(txtpath.get(), "r")

    for line in f.readlines():

        obj.insert(END,line)

   

 

btnOpen = Button(window, text="Open", command=getFile,font=("Arial",25),fg="white",bg="red")

 

btnOpen.grid(column=0, row=2)

 

 

window.mainloop()

 

Comments

Popular posts from this blog

Annapurna Base Camp

song on clouds