Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday, July 3, 2021

Python - Virtual env, pip freeze, Lambda function, join method, format method and map, filter, reduce

 Virtual Env:

An environment which is same as the system interpreter but is isolated from the other python environments on the system.

Installation:

to use virtual environment:

    pip install virtualenv

to create:

    virtualenv myprojectenv

to activate:

    activate

pip freeze:

It returns all the packages installed in a given env along with the versions.

    pip freeze > list.txt

we can share the this file to other user and they can recreate the same env using:

    pip install -r list.txt

Lambda function:

syntax:

    lambda arguments: expressions

instance:

    square = lambda a : a * a

    square(2) 

Join method:

It creates a string from iterable objects.

l=["apple","mango","banana"]

" and ".join(l)

output: "apple and mango and banana"

format method:

formats the values inside a string into a desired output.

template.format(arguments)

example:

"{} is a good {}".format("john","boy")

or

"{1} is a good {0}".format("boy","john")

output: john is a good boy

Map, filter and reduce:

Map:

map applies a function to all the items in a input list.

map(function,list)

Filter:

It creates a list of items for which the function returns true.

list(filter(function,list))

Reduce:

It applies a rolling computation to sequential pair of elements.

from functools import reduce

val=reduce(function, list)

if the function computes the sum of two numbers and the list is [1,2,3,4], the output will be 10.


Practice:

Create two virtual environments , install few packages in the first one. create a similar env in the 2nd one.

pip install virtualenv

virtualenv env1

virtualenv env2

.\env1\Scripts\activate.ps1

pip install pandas

pip freeze > 2.txt

deactivate

 .\env2\Scripts\activate.ps1

pip install -r .\2.txt

deactivate

WAP to input name, marks and phone numbers of a student and format it using the format function like "The name of the student is Sri and his marks are 65 and phone number is 0000000000.

nameinput("Please enter your name: ")
marksinput("Please enter your marks: ")
phoneinput("Please enter phone number: ")
template="the name of the Stdent is {} and his marks are {} and his phone number is {}."
print(template.format(name,marks,phone))


a list contains the multiplication table of 7. WAP to convert to a vertical string of the same numbers.

num = int(input("Enter a number: "))
table = [str(num * ifor i in range(1,11)]
print(table)
vertical="\n".join(table)
print(vertical)

WAP to filter a list of numbers which are divisible by 5.

myList=[1,2,4,6,7,8,9,123,54,67,90,45,5,56,50]

newList=filter(lambda a:a % 5 ==0,myList)

print(list(newList))

WAP to find the max of the numbers in a list using reduce function.

from functools import reduce
numberList=[1,2,4,6,7,8,9,123,54,67,90,45,5,56,50]

maxnumber=reduce(max,numberList)

print(maxnumber)







Thursday, July 1, 2021

Python - Exception handling

There are many built in exceptions which are raised in python when something goes wrong. Exceptions in python can be handled using a try statement. The code that handles the exception is written in the except clause.

try:

    #code

except Exception as e:

    print(e)

when the exception is handled the code flow continues without program interruption.

try:

    #code

except ZeroDivisionError:

    #code

except TypeError:

    #code

except:

    #code

Raising Exceptions:

We can raise custom exceptions using the raise keuword.

try with else clause:

sometimes we want to run a piece of code when try was successful.

try:

    #code

except:

    #code

else:

    #code

try with finally:

python offers a finally clause which ensures execution of a piece of code irrespective of the exception.

try:

    #code

except:

    #code

finally:

#code

if __name__ = '__main__':

__name__ evaluates to the name of the module in python from where the program is run. if the module is being run directly from the cmd line the __name__ is set to string "__main__".

thus this behaviour is used to check if the module is run directly or imported to another file.

Global keyword:

global keyword is used to modify the variable outside of the current scope.

enumerate function:

It adds counter to an iterable and returns it.

for i,item in enumerate(list1):

    print(i,item)

list comprehensions:

It is an elegant way to create lists based on existing lists.

list1=[1,7,12,11,22]

list2=[i for item in list1 if item >8]


Practice:

Write a program to open 3 files 1.txt,2.txt and 3.txt.if any one of the files do not present then a message without exiting the program must be printed prompting the same.

def readFile(fileName):
    try:    
        with open(fileName,'r'as f:
            print(f.read())
    except:
        print(f"the file {fileName} does not exist")


readFile("1.txt")
readFile("2.txt")
readFile("3.txt")       


WAP to print 3rd,5th and 7th element from a list using enumerate function.

myList=[1,2,3,4,5,6,7,8,8,9,10]

for i,item in enumerate(myList):
    if i==2 or i==4 or i==6:
        print(f"the {i+1} element is {item}")


Write a list comprehension to print a list which contains the multiplication table of a user entered number.


numint(input("Please enter a number: "))

table = [num*i for i in range(1,11) ]
print(table)

WAP to display a/b  where a and b are integers. if b=0, display infinite by handling the ZeroDivisionError.

aint(input("Please enter 1st number: "))
bint(input("Please enter 2nd number: "))

try:
    print(a/b)
except ZeroDivisionError:
    print("Infinite")
except Exception as e:
    print(e)
finally:
    print("Thanks!")



Wednesday, June 30, 2021

Python - Inheritance & more on OOPs

 Inheritance is a way of creating a new class from an existing class.

Syntax:

class Emoloyee: #Base Class

#Code

class Programmer(Employee): #Derived or child class

#Code

We can use the methods and attributes of Employee in Programmer object. Also, we can overwrite or add new attributes and methods in the Programmer class.


Type of Inheritance:

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance

Single Inheritance

Single inheritance occurs when child class inherits only a single parent class.

Base -> Derived


Multiple Inheritance:

Multiple inheritance occurs when the child class inherits from more than one parent class.

Multilevel Inheritance

When a child class becomes a parent for another child class.


Super() method

Super method is used to access the methods of a super class in the derived class.

super().__init__()  #Calls constructor of the base class


Class methods

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

@classmethod decorator is used to create a class method.

Syntax to create a class method:

@classmethod

def (cls, p1, p2):

#code

@property decorators

Consider the following class

class Employee:

@property 

def name(self):

return self.ename

if e = Employee() is an object of class employee, we can print (e.name) top print the ename/call name() function.


@.getters and @.setters

The method name with @property decorator is called getter method.

We can define a function + @name.setter decorator like below:

@name.setter

def name(self, value):

self.ename = value

Operator overloading in Python

Operators in python can be overloaded using dunder methods.

These methods are called when a given operator is used on the objects.

Operators in python can be overloaded using the following methods:

p1 + p2 -> p1.__add__(p2)

p1 – p2 -> p1.__sub__(p2)

p1 * p2 -> p1.__mul__(p2)

p1 / p2 -> p1.__truediv__(p2)

p1 // p2 -> p1.__floordiv__(p2)

Other dunder/magic methods in Python

__str__() -> used  to set what gets displayed upon calling str(obj)

__len__() -> used to set what gets displayed upon calling .__len__() or len(obj)

 

Practice:

Create a class C-2d vector and use it to create another class representing a 3-d vector.

class C2dVec:
    def __init__(selfij):
        self.icap = i
        self.jcap = j

    def __str__(self):
        return f"{self.icap}i + {self.jcap}j"

class C3dVec(C2dVec):
    def __init__(selfijk):
        super().__init__(ij)
        self.kcap = k
    
    def __str__(self):
        return f"{self.icap}i + {self.jcap}j + {self.kcap}k"
    
    
v2d = C2dVec(13)
v3d = C3dVec(197)
print(v2d)
print(v3d)

Create a class pets from a class Animals and further create class Dog from Pets. Add a method bark to class Dog.

class Animals:
    color = "White"

class Pets(Animals):
    @staticmethod
    def sleep():
        print("Pets are sleeping")


class Dog(Pets):
    
    @staticmethod
    def bark():
        print("Dog is barking Bow Bow")

d = Dog()
print(d.color)
d.sleep()
d.bark()

Create a class Employee and add salary and increment properties to it.

Write a method SalaryAfterIncrement method with a @property decorator with a setter which changes the value of increment based on the salary.

class Employee:
    salary2000
    increments=1.5

    @property
    def salaryAfterIncrements(self):
        return self.salary * self.increments

    @salaryAfterIncrements.setter
    def salaryAfterIncrements(selfsal):
        self.incrementssal / self.salary

e = Employee()
print(e.salaryAfterIncrements)
print(e.increments)
e.salaryAfterIncrements=5000
print(e.salaryAfterIncrements)
print(e.increments)

Write a class complex to represent complex numbers, along with overloaded operators + and * which adds and multiplies them.

class Complex:
    def __init__(selfij):
        self.i =i
        self.j=j
    
    def __add__(self,obj2):
        return Complex(self.i + obj2.i, self.j + obj2.j)
    def __str__(self):
        return f"{self.i} + {self.j}i"
c1=Complex(2,3)
c2=Complex(3,4)
print(c1 + c2)



Sunday, June 6, 2021

Python - Object-Oriented Programming

Solving a problem by creating objects is one of the most popular approaches in programming. This is called object-oriented programming.This concept focuses on using reusable code. (Implements DRY principle)

Class

A class is a blueprint for creating objects.

The syntax of a class looks like this:

Class Employee: [classname is written in PascalCase]

#methods & variables

Object

An object is an instantiation of a class. When class is defined, a template(info) is defined. Memory is allocated only after object instantiation.

Objects of a given class can invoke the methods available to it without revealing the implementation details to the user.     #Abstraction & Encapsulation!

Modelling a problem in OOPs

We identify the following in our problem

Noun -> Class -> Employee

Adjective -> Attributes -> name,age,salary

Verbs -> Methods -> getSalary(), increment()


Class Attributes

An attribute that belongs to the class rather than a particular object.

Example:

Class Employee:

company = “Google” #Specific to each class

harry = Employee() #Object instantiation

harry.company

Employee.company = “YouTube” #changing class attribute

Instance Attributes

An attribute that belongs to the Instance (object)

Assuming the class from the previous example:

harry.name = “Harry”

harry.salary = “30K” #Adding instance attributes

Note: Instance attributes take preference over class attributes during assignment and retrieval.


‘self’ parameter:

self refers to the instance of the class.

It is automatically passed with a function call from an object.

harry.getSalary()

here, self is harry and above line of code is equivalent to Employee.getSalary(harry)

This function getsalary is defined as:

class Employee:

company = “Google”

def getSalary(self):

print(“Salary is not there”)

Static method:

Sometimes we need a function that doesn’t use the self-parameter. We can define a static method like this:

@staticmethod #decorator to mark greet as a static method

def greet():

print(“Hello user”)


__init__() constructor:

  • __init__() is a special method which runs as soon as the object is created.
  • __init__() method is also known as constructor.
  • It takes self-argument and can also take further arguments.

For Example:

class Employee:

def __init__(self,name):

self.name = name

def getSalary(self):

#Some code…

harry = Employee(“Harry”) #Object can be instantiated using constructor like this!

 


Practice:

Create a class programmer for storing information of a few programmers working at Microsoft.

class Programmer:
    company = "Microsoft"
    def __init__(self,name,product):
        self.name=name
        self.product=product

    def getInfo(self):
        print(f"name of the companty {self.company} and name is {self.name} and product is {self.product}")

sri=Programmer("Sri","Skype")
nanda=Programmer("Nannda","Outlook")
print(sri.getInfo())
print(nanda.getInfo())

Write a class calculator capable of finding square, cube and the square root of a number.

class Calculator:

    def __init__(self,num):
        self.num=num
    def getSquare(self):
        return self.num * self.num

    def getCube(self):
        return self.num ** 3

    def getSqrRoot(self):
        return  self.num * 0.5

c=Calculator(5)
print(c.getSquare())
print(c.getCube())
print(c.getSqrRoot())

Create a class with a class attribute a; create an object from it and set a directly using object.a=0 Does this change the class attribute?

class Sample:
    a=23

s = Sample()
s.a=0
print(Sample.a)
print(s.a)

Answer: No, This will not change the class attribute.

Add a static method in problem 2 to greet the user with hello.

class Calculator:

    def __init__(self,num):
        self.num=num
    def getSquare(self):
        return self.num * self.num

    def getCube(self):
        return self.num ** 3

    def getSqrRoot(self):
        return  self.num * 0.5
    
    @staticmethod
    def greetUser():
        print("Hello user")

c=Calculator(5)
c.greetUser()
print(c.getSquare())
print(c.getCube())
print(c.getSqrRoot())

Write a class Train which has methods to book a ticket, get status(no of seats), and get fare information of trains running under Indian Railways.

class Train:

    def __init__(self, name, fare, seats):

        self.name = name

        self.fare = fare

        self.seats = seats


    def getStatus(self):

        print("************")

        print(f"The name of the train is {self.name}")

        print(f"The seats available in the train are {self.seats}")

        print("************")


    def fareInfo(self):

        print(f"The price of the ticket is: Rs {self.fare}")


    def bookTicket(self):

        if(self.seats>0):

            print(f"Your ticket has been booked! Your seat number is {self.seats}")

            self.seats = self.seats - 1

        else:

            print("Sorry this train is full! Kindly try in tatkal")


    def cancelTicket(self, seatNo):

        pass


intercity = Train("Intercity Express: 14015", 90, 2)

intercity.getStatus() 

intercity.bookTicket()

intercity.bookTicket()

intercity.bookTicket()

intercity.getStatus()


 


Sunday, May 23, 2021

python - Install required software and validation

Step1:  Search "python install" in Browser and download python 3.9.5(www.python.org)

during installation, 

  • checked the option - add python 3.9 to path
  • install now 
  • yes
  • close

Step2: Search "VS Code install" in browser. (IDE cum source code editor)code.visualstudio.com

For my case, its windows 64 bit. (my pc --> right click properties-->check 32/64 bit)

During installation,

  • I accept the agreement
  • check all the 4 options in delect additional sections
  • next 
  • install
  • uncheck launch vs code
  • finish

Step3: open windows power shell/CMD and validate as following:

>python

>>>exit()

>python --version

python 3.9.5

>pip






Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...