Social Media

Image Slider

2/20/2019

__init__() function

  • This is a function which we do not need to call.
  • If we define this function in the class then it is the first function in the life of an object which is called.
  • When we create an object of the class in which this function is defined then this function is called automatically for that object.
  • Mainly this function is used to define instance members of the object.
  • If you have knowledge of java or c++ language, then you can say that this function is just similar to constructor.

**One argument is necessary in __init__ function while we define it.
When an object call this function object itself is passed as a first argument.
class square:
    def __init__(self,side): 
        self.side=side
    def calarea(self):
        x=self.side
        print("The area of square is ",x*x)
        
s1=square(10)
s2=square(20)
s1.calarea()

Output:
The area of square is  100
The area of square is  400

Example2: Write an script to calculate the area of rectangle whose length and breadth are taken from the user in object oriented way.
class rect:
    def __init__(self,l,b):
        self.l=l
        self.b=b
    def calarea(self):
        x=self.l
        y=self.b
        print("The area of rectangle is",x*y)

a,b=int(input("Enter length ")),int(input("Enter breadth "))

r1=rect(a,b)
r1.calarea()

Output:
Enter length 3
Enter breadth 4
The area of rectangle is 12

2/12/2019

Object Oriented programming using python

If a language support object oriented way of programming it means that a large problem can be divided into smaller ones and then we can combine them to get the target output.
It means by using OOP's (Object Oriented Programming) we can achieve the solution of large and complex problems in easier way as compared to procedural programming.
The main features of object oriented programming are
  • Classes and objects
  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
Classes and Objects:
  • If we are creating a class, it means that we are actually creating a new datatype.
  • We can encapsulate(bind) data members, and functions (methods) into a single unit which is called class.
  • Basically class is identified by some name.
  • Class represent a blueprint of the object(real world entity).
  • int, float, complex, list, tuple, set, dict are all examples of predefined classes in Python.
  • Object represent the instant of class.
  • By defining a class, we are not actually consuming any memory. Memory will be consume when objects of that class are made, means object consumes memory.
  • We can create any number of objects of a single class.
  • A simple script is given below for defining and creating object of the class.
 class M1:
    s=10
    def fun1():
        print("This is function of class")


print(M1.s) # M1 is class object
M1.fun1()
o1=M1()   #We are creating a new object and o1 will referring it
print(o1.s)
o1.fun1() # Error Come here


The output of this script is:
10
This is function of class
10
Traceback (most recent call last):
  File "/root/Desktop/p1.py", line 10, in <module>
    o1.fun1()
TypeError: fun1() takes 0 positional arguments but 1 was given 


Have a look on the above script and try to understand the flow of the program. Don't worry why error is coming, we will understand it later.
2/11/2019

Explicitly raising and handling of Exception

Explicitly raising and implicitly handling:

x=int(input("Enter first number "))
y=int(input("Enter second number "))
if y==0:
    raise ZeroDivisionError("Cannot divide by zero")
rslt=x/y
print("The result is",rslt)

if y=0 then output of above script can be as:
Enter first number 1
Enter second number 0
Traceback (most recent call last):
  File "/root/Desktop/p1.py", line 4, in <module>
    raise ZeroDivisionError("Cannot divide by zero")
ZeroDivisionError: Cannot divide by zero # message will be printed here


Explicitly raising and implicitly handling:

a=int(input("Enter first number "))
b=int(input("Enter second number "))
try:
    if b==0:
        raise ZeroDivisionError("Cannot divide by zero")
    rslt=a/b
    print("The result is",rslt)
except ZeroDivisionError as e:
    print("This is exception:",e)
finally:
    print("This program is created by Mayank Kumar Prajapati")


if b=0 then output of above script is as:
Enter first number 1
Enter second number 0
This is exception: Cannot divide by zero
This program is created by Mayank Kumar Prajapati


Implicitly raising and handling of Exception

Implicitly raising and implicitly handling:

a=int(input("Enter first number "))
b=int(input("Enter second number "))
rslt=a//b
print("The result is",rslt)


If b=0 then result can be as:
Enter first number 2
Enter second number 0
Traceback (most recent call last):
  File "/root/Desktop/p1.py", line 3, in <module>
    rslt=a//b
ZeroDivisionError: integer division or modulo by zero


if b!=0 then result will be:
Enter first number 2
Enter second number 1
The result is 2


Implicitly raising and explicitly handling:

a=int(input("Enter first number "))
b=int(input("Enter second number "))
try:
    rslt=a//b
    print("The result is",rslt)
except ZeroDivisionError as e:
    print(e)
else:
    print("Program executed successfully")
finally:
    print("This program is created by Mayank Kumar Prajapati")


if b=0 then the result of b=above program is:
Enter first number 2
Enter second number 0
integer division or modulo by zero
This program is created by Mayank Kumar Prajapati


if b!=0 then result is:
Enter first number 2 
Enter second number 1
The result is 2
Program executed successfully
This program is created by Mayank Kumar Prajapati

2/10/2019

try, except and finally

In try block we have to write that code of our program, where we expecting that exception will come.

Some points about try and except:
  • We cannot have any except block without try block.
  • In except we have to catch the object thrown by that line which is present in the try block.
  • There can be more than one except block for a single try block.
  • except block only executed when any exception occurs, if no exception occurs program will execute normally and don't enter in the except block.
  •  If we have not made any except block, then python will handle exception automatically.
  • We can also accept more than one exception in the except by writing the name of the class separated by the ",". 
Some points about finally block:
  • This block always be executed, it doesn't matter whether the exception is occurred or not in our program.
  • finally always come after the except block.
  • finally works before the default exception catch mechanism of python.
  • try block should have at least one except or finally block.
  • We can't made more than one finally block.
  • If we made except by ourselves and exception occurs, then in this case, first except block will be executed and then finally block executed.
Note* We can also use else block with try block. else block will execute when there is no exception occurs in our program.
We have to write the else block before finally block and after except block.


try:


   """ write your code here""" 

except ExceptionClassName1: 

   """Write your code here""" 


except ExceptionClassName2: 

   """Write your code here" 

else:   

   """Write your code here"""

finally:

    """Write your code here"""
2/09/2019

Exception Handling

When a program terminates in abnormal condition, it is called exception.
The normal flow of the program is disturbed if any exception situation occurs in the program. The simplest example of exception situation is as:
e.g. Suppose we have to calculate a/b where a and b are entered by the user. What will  happen if user unknowingly enter the value of b 0. Exception will arise, because we can't divide any number by 0.

Our program will terminate from that line where exception is occurred.
Python has mechanism to deal such kinds of situation. We have 4 ways to deal with these kinds of situation.
  1. Python raise exception and also handle it implicitely
  2. Python raise raise exception and user handle it explicitely
  3. User raise exception and python handle it implicitely
  4. User raise exception and also handle it explicitely
 Exceptions can be of two types.
  1. Predefined Exceptions
  2. User defined Exceptions
The keywords that we will use in Exception handling are as follows:
  1. try
  2. except
  3. finally
  4. raise 



2/07/2019

Anonymous function (Lambda Expression)

Anonymous function is that function which has no name.
lambda keyword is used for defining anonymous function.

Script1: Write anonymous function to calculate the sum of two variables.

sm=lambda a,b: a+b
n1=int(input())
n2=int(input())
ans=sm(n1,n2)
print(ans)

Script2: Write anonymous function for calculating factorial of a given number.

f=lambda n: 1 if n==0 or n==1 else n*f(n-1)
n=int(input("Enter the number "))
ans=f(n)
print("The factorial of",n," is",ans)

Recursion

When a function calls itself, then this is called recursion.
These are some of the script which are illustrating the use of recursion.

Script1: Write an script to print natural numbers from 1 to n in descending order using recursion, the value of n will be entered by the user.

def printnatno(n):
    if n==0:
        return
    else:
        print(n)
        printnatno(n-1)

n=int(input("Enter the value of n "))

printnatno(n)


Script2: Write a function to calculate the factorial of a number using recursion.

def calfact(n):
    if n==0 or n==1:
        return 1
    else:
        return n*calfact(n-1)

n=int(input("Enter the number "))
ans=calfact(n)
print("The factorial of {} is {}".format(n,ans))

2/06/2019

Examples on functions

Script1: Write a function in python which can calculate the factorial of a number entered by the user.
def calfact(n):
    x=1
    while n!=1:
        x*=n
        n-=1
    return x

a=int(input("Enter the number "))

f=calfact(a)
print("The factorial is {}".format(f))

Script2: Write a function in python which can print the fibonacci series up to n numbers, value of n is entered by the user.
def printfibo(n):
    x=1
    y=2
    if n==1:
        print(x)
        return
    print(x,end=" ")
    print(y,end=" ")
    while n!=2:
        print(x+y,end=" ")
        x,y=y,x+y
        n-=1

n=int(input("Enter the number "))

printfibo(n)



Script3. Write a function which can decide whether the entered number by the user is prime or not.
def checkprime(n):
    i=2
    if n==1 or n==2:
        print("Number is prime")
        return
    while i!=n-1:
        if n%i==0:
            print("Number is not prime")
            break
        i+=1
    else:
        print("Number is prime")

x=int(input("Enter the number "))

checkprime(x)

Script4: Write a function which check whether the number entered by the user is armstrong or not.
def checkarmstrong(n):
    sum=0
    temp=n
    while n!=0:
        sum+=(n%10)**3
        n//=10
    if sum==temp:
        print("Number is armstrong")
    else:
        print("Number is not armstrong")

print("Enter the number ")

x=int(input())
checkarmstrong(x)

Script5: Write a function which check whether the entered string is palindrome or not.
def checkpalindrome(s):

    m=s[::-1]
    if m==s:
        print("String is palindrome")
    else:
        print("String is not palindrome")

print("Enter the string you want to check ")

x=input()
checkpalindrome(x)



2/05/2019

Variable length arguments

Variable length arguments:
If a function has variable length arguments, it means it has the capability to accept any number of arguments.
Variable length argument is prefixed with *.
The type of variable length argument is tuple.

Write a function which can return the sum of any number of arguments passed to it.
def f1(*a):
    return sum(a)

print(f1(2)) # 2
print(f1(2,3)) # 5
print(f1())  # 0


Note* In this case keyword argument is compulsory to set the value of second argument.
def f1(*m,s):
    print(m,s) # (2, 3, 4) 5

f1(2,3,4,s=5)


Variable length keyword arguments:
If we write ** then its type will be dictionary.
It always accepts keyword arguments.
If positional arguments are passed to it, it will shows error.

def f1(**x):
    print(x)

f1(a=2,b=3) # {'a': 2, 'b': 3}
f1(a=1,b=2,c=3) # {'a': 1, 'b': 2, 'c': 3}

f1(a=1,a=2) # will show error

Types of arguments in a function

There can be different types of arguments which a function can have. These are as follows:
  • Default arguments
  • Positional arguments
  • Keyword arguments
  • Variable length arguments
  • Variable length keyword arguments
Default arguments: The usage of default argument is shown below in the simple python script.

def addition(a,b,c=0):
    return a+b+c

x=addition(2,3)
y=addition(2,3,4)
print(x,y) # 5 9

Here addition function can accept maximum three arguments and minimum two arguments. If we pass only two arguments then third argument will automatically initialized to 0 and we get the sum of two arguments in return.
If we pass three arguments then third argument hold that value which is passed by us and in return we get the sum of three numbers.

Positional and keyword arguments:
def f1(x,y):
    print("x=",x,"y=",y)

f1(1,2) # Positional arguments
f1(x=1,y=2) # Keyword arguments
f1(y=1,x=2) # Keyword arguments

f1(x=1,y) # error comes
f1(3,x=3) # error comes
In keyword arguments order is not really important. You can pass the keyword argument in any order you want, but in case of positional arguments order matters.

Note* Positional arguments can never come after keyword arguments, if we do so error will come.

2/04/2019

Functions Introduction

Function is actually a block of code.
It increases the reusability of code in our script or program.
The syntax for function in the python language is as:
def f1():
    statement 1
    statement 2
A function can take any number of arguments.

Example1: Write an script to multiply two  numbers entered by the user.
def multiply(n1,n2):
    print("The multiplication is ",n1*n2)

a,b=int(input("enter first number")), int(input("Enter second number"))

multiply(a,b)

A function can also return any kind of data, means it can be used to return an integer, string, list tuple etc.

Example2: Write an script which return the factorial of a given number.
def fact(n):
    s=1
    while n!=1:
        s=s*n
        n-=1
    return s

x=int(input("Enter the number "))
f=fact(x)
print("factorial is",f)

Note* If a function does not return anything in python then it will automatically return None.


Input data structure from user

Reading multiple values:
There can be many ways to take multiple in inputs from the user. Some of them are shown below.
x,y=int(input("Enter first number")),int(input("Enter second number"))

x,y=input("Enter two numbers").split()


x,y=map(int,input().split())


Note* x,y=int(input("Enter two numbers")).split() is wrong. This will show ValueError.

Taking different Values as input using eval() method:
x,y,z=[eval(x) for x in input().split()]
If we give input: 1 2 "mayank"
x and y type are int and z type will be string automatically. We don't need any type of conversion here because we are using eval() function for that.

Taking list as input from user:
l=[eval(x) for x in input().split()]

l=list(map(int,input().split()))

Taking tuple as input from user:
t=tuple([eval(x) for x in input().split()])

t=tuple(map(int,input().split()))

Taking set as input from user:
s=set([eval(x) for x in input().split()])

s=set(map(int,input().split()))

Taking dictionary as input from user:
d={int(input("enter key ")) : input("enter value ") for i in range(3)}
Here second input() method execute before the first input() method.

d={x: input() for x in range(3)}

Here 0 1 and 2 will becomes key and values will be enter by user.