python in Handling Exceptions try…except try…finally by unitdiploma

•Handling Exceptions

•try…except

•try…finally

Errors and Exceptions

Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of

Errors: syntax errors and exceptions.

 while True print(‘Hello world’)

  File “<stdin>”, line 1

while True print(‘Hello world’)

                ^

SyntaxError: invalid syntax

•The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected.

•The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the function print(),

•since a colon (‘:’) is missing before it.

•File name and line number are printed so you know where to look in case the input came from a script.

Exceptions

•Even if a statement or expression is syntactically correct.

•It may cause an error when an attempt is made to execute it.

•Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs.

•Most exceptions are not handled by programs, however, and result in error messages as shown here:

1..>>> 10 * (1/0)

Traceback (most recent call last):

  File “<stdin>”, line 1, in <module>

ZeroDivisionError: division by zero

2..>>> 4 + spam*3

Traceback (most recent call last):

  File “<stdin>”, line 1, in <module>

NameError: name ‘spam’ is not defined

3..>>> ‘2’ + 2

Traceback (most recent call last):

  File “<stdin>”, line 1, in <module>

TypeError: Can’t convert ‘int’ object to str implicitly

Built-in Exceptions

•In Python, all exceptions must be instances of a class that derives from BaseException.

•In a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived).

•Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.

•exception Exception

•All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.

•exception ArithmeticError

•The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError.

•exception BufferError

•Raised when a buffer related operation cannot be performed.

•exception LookupError

•The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by codecs.lookup().

Built-in Exceptions Contd…

•Concrete exceptions

•The following exceptions are the exceptions that are usually raised.

•exception AssertionError

•Raised when an assert statement fails.

•exception AttributeError

•Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.)

•exception EOFError

•Raised when the input() function hits an end-of-file condition (EOF) without reading any data. (N.B.: the io.IOBase.read() and io.IOBase.readline() methods return an empty string when they hit EOF.)

•exception FloatingPointError

•Not currently used.

•exception GeneratorExit

•Raised when a generator or coroutine is closed; see generator.close() and coroutine.close(). It directly inherits from BaseException instead of Exception since it is technically not an error.

•exception ImportError

•Raised when the import statement has troubles trying to load a module. Also raised when the “from list” in from … import has a name that cannot be found.

•The name and path attributes can

Handling Exceptions

•It is possible to write programs that handle selected exceptions.

•Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

 while True:

… try:

…     x = int(input(“Please enter a number: “))

…     break

… except ValueError:

…     print(“Oops!  That was no valid number.  Try again…”)

Handling Exceptions Contd…

•First, the try clause (the statement(s) between the try and except keywords) is executed.

•If no exception occurs, the except clause is skipped and execution of the try statement is finished.

•If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.

•If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

Examples

Example 1

for arg in sys.argv[1:]:

try:

     f = open(arg, ‘r’)

except OSError:

     print(‘cannot open’, arg)

else:

     print(arg, ‘has’, len(f.readlines()), ‘lines’)

     f.close()

Example 2

def this_fails():

… x = 1/0

>>> try:

… this_fails()

… except ZeroDivisionError as err:

… print(‘Handling run-time error:’, err)

Handling run-time error: division by zero

Example 3

a = [1, 2, 3]

try: 

print “Second element = %d” %(a[1])

# Throws error since there are only 3 elements in array

print “Fourth element = %d” %(a[3]) 

except IndexError:

print “An error occurred”

User Define Exception

•Programmers may name their own exceptions by creating a new exception class.

•Exceptions need to be derived from the Exception class, either directly or indirectly.

•Although not mandatory, most of the exceptions are named as names that end in “Error” similar to naming of the standard exceptions in python. 

Example

#A python program to create user-defined exception

 # class MyError is derived from super class Exception

class MyError(Exception):

  # Constructor or Initializer

def __init__(self, value):

     self.value = value

   # __str__ is to print() the value

def __str__(self):

     return(repr(self.value))

  try:

raise(MyError(3*2))

# Value of Exception is stored in error

except MyError as error:

print(‘A New Exception occured: ‘,error.value

Output (‘A New Exception occured: ‘, 6)

python in Data Hiding Method Overriding Polymorphism Method Overriding by unitdiploma

Data Hiding

•Method Overriding

•Polymorphism

Method Overriding

• We can provide some specific implementation of the parent class method in our child class.

•When the parent class method is defined in the child class with some specific implementation, then the concept is called method overriding.

•We may need to perform method overriding in the scenario where the different definition of a parent class method is needed in the child class.

Example of Method Overriding

class Animal:  

    def speak(self):  

        print(“speaking”)  

class Dog(Animal):  

    def speak(self):  

        print(“Barking”)  

d = Dog()  

d.speak()  

Output:  Barking

Real Life Example of method overriding

class Bank:  

    def getroi(self):  

        return 10;  

class SBI(Bank):  

    def getroi(self):  

        return 7;  

class ICICI(Bank):  

    def getroi(self):  

        return 8;  

b1 = Bank()  

b2 = SBI()  

b3 = ICICI()  

print(“Bank Rate of interest:”,b1.getroi());  

print(“SBI Rate of interest:”,b2.getroi());  

print(“ICICI Rate of interest:”,b3.getroi()); 

Data abstraction in python

•Abstraction is an important aspect of object-oriented programming.

•In python, we can also perform data hiding by adding the double underscore (___) as a prefix to the attribute which is to be hidden.

•After this, the attribute will not be visible outside of the class through the object.

Example of Data abstraction in python

class Employee:  

    __count = 0;  

    def __init__(self):  

        Employee.__count = Employee.__count+1  

    def display(self):  

        print(“The number of employees”,Employee.__count)  

emp = Employee()  

emp2 = Employee()  

try:  

    print(emp.__count)  

finally:  

    emp.display()  

Output

The number of employees 2 AttributeError: ‘Employee’ object has no attribute ‘__count’

Polymorphism

•Polymorphism and Method Overriding

•In literal sense, Polymorphism means the ability to take various forms.

•In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class.

•As we know, a child class inherits all the methods from the parent class.

Method Overloading

# Python program to demonstrate in-built poly-

# morphic functions

  # len() being used for a string

print(len(“geeks”))

  # len() being used for a list

print(len([10, 20, 30]))

Example of Method Overloading

def add(x, y, z = 0): 

    return x + y + z

  # Driver code 

print(add(2, 3))

print(add(2, 3, 4)) 

Polymorphism with Inheritance

•In Python, Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class.

•In inheritance, the child class inherits the methods from the parent class. However, it is possible to modify a method in a child class that it has inherited from the parent class.

•This is particularly useful in cases where the method inherited from the parent class doesn’t quite fit the child class.

•In such cases, we re-implement the method in the child class.

•This process of re-implementing a method in the child class is known as Method Overriding.

Example of Polymorphism with Inheritance

class Bird:

  def intro(self):

    print(“There are many types of birds.”)

       def flight(self):

    print(“Most of the birds can fly but some cannot.”)

    class sparrow(Bird):

  def flight(self):

    print(“Sparrows can fly.”)

  class ostrich(Bird):

  def flight(self):

    print(“Ostriches cannot fly.”)

     obj_bird = Bird()

obj_spr = sparrow()

obj_ost = ostrich()

 obj_bird.intro()

obj_bird.flight()

 obj_spr.intro()

obj_spr.flight()

 obj_ost.intro()

obj_ost.flight() 

Output

•There are many types of birds.

• Most of the birds can fly but some cannot. There are many types of birds.

• Sparrows can fly.

•There are many types of birds.

•Ostriches cannot fly.

Constructor Overriding

#constructor overriding

class father:

   def __init__(self):

   self.p=10

   def disp(self):

   print(self.p)

class son(father):

def __init__(self):

         self.p1=20

def disp(self):

     print(self.p1)

s=son()

s.disp()

super() method

#using super() method

class father:

   def __init__(self,p=0):

   self.p=p

   def disp(self):

   print(self.p)

class son(father):

def __init__(self,p1=0,p=0):

     super().__init__(p)

     self.p1=p1

def disp(self):

     print(self.p+self.p1)

s=son(10,20)

s.disp()

Problems in multiple inheritance

#using super() method

class Gfather:

   def __init__(self):

   self.p1=’a’

   print(self.p1)

   class father:

   def __init__(self):

   self.p2=’b’

   print(self.p2)

class son(Gfather,father):

def __init__(self):

     super().__init__()

     self.p3=’c’

     print(self.p3)

s=son()

“””output

c

a”””

Method resolution order(MRO)

#using super() method

class Gfather:

   def __init__(self):

   self.p1=’a’

   print(self.p1)

   super().__init__()

  class father:

   def __init__(self):

     self.p2=’b’

   print(self.p2)

   super().__init__()

class son(Gfather,father):

def __init__(self):

       self.p3=’c’

     print(self.p3)

     super().__init__()

s=son()

Output– c  a  b

bython in Constructor Destructor Inheritence in hindi by unitdiploma

•Constructor

•Destructor

•Inheritence

Constructor

•Constructors are generally used for instantiating an object.

•The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created.

•In Python the __init__() method is called the constructor and is always called when an object is created.

Syntax of constructor declaration :

  def __init__(self):   # body of the constructor

Types of Construtor

default constructor

•The default constructor is simple constructor which doesn’t accept any arguments.

•It’s definition has only one argument which is a reference to the instance being constructed.

parameterized constructor

 

•constructor with parameters is known as parameterized constructor.

•The parameterized constructor take its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.

The___init___() function

•To understand the meaning of classes we have to understand the built-in __init__() function.

•All classes have a function called __init__(), which is always executed when the class is being initiated.

•Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

Example:

class Person:

  def __init__(self, name, age):

    self.name = name

    self.age = age

p1 = Person(“John”, 36)

print(p1.name)

print(p1.age)

The __init__() function is called automatically every time the class is being used to create a new object. 

Destructors

•Destructors are called when an object gets destroyed.

•In Python, destructors are not needed as much needed in C++ because Python has a garbage collector that handles memory management automatically.

•The __del__() method is a known as a destructor method in Python.

•It is called when all references to the object have been deleted i.e when an object is garbage collected.

Syntax of destructor declaration :

•def __del__(self): # body of destructor

Note : A reference to objects is also deleted when the object goes out of reference or when the program ends.

Data Abstraction

•Data abstraction and encapsulation both are often used as synonyms.

•Both are nearly synonym because data abstraction is achieved through encapsulation.

•Abstraction is used to hide internal details and show only functionalities.

•Abstracting something means to give names to things so that the name captures the core of what a function or a whole program does.

Inheritance

•Inheritance allows us to define a class that inherits all the methods and properties from another class.

•Parent class is the class being inherited from, also called base class.

•Child class is the class that inherits from another class, also called derived class

Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:

class Person:

  def __init__(self, fname, lname):

         self.firstname = fname

         self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person(“John”, “Doe”)

x.printname() 

Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:

class Student(Person):

  pass

Use the Student class to create an object, and then execute the printname method:

x = Student(“Mike”, “Olsen”)

x.printname() 

Single Inheritance

class Animal:  

    def speak(self):  

        print(“Animal Speaking”)  

#child class Dog inherits the base class Animal  

class Dog(Animal):  

    def bark(self):  

        print(“dog barking”)  

d = Dog()  

d.bark()  

d.speak()

Multiple Inheritance

class Animal:  

    def speak(self):  

        print(“Animal Speaking”)  

#The child class Dog inherits the base class Animal  

class Dog(Animal):  

    def bark(self):  

        print(“dog barking”)  

#The child class Dogchild inherits another child class Dog  

class DogChild(Dog):  

    def eat(self):  

        print(“Eating bread…”)  

d = DogChild()  

d.bark()  

d.speak()  

d.eat()

Multiple Inheritance Contd..

class Calculation1:  

    def Summation(self,a,b):  

        return a+b;  

class Calculation2:  

    def Multiplication(self,a,b):  

        return a*b;  

class Derived(Calculation1,Calculation2):  

    def Divide(self,a,b):  

        return a/b;  

d = Derived()  

print(d.Summation(10,20))  

print(d.Multiplication(10,20))  

print(d.Divide(10,20)) 

The issubclass(sub, sup) method

The issubclass(sub, sup) method is used to check the relationships between the

 specified classes. It returns true if the first class is the subclass of the second class, and false otherwise.

class Calculation1:  

    def Summation(self,a,b):  

        return a+b;  

class Calculation2:  

    def Multiplication(self,a,b):  

        return a*b;  

class Derived(Calculation1,Calculation2):  

    def Divide(self,a,b):  

        return a/b;  

d = Derived()  

print(issubclass(Derived,Calculation2))  

print(issubclass(Calculation1,Calculation2)

The isinstance (obj, class) method

The isinstance() method is used to check the relationship between the objects and classes. It returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e., class.

class Calculation1:  

    def Summation(self,a,b):  

        return a+b;  

class Calculation2:  

    def Multiplication(self,a,b):  

        return a*b;  

class Derived(Calculation1,Calculation2):  

    def Divide(self,a,b):  

        return a/b;  

d = Derived()  

print(isinstance(d,Derived)

python Classes and Objects Encapsulation in hindi

•Classes and Objects

•Encapsulation

Class

•The class can be defined as a collection of objects.

•It is a logical entity that has some specific attributes and methods.

•For example: if you have an employee class then it should contain an attribute and method, i.e. an email id, name, age, salary, etc.

Example

class ClassName:   

        <statement-1>   

        .   

        .    

        <statement-N> 

Example of Class

class Test:

    # A sample method 

    def fun(self):

        print(“Hello”)

# Driver code

obj = Test()

obj.fun()

Object

•The object is an entity that has state and behavior.

•It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.

•Everything in Python is an object, and almost everything has attributes and methods.

•All functions have a built-in attribute __doc__, which returns the doc string defined in the function source code.

Method

•The method is a function that is associated with an object.

•In Python, a method is not unique to class instances.

•Any object type can have methods.

Encapsulation

  • Encapsulation is also an essential aspect of object-oriented programming. 
  • It is used to restrict access to methods and variables. 
  • In encapsulation, code and data are wrapped together within a single unit from being modified by accident.

Data Abstraction

•Data abstraction and encapsulation both are often used as synonyms.

•Both are nearly synonym because data abstraction is achieved through encapsulation.

•Abstraction is used to hide internal details and show only functionalities.

•Abstracting something means to give names to things so that the name captures the core of what a function or a whole program does.

python in Object Oriented Programming Concepts by unitdiploma

•Object Oriented Programming Concepts

Oops Concepts

Like other general-purpose programming languages, Python is also an object-oriented language since its beginning. It allows us to develop applications using an Object-Oriented approach. In Python, we can easily create and use classes and objects.

An object-oriented paradigm is to design the program using classes and objects. The object is related to real-word entities such as book, house, pencil, etc. The oops concept focuses on writing the reusable code. It is a widespread technique to solve the problem by creating objects.

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

  • Class
  • Object
  • Method
  • Inheritance
  • Polymorphism
  • Data Abstraction
  • Encapsulation

Class & Object

Class

The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. For example: if you have an employee class, then it should contain an attribute and method, i.e. an email id, name, age, salary, etc.

Syntax

class ClassName:     

        <statement-1>     

        .     

        .      

        <statement-N>     

Object

The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the function source code.

When we define a class, it needs to create an object to allocate the memory. Consider the following example.

Example:

class car:  

    def __init__(self,modelname, year):  

        self.modelname = modelname  

        self.year = year  

    def display(self):  

        print(self.modelname,self.year)  

c1 = car(“Toyota”, 2016)  

c1.display()  

Output:

Toyota 2016

Method & Inheritance

Method

The method is a function that is associated with an object. In Python, a method is not unique to class instances. Any object type can have methods.

Inheritance

Inheritance is the most important aspect of object-oriented programming, which simulates the real-world concept of inheritance. It specifies that the child object acquires all the properties and behaviors of the parent object.

By using inheritance, we can create a class which uses all the properties and behavior of another class. The new class is known as a derived class or child class, and the one whose properties are acquired is known as a base class or parent class.

It provides the re-usability of the code.

Polymorphism

  • Polymorphism contains two words “poly” and “morphs”. 
  • Poly means many, and morph means shape. 
  • By polymorphism, we understand that one task can be performed in different ways. 
  • For example – you have a class animal, and all animals speak. But they speak differently. 
  • Here, the “speak” behavior is polymorphic in a sense and depends on the animal. So, the abstract “animal” concept does not actually “speak”, but specific animals (like dogs and cats) have a concrete implementation of the action “speak”.

Encapsulation & Data Abstraction

Encapsulation

Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.

Data Abstraction

Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms because data abstraction is achieved through encapsulation.

Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names to things so that the name captures the core of what a function or a whole program does.

Object-oriented vs. Procedure-oriented Programming languages

The difference between object-oriented and procedure-oriented programming is given below:

IndexObject-oriented ProgrammingProcedural Programming
1.Object-oriented programming is the problem-solving approach and used where computation is done by using objects.Procedural programming uses a list of instructions to do computation step by step.
2.It makes the development and maintenance easier.In procedural programming, It is not easy to maintain the codes when the project becomes lengthy.
3.It simulates the real world entity. So real-world problems can be easily solved through oops.It doesn’t simulate the real world. It works on step by step instructions divided into small parts called functions.
4.It provides data hiding. So it is more secure than procedural languages. You cannot access private data from anywhere.Procedural language doesn’t provide any proper way for data binding, so it is less secure.
5.Example of object-oriented programming languages is C++, Java, .Net, Python, C#, etc.Example of procedural languages are: C, Fortran, Pascal, VB etc. 

python module in hindi by unitdiploma

  • Built-in Modules
  • Import statement
  • Packages
  • Date and Time Module

Python Module

A python module can be defined as a python program file which contains a python code including python functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is treated as the module. We may have a runnable code inside the python module.

Modules in Python provides us the flexibility to organize the code in a logical way.

To use the functionality of one module into another, we must have to import the specific module.

Example

In this example, we will create a module named as file.py which contains a function func that contains a code to print some message on the console.

Let’s create the module named as file.py.

1.#displayMsg prints a message to the name being passed.  

2.def displayMsg(name) 

3.  print(“Hi “+name);   

Here, we need to include this module into our main module to call the method displayMsg() defined in the module named file.

Loading the module in our python code

We need to load the module in our python code to use its functionality. Python provides two types of statements as defined below.

1.  The import statement

2. The from-import statement

The import statement

The import statement is used to import all the functionality of one module into another. Here, we must notice that we can use the functionality of any python source file by importing that file as the module into another python source file.

We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it has been imported into our file.

The syntax to use the import statement is given below.

1.  import module1,module2,…….. module n 

Hence, if we need to call the function displayMsg() defined in the file file.py, we have to import that file as a module into our module as shown in the example below.

Example:

1.  import file; 

2.  name = input(“Enter the name?”) 

3.  file.displayMsg(name)

Output:

Enter the name?John

Hi John

The from-import statement

Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. This can be done by using from? import statement. The syntax to use the from-import statement is given below.

1.from < module-name> import <name 1>, <name 2>..,<name n>  

Consider the following module named as calculation which contains three functions as summation, multiplication, and divide.

calculation.py:

1.  #place the code in the calculation.py  

2.  def summation(a,b): 

3.  return a+b 

4.  def multiplication(a,b): 

5.  return a*b; 

6.  def divide(a,b): 

7.  return a/b;

Main.py:

1.  from calculation import summation   

2.  #it will import only the summation() from   calculation.py 

3.  a = int(input(“Enter the first number”)) 

4.  b = int(input(“Enter the second number”)) 

5.  print(“Sum = “,summation(a,b)) #we do not need to specify the module name while accessing summation()

Output:

Enter the first number10

Enter the second number20

Sum =  30

The from…import statement is always better to use if we know the attributes to be imported from the module in advance. It doesn’t let our code to be heavier. We can also import all the attributes from a module by using *.

Consider the following syntax.

1.  from <module> import *

Renaming a module

Python provides us the flexibility to import some module with a specific name so that we can use this name to use that module in our python source file.

The syntax to rename a module is given below.

1.import <module-name> as <specific-name>

Example

1.  #the module calculation of previous example is imported in this   example as cal.  

2.  import calculation as cal; 

3.  a = int(input(“Enter a?”)); 

4.  b = int(input(“Enter b?”)); 

5.  print(“Sum = “,cal.summation(a,b)) 

Output:

Enter a?10

Enter b?20

Sum =  30

Using dir() function

The dir() function returns a sorted list of names defined in the passed module. This list contains all the sub-modules, variables and functions defined in this module.

Consider the following example.

Example

1.  import json  

3.  List = dir(json)   

5.  print(List) 

Output:

[‘JSONDecoder’, ‘JSONEncoder’, ‘__all__’, ‘__author__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’,

‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__path__’, ‘__spec__’, ‘__version__’,

‘_default_decoder’, ‘_default_encoder’, ‘decoder’, ‘dump’, ‘dumps’, ‘encoder’, ‘load’, ‘loads’, ‘scanner’]

The reload() function

As we have already stated that, a module is loaded once regardless of the number of times it is imported into the python source file. However, if you want to reload the already imported module to re-execute the top-level code, python provides us the reload() function. The syntax to use the reload() function is given below.

1.  reload(<module-name>) 

for example, to reload the module calculation defined in the previous example, we must use the following line of code.

1.  reload(calculation)

Python packages

The packages in python facilitate the developer with the application development environment by providing a hierarchical directory structure where a package contains sub-packages, modules, and sub-modules. The packages are used to categorize the application level code efficiently.

Let’s create a package named Employees in your home directory. Consider the following steps.

1.Create a directory with name Employees on path /home.

2.Create a python source file with name ITEmployees.py on the path /home/Employees.

ITEmployees.py

1.  def getITNames(): 

2.  List = [“John”, “David”, “Nick”, “Martin”] 

3.  return List; 

  3. Similarly, create one more python file with name   BPOEmployees.py and create a function   getBPONames().

4.Now, the directory Employees which we have created in the first step contains two python modules. To make this directory a package, we need to include one more file here, that is __init__.py which contains the import statements of the modules defined in this directory.

__init__.py

1.  from ITEmployees import getITNames 

2.  from BPOEmployees import getBPONames 

5.Now, the directory Employees has become the package containing two python modules. Here we must notice that we must have to create __init__.py inside a directory to convert this directory to a package.

6.To use the modules defined inside the package Employees, we must have to import this in our python source file. Let’s create a simple python source file at our home directory (/home) which uses the modules defined in this package.

Test.py

1.  import Employees 

2.  print(Employees.getNames()) 

Output:

[‘John’, ‘David’, ‘Nick’, ‘Martin’]

We can have sub-packages inside the packages. We can nest the packages up to any level depending upon the application requirements.

The following image shows the directory structure of an application Library management system which contains three sub-packages as Admin, Librarian, and Student. The sub-packages contain the python modules.

Python datetime

Python provides the datetime module work with real dates and times. In real-world applications, we need to work with the date and time. Python enables us to schedule our Python script to run at a particular timing.

In Python, the date is not a data type, but we can work with the date objects by importing the module named with datetime, time, and calendar.

Example1-Get Current date & Time

import datetime

cdtime = datetime.datetime.now()

print(cdtime)

Output:

2020-09-01 10:18:36.461122

we have imported datetime module using import datetime statement.

One of the classes defined in the datetime module is datetime class. We then used now() method to create a datetime object containing the current local date and time.

Example2-Get Current date

import datetime

date1 = datetime.date.today()

print(date1)

Output:

2020-09-01

In this program, we have used today() method defined in the date class to get a date object containing the current local date.

Commonly used classes in the datetime module are:

•date Class

•time Class

•datetime Class

•timedelta Class

datetime.date Class

You can instantiate date objects from the date class. A date object represents a date (year, month and day).

Example 3: Date object to represent a date

import datetime

d = datetime.date(2020, 1, 7)

print(d)

Output:

2020-01-07

We can only import date class from the datetime module. Here’s how:

from datetime import date

a = date(2020, 4, 13)

print(a)

Output:

2020-04-13

Python datetime Contd..

Example: Print today’s year, month and day

We can get year, month, day, day of the week etc. from the date object easily.

from datetime import date

# date object of today’s date

today = date.today()

print(“Current year:”, today.year)

print(“Current month:”, today.month)

print(“Current day:”, today.day)

Output:

Current year: 2020

Current month: 9

Current day: 1

Example : Print hour, minute, second and microsecond

time object, you can easily print its attributes such as hour, minute etc.

from datetime import time

a = time(11, 34, 56)

print(“hour =”, a.hour)

print(“minute =”, a.minute)

print(“second =”, a.second)

print(“microsecond =”, a.microsecond)

Output:

hour = 11

minute = 34

second = 56

microsecond = 0

The calendar module

Python provides a calendar object that contains various methods to work with the calendars.

Example: Print the calendar for the month August-2020.

import calendar   

cal = calendar.month(2020,8)   

#printing the calendar of August 2020  

print(cal)  

Output:

Example : Print the calendar of year2020

import calendar   

#printing the calendar of the year 2020 

s = calendar.prcal(2020)

python File Handling in hindi

Introduction to File Handling

•File Operations

•Directories

File Handling

Files are named locations on disk to store related information. They are used to permanently store data in a non-volatile memory (e.g. hard disk).

  • Since Random Access Memory (RAM) is volatile, we use files for future use of the data by permanently storing them.
  • File handling provides a mechanism to store the output of a program in a file and to perform various operations on it.

File Types

Text files

In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default. Text file has extension .txt.

Binary files

In this type of file, there is no terminator for a line and   the   data is stored after converting it into machine   understandable binary language. Binary files have an   extension .bin.

File Operation

In Python, a file operation takes place in the following order:

1.  Open a file

2.  Read or write (perform operation)

3.  Close the file

File Handling Method

Python provides the open() function which accepts two arguments, file name and access mode in which the file is accessed. The function returns a file object which can be used to perform various operations like reading, writing, etc.

The syntax to use the open() function—-

file object = open(<file-name>, <accessmode>, <buffering>) 

The files can be accessed using various modes like read, write, or append.

The following are the details about the access mode to open a file.

SNAccess modeDescription
1rIt opens the file to read-only. The file pointer exists at the beginning. The file is by default open in this mode if no access mode is passed.
2rbIt opens the file to read only in binary format. The file pointer exists at the beginning of the file.
3r+It opens the file to read and write both. The file pointer exists at the beginning of the file.
4rb+It opens the file to read and write both in binary format. The file pointer exists at the beginning of the file.
5wIt opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file.
6wbIt opens the file to write only in binary format. It overwrites the file if it exists previously or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file.
7w+It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous file if one exists whereas r+ doesn’t overwrite the previously written file. It creates a new file if no file exists. The file pointer exists at the beginning of the file.
8wb+It opens the file to write and read both in binary format. The file pointer exists at the beginning of the file.
9aIt opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name.
10wIt opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file.
11abIt opens the file in the append mode in binary format. The pointer exists at the end of the previously written file. It creates a new file in binary format if no file exists with the same name.
12a+It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It creates a new file if no file exists with the same name.
13ab+It opens a file to append and read both in binary format. The file pointer remains at the end of the file.

File Handling Method Contd…

To open a file named “file.txt” (stored in the same directory) in read mode and printing its content on the console.

#opens the file file.txt in read mode  

fileptr = open(“file.txt”,”r”)  

if fileptr:  

    print(“file is opened successfully”) 

Output:

<class ‘_io.TextIOWrapper’>

file is opened successfully

The close() method

Once all the operations are done on the file, we must close it through our python script using the close() method. Any unwritten information gets destroyed once the close() method is called on a file object.

We can perform any operation on the file externally in the file system is the file is opened in python, hence it is good practice to close the file once all the operations are done.

The syntax to use the close() method is —

  fileobject.close()  

Example

# opens the file file.txt in read mode  

fileptr = open(“file.txt”,”r”)  

if fileptr:  

    print(“file is opened successfully”)  

#closes the opened file  

fileptr.close()  

File Handling Method Contd…

Reading the File

To read a file using the python script, the python provides us the read() method. The read() method reads a string from the file. It can read the data in the text as well as binary format.

The syntax of the read() method is —-

fileobj.read(<count>)

Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If the count is not specified, then it may read the content of the file until the end.

Reading from a file

There are three ways to read data from a text file.

1.  Using read()

2.  Using readline()

3.  Using readlines()

Files

read() :

The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.

  File.read([size])

  Where, size is optional. The number of bytes to return. Default -1, which means the whole file.

Example:  #opening file in reading mode

file1 = open(“mydata.txt”,”r”)

print(“Output of read()”)

print(“—————————–“)

#To read entire file using read()

print(file1.read())

file1.close()  # closing the file

To run this program,

•Create new file using notepad.

•Type some content in the file.

•Save the file with name – mydata.

•Location of mydata file and program must be the same.

•If you save the mydata file at desktop, then save the python file also on desktop.

Example:  Reading 7 character using read(7)

#opening file in reading mode

file1 = open(“mydata.txt”,”r”)

print(“Output of read()”)

print(“—————————–“)

#print(“Output of read(7)”)

print(file1.read(7))

file1.close()

readline() :

The readline() method returns one line from the file. You can also specified how many bytes from the line to return, by using the size parameter

Syntax:   File.readline([size])

Where, size is optional. The number of bytes from the line to return. Default -1, which means the whole line.

Example 1: 

file1 = open(“mydata.txt”,”r”)

print(“Calling readline() to return  the first line only:”)

print(file1.readline())

file1.close()  # closing the file

Example:

print(“Return only the six first bytes from the first line:”)

print(file1.readline(6))

readlines():

Reads all the lines and return them as each line a string element in a list.

 Syntax:  file.readlines(hint)

Where, hint is optional. If the number of bytes returned exceed the hint number, no more lines will be returned. Default value is  -1, which means all lines will be returned.

Example 1:

file1 = open(“mydata.txt”,”r”)

print(“Return all lines in the file, where each line is an item in the list:”)

print(file1.readlines())

file1.close()  # closing the file

Example 2: Do not return the next line if the total number of returned bytes are more than 10:

file1 = open(“mydata.txt”,”r”)

print(“Do not return the next line if the total number of returned bytes are more than 10:”)

print(file1.readlines(10))

file1.close()  # closing the file

Redirecting the output:

We can redirect the output from output screen to a file by specifying the file object in print().

•Redirecting text to a file

print(“text”,file=file_object)

•Redirecting variable value to a file

print(var_name, file=file_object)

#Writing output to a file

f = open(“output.txt”, “w”)

r=5

a=3.14*r*r

print(“Area=”, a, file=f)

print(“New line.”, file=f)

f.close()

#Writing output to a file with more result

ch=’y’

f = open(“output.txt”, “w”)

while ch==’Y’ or ch ==’y’:

print(“Enter radius”)

r=float(input())

a=3.14*r*r

print(“Area=”, a, file=f)

print(“enter your choice”)

ch=input()

f.close()

Writing to a file

There are two methods to write in a file.

1.  Using write()

2.  Using writeline()

Write():

The write() method writes a specified text to the file. Where the specified text will be inserted depends on the file mode and stream position. A file can be written in two mode:

  • “a”:  The text will be inserted at the current file stream position, default at the end of the file.
  • “w”: The file will be emptied before the text will be inserted at the current file stream position, default 0. The contents of existing file will be overwritten.

Note:

  • If file does not exist, the new file will be created using “a” or “w” mode.
  • If you want to create a new file, then use “a” or “w” mode.
  • If you want to append the contents at the end of the existing file, use “a” mode.
  • If you want to overwrite the content of an existing file, use “w” mode.

Note:  “x” mode is similar to “w ” mode.

  • For “x ” mode, if the file exists, raise FileExistsError.
  • For “w” mode, it will simply create a new file or overwrite the existed file.

Syntax:  file.write(byte)

  Where, byte is the text or byte object that will be inserted.

Example 1:  Open the file with “a” mode for appending, then add some text to the file:

#opening file in read mode to see contents of original file

f = open(“mydata.txt”,”r”)

print(“Original File:”)

print(“———————————————–“)

print(f.read())

f.close()

#opening file in append mode to write into file

f1 = open(“mydata.txt”,”a”)

#writing into file

f1.write(“This line inserted today”)

f1.close()

#open and read the file after the appending:

print(“File After appending the content to the file-“)

print(“———————————————–“)

f = open(“mydata.txt”, “r”)

print(f.read())

f.close()

creating a new file named new_file.txt and typing the content using keyboard

f1 = open(r”C:\Users\nielit\Documents\new_file.txt”,”w”)

#writing content from keyboard in file

s=input(“Enter text to be inserted in file:”)

f1.write(s)

f1.close()

#open and read the file after the appending:

print(“File After writing the content to the file-“)

print(“———————————————–“)

f = open(r”C:\Users\nielit\Documents\new_file.txt”, “r”)

print(f.read())

f.close()

Writelines()

The writelines() method writes the items of a list to the file. Where the texts will be inserted depends on the file mode and stream position. It is used to write more than one line to the file. The file can be opened in two modes:

  • “a”:  append mode
  • “w”: write mode

Example 2: Creating a new file named writelines_ex.txt and typing the content using keyboard

f1 = open(“writelines_ex.txt”,”w”)

#writing content from keyboard in file

s=input(“Enter text to be inserted and press enter key to insert the content in the file:”)

f1.writelines(s)

f1.close()

#open and read the file after the writing:

print(“File After writing the content to the file-“)

print(“———————————————–“)

f = open(“writelines_ex.txt”, “r”)

print(f.read())

f.close()

Example 1: Open the file with “a” for appending, then add a list of texts to append to the file:

#Open the file with “a” for appending, then add a list of texts to append to the file:

f = open(“demofile3.txt”, “a”)

#demofile3 file will now be created where this program is stored

f.writelines([“See you soon!”, “Over and out.”])

f.close()

#open and read the file after the appending:

f = open(“demofile3.txt”, “r”)

print(f.read())

The difference between Write() and WriteLine() method is based on new line character.

  • write(arg) expects a string as argument and writes it to the file. If you provide a list of strings, it will raise an exception.
  • writelines(arg) expects an iterable as argument (an iterable object can be a tuple, a list, a string). Each item contained in the iterator is expected to be a string.
  •  

seek () function

The seek() method sets the current file position in a file stream. The seek() method also returns the new position.

Syntax:  file.seek(offset)

Where, offset is required. Offset is the number representing the position to set the current file stream position.

#Using seek method to place cursor at 4th position and then reading:

f = open(“demofile3.txt”, “r”)

print(“Original Content:”)

print(f.read())

print(“—————————————“)

print(“Reading the content from 4th position:”)

f.seek(4)

print(f.readline())

f.close()

Tell()

The tell() method returns the current file position in a file stream.

Syntax:  file.tell()

  It has no parameter.

Example:  Open the file and check the cursor position:

f = open(“demofile3.txt”, “r”)

print(“Current Location of cursor”,f.tell())

print(f.readline())

print(“Updated Location of cursor after reading”,f.tell())

Python os module

The os module provides us the functions that are involved in file processing operations like renaming, deleting, etc.

Let’s look at some of the os module functions.

Renaming Files

The os module provides us the rename() method which is used to rename the specified file to a new name.

The syntax to use the rename() method is…

rename(?current-name?, ?new-name?)

Example:

import os;  

#rename file2.txt to file3.txt  

os.rename(“file2.txt”,”file3.txt”) 

Removing the file

The os module provides us the remove() method which is used to remove the specified file.

The syntax to use the remove() method is–

remove(?file-name?)  

Example:

import os;  

#deleting the file named file3.txt   

os.remove(“file3.txt”)  

Creating the new directory

The mkdir() method is used to create the directories in the current working directory.

The syntax to create the new directory is 

mkdir(?directory name?)  

Example:

import os;  

#creating a new directory with the name new  

os.mkdir(“new”)  

Changing the current working directory

The chdir() method is used to change the current working directory to a specified directory.

The syntax to use the chdir() method is 

chdir(“new-directory”)  

Example:

import os;   

#changing the current working directory to new    

os.chdir(“new”)  

Changing the current working directory

The chdir() method is used to change the current working directory to a specified directory.

The syntax to use the chdir() method is 

chdir(“new-directory”)  

Example:

import os;   

#changing the current working directory to new    

os.chdir(“new”)  

The getcwd() method

This method returns the current working directory.

The syntax to use the getcwd() method is 

os.getcwd() 

Example:

import os;  

#printing the current working directory   

print(os.getcwd()) 

python Anonymous functions (Lambda Function) Recursive Functions with examples in hindi

Anonymous functions (Lambda Function)

•Recursive Functions with examples

Lambda Function

•Anonymous function is a function that is defined without a name.

•Anonymous functions are defined using the lambda keyword.

•Therefore, anonymous functions are also called lambda functions.

•The object returned by lambda is usually assigned to a variable or used as a part of other bigger functions.

•Instead of the conventional def keyword used for creating functions, a lambda function is defined by using the lambda keyword. 

Syntax:

  lambda arguments: expression

•This function can have any number of arguments but only one expression, which is evaluated and returned.

•One is free to use lambda functions wherever function objects are required.

•You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.

•It has various uses in particular fields of programming besides other types of expressions in functions.

Example 1 of Lambda Function

#calculate square of value

  f=lambda x:x*x

  value=f(5)

  print(‘Square of 5= ‘,value)

#calculate sum of two numbers

  f=lambda x,y:x+y

  result=f(1.55,10)

  print(‘sum=’, result)

Example 2 of Lambda Function

lambda function that doubles the input value.

# Program to show the use of lambda functions

double = lambda x: x * 2

print(double(5))

Run Code

Output: 10

In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the expression that gets evaluated and returned.

This function has no name. It returns a function object which is assigned to the identifier double. We can now call it as a normal function. The statement

double = lambda x: x * 2

is nearly the same as:

def double(x):

   return x * 2

Use of Lambda Function in python

We use lambda functions when we require a nameless function for a short period of time.

In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter(), map() etc.

Using Lambdas with filter () Function

  • The filter() function in Python takes in a function and a list as arguments.

The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to True.

Here is an example use of filter() function to filter out only even numbers from a list.

# Program to filter out only the even items from a list

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

print(new_list)

Run Code

Output

[4, 6, 8, 12]

Example use with map()

The map() function in Python takes in a function and a list.

The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.

Here is an example use of map() function to double all the items in a list.

# Program to double each item in a list using map()

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

print(new_list)

Run Code

Output: [2, 10, 8, 12, 16, 22, 6, 24]

Recursive function in Python

What is recursion?

•Recursion is the process of defining something in terms of itself.

•A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.

Python Recursive Function

•In Python, we know that a function can call other functions.

•It is even possible for the function to call itself.

•These types of construct are termed as recursive functions.

The following image shows the working of a recursive function called recurse 

Example of a Recursive function

def factorial(x):

“””This is a recursive function to find the factorial of an integer”””

if x == 1:

  return 1

else:

  return (x * factorial(x-1))

num = 3

print(“The factorial of”, num, “is”, factorial(num))

Advantages & Disadvantages of Recursive function

Advantages of Recursion

•Recursive functions make the code look clean and elegant.

•A complex task can be broken down into simpler sub-problems using recursion.

•Sequence generation is easier with recursion than using some nested iteration

Disadvantages of Recursion

•Sometimes the logic behind recursion is hard to follow through.

•Recursive calls are expensive (inefficient) as they take up a lot of memory and time.

•Recursive functions are hard to debug.

python Concept of Functions with Examples in hindi 

Advantages of Using Function

  • Ease of Use: This allows ease in debugging the code and prone to less error.
  • Reusability: It allows the user to reuse the functionality with a different interface without typing the whole program again.
  • Ease of Maintenance: It helps in less collision at the time of working on modules, helping a team to work with proper collaboration while working on a large application.

What is Function?

A function can be defined as the organized block of reusable code which can be called whenever required. A function is a block of code which only runs when it is called. Basically two  types of function.

1-SDF-System Defined Function

2-UDF-User Defined Function.

  • Python allows us to divide a large program into the basic building blocks known as function.
  • A function can be called multiple times to provide reusability and modularity to the python program.
  • The idea is to put some commonly or repeatedly done task together and make a function.

Function can be categorized in to:

  • Non-Parameterized Function
  • Parameterized Function

Function Definition

In python, we can use def keyword to define the function.

Syntax:

  def function_name(parameter_list): 

  function-definition  

return <expression>  

  • The function block is started with the colon (:)
  • All the same level block statements remain at the same indentation.
  • A function can accept any number of parameters that must be the same in the definition and function calling.

Function Calling

In python, a function must be defined before the function calling otherwise the python interpreter gives an error.

Once the function is defined, we can call it from another function or the python prompt.

To call the function, use the function name followed by the parentheses.

def hello_world():

#function declaration

print(“This is first statement”)

   #function definition

print(“This is second statement”)

hello_world()   

 Non-Parameterized Function

The non-parameterized function does not require any variable name in their declaration and calling.

Example:

def area_circle():

r=float(input(“Enter Radius of Circle:”))

a=3.14*r*r

print(“Area of circle:”,a)

area_circle()  #function calling

Parameterized Function

The parameterized function require variable name in their declaration and calling.

Function parameters

The information into the functions can be passed as the parameters. The parameters are specified in the parentheses.

A function may have any number of parameters.

Multiple parameters are separated with a comma

Example 1:

def area_circle(r):

a=3.14*r*r

print(“Area of circle:”,a)

radius=float(input(“Enter Radius:”))

area_circle(radius)

  • Here, the function named area_circle() is declared with empty().
  • This means, the function called with empty() i.e. calling does not requires any parameter.

Example 2: Python function to calculate area of rectangle using parameterized function

def area_rect(l,b):  #parameterized function

  area_lb=l*b

  print(“Area of Rectangle:”,area_lb)

len=float(input(“Enter Length of rectangle:”))

brth=float(input(“Enter Breadth of rectangle:”))

area_rect(len, brth)

Output:

Enter Length of rectangle:30

Enter Breadth of rectangle:20

Area of Rectangle: 600.0

Return Statement

A function may return a value using return keyword. When a function produces a result, there are two possibilities:

a) The value of output is preserved within the function. As in above example.

b) Transfer the value of output to calling function.

  i)  Return statement is used in this scenario.

  ii)  A return statement is used to end the execution of the   function call and “returns” the result (value of the expression   following the return keyword) to the caller.

c. The statements after the return statements are not executed.

d. If the return statement is without any expression, then the special value None is returned.

Example 1:

def si_int(p,r,t): 

  si=(p*r*t)/100

  return si  #returning the value of si to the calling function    

s=si_int(20000,8.5,3)

print(“Simple Interest=”,s)

  • In above example, the function si_int() will calculate the simple interest in variable named si and returns the value of si to the function calling.
  • At function calling, the returned value is stored in variable named s.
  • Now, we can use the value of s as per requirement. In above example, the value of s gets printed using print statement.

Example 2:

def area_rect(l,b): #parameterized function

  area_lb=l*b

  return area_lb  #returning the value of area_lb to calling function

len=float(input(“Enter Length of rectangle:”))

brth=float(input(“Enter Breadth of rectangle:”))

# Ar will store the value of area_lb, which is returned by the function

Ar=area_rect(len, brth)

Output:

Enter Length of rectangle:20

Enter Breadth of rectangle:10

Area of Rectangle: 200.0

Types of Parameter

There may be several types of arguments which can be passed at the time of function calling.

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

Required Arguments

The required arguments are required to be passed at the time of function calling with the exact match of their positions in the function call and function definition. If either of the arguments is not provided in the function call, or the position of the arguments is changed, then the python interpreter will show the error.

Example 1:

def calculate(a,b):

     return a+b 

sum1=calculate(10) # this causes an error as we are missing a required arguments b.

print(“Sum=“,sum)

Output: calculate() missing 1 required positional argument: ‘b’

Example 2:

def calculate(a,b):

     return a+b 

sum1=calculate(10,10)  

print(“Sum=“,sum)

Output: Sum=20 

Keyword Arguments

Python allows us to call the function with the keyword arguments. This kind of function call will enable us to pass the arguments in the random order.

Example1:

#The function simple_interest(p, t, r) is called with the keyword arguments the order of arguments doesn’t matter in this case 

def simple_interest(p,t,r): 

return (p*t*r)/100 

print(“Simple Interest: “,simple_interest(t=10,r=10,p=1900))

Output: Simple Interest:  1900.0

Note: In this case the name of argument is same in calling and definition.

Example 2:

#The function simple_interest(p, t, r) is called with the keyword arguments the order of arguments doesn’t matter in this case 

def simple_interest(p,t,r): 

return (p*t*r)/100

x=float(input(“Enter Amount”))

y=float(input(“Enter Time”))

z=float(input(“Enter Rate”))

print(“Simple Interest: “,simple_interest(t=y,r=z,p=x))

Output:

Enter Amount12000

Enter Time5

Enter Rate5

Simple Interest:  3000.0

  • If we provide the different name of arguments at the time of function call, an error will be thrown.

  simple_interest(20000,rate=7.5, time=6)  #error

  • The python allows us to provide the mix of the required arguments and keyword arguments at the time of function call.   simple_interest(20000,t=5,r=6.5)
  • The required argument must not be given after the keyword argument.

  simple_interest(20000,r=7.5,6)   #error

Default Arguments

Python allows us to initialize the arguments at the function definition. If the value of any of the argument is not provided at the time of function call, then the default value for the argument will be used.

Example 1:

def printme(name,age=22): 

  print(“Name:”,name,”\nAge:”,age) 

printme(“Ravi”)   # name=Ravi age=22 (default value)

printme(“Sachin”, 33)  #name =Sachin age=33

Output:

Name: Ravi

Age: 22

Name: Sachin

Age: 33

Variable Length Arguments

Variable length argument is a feature that allows a function to receive any number of arguments. However, at the function definition, we have to define the variable with * (star) as *<variable – name >.

Example 1:

def printme(*names): 

print(“type of passed argument is “,type(names)) 

print(“printing the passed arguments…”) 

for name in names: 

     print(name) 

#calling printme function

printme(“Rahul”,”Prashant”,”sunita”,”Sandeep”)

Output:

type of passed argument is  <class ‘tuple’>

printing the passed arguments…

Rahul

Prashant

sunita

Sandeep

Example 2:

def adder(*num):

sum = 0

for n in num:

     sum = sum + n

print(“Sum:”,sum)

adder(3,5)                 #calling adder with 2 argument

adder(4,5,6,7)              #calling adder with 4 argument

adder(1,2,3,5,6)       #calling adder with 5 argument

Output:

Sum: 8

Sum: 22

Sum: 17

Local Variable

  • A local variable is a type of variable declared within programming block or function.
  • It can only be used only inside that function or code block in which they were declared.
  • The local variable exists until the block of the function is in under execution. After that, it will be destroyed automatically.

Example 1:

def func():

a=10

print(“Value of a in function:”,a)

func()

print(“Value of ‘a’ outside function:”,a)

Output: name ‘a’ is not defined

In  example1, it is clearly shown that the value of variable ‘a’ is only accessible inside the function func(). The value variable ‘a’ cannot be accessible outside the function because variable ‘a’ is a local variable of the function func(). It can only be accessible inside the function func().

Global Variable

  • Global variables are defined outside of a subroutine or function.
  • The global variable will hold its value throughout the lifetime of a program.
  • They can be accessed within any function defined for the program.

Example 1:

a=10

def func():

print(“Value of a in function:”,a)

func()

print(“Value of ‘a’ outside function:”,a)

Output:

Value of a in function: 10

Value of ‘a’ outside function: 10

Here, variable ‘a’ is defined outside the function func(). The variable ‘a’ will now become a global variable. It can be accessed inside any function as well as outside the function.

Global Keyword

So far, we haven’t had any kind of a problem with global scope. So let’s take an .

Example 1:

i=10  #global variable

def counter():

i=20 #local variable of function counter

print(“Value of i in function:”,i)           

counter()

print(“Value of i Outside Function:”,i)

Output:

Value of i in function: 20

Value of i Outside Function: 10

Now, when we make a reference to ‘i’ outside this function, we get 10 instead of 20.

Global keyword is a keyword that allows a user to modify a variable outside of the current scope.

  • It is used to create global variables from a non-global scope i.e. inside a function.
  • Global keyword is used inside a function only when we want to do assignments or when we want to change a variable.
  • Global is not needed for printing and accessing.

Rules of Global Keywords

If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

  • Variables that are only referenced inside a function are implicitly global.
  • We Use global keyword to use a global variable inside a function.
  • There is no need to use global keyword outside a function.

Use of Global Keywords

To access a global variable inside a function there is no need to use global keyword.

Example 1:

# global variable

a = 15

b = 10

 # function to perform addition

def add():

c = a + b

print(c)  

# calling a function

add()

Output: 25

If we need to assign a new value to a global variable then we can do that by declaring the variable as global.

Code: Without global keyword

a = 15

  # function to change a global value

def change():

   # increment value of a by 5

a = a + 5

print(a)

 change()

If we need to assign a new value to a global variable then we can do that by declaring the variable as global.

Code : Without global keyword

a = 15

  # function to change a global value

def change():

  a = a + 5  # increment value of a by 5

  print(a)

change()

Output: UnboundLocalError: local variable ‘a’ referenced before assignment

This output is an error because we are trying to assign a value to a variable in an outer scope. This can be done with the use of global variable.

Code : With global keyword

# Python program to modify a global

# value inside a function

x = 15

def change():    

global x  # using a global keyword      

x = x + 5 # increment value of a by 5 

print(“Value of x inside a function :”, x)

change()

print(“Value of x outside a function :”, x)

Output:

Value of x inside a function : 20

Value of x outside a function : 20

Python docstrings

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.

General Rules:

  • The doc string 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 string, the second line should be blank, visually separating the summary from the rest of the description.
  • The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.

Declaring Docstrings: The docstrings are declared using “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.

Accessing Docstrings: The docstrings can be accessed

  • using the __doc__ method of the object or
  • using the help function.

Example:

def my_function():

“””Demonstrate docstrings and does nothing really.”””

return None

print(“Printing DocString Using __doc__:”)

print(my_function.__doc__ )

print(“Printing DocString Using help function:”)

help(my_function)

Output:

Printing DocString Using __doc__:

Demonstrate docstrings and does nothing really.

Printing DocString Using help function:

Help on function my_function in module __main__:

my_function()

     Demonstrate docstrings and does nothing really.

python Concept of String String manipulating & Indexing Creating String & Deleting String Various String Functions by unitdiploma

p

  • Concept of String.
  • String manipulating & Indexing
  • Creating String &  Deleting String
  • Various String Functions

String

Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The computer does not understand the characters; internally, it stores manipulated character as the combination of the 0’s and 1’s.

Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.

Example:

str=”Nielit”

print(type(str))

Output:

<class ‘str’>

In Python, strings are treated as the sequence of characters, which means that Python doesn’t support the character data-type; instead, a single character written as ‘N’ is treated as the string of length 1.

Creating String in Python

We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides triple-quotes to represent the string, but it is generally used for multiline string or docstrings.

Example:

#Use single quotes 

s1 = ‘Python Programming’ 

print(s1)

print(type(s1))

print(“***********************”)

#Use double quotes

s2 = “Python Programming” 

print(s2)

print(type(s2))

print(“***********************”)

#Use triple quotes 

s3 = ””’Triple quotes are generally used for 

represent the multiline or

docstring”’  

print(s3)

print(type(s3))

Output

Python Programming

<class ‘str’>

***********************

Python Programming

<class ‘str’>

***********************

”Triple quotes are generally used for 

represent the multiline or

docstring

<class ‘str’>

Strings indexing and splitting

Like other languages, the indexing of the Python strings starts from 0. For example, the string “HELLO” is indexed as given in the below figure.

Example

str = “PYTHON” 

print(str[0]) 

print(str[1]) 

print(str[2]) 

print(str[3]) 

print(str[4])

print(str[5])

# It returns the IndexError because 6th index doesn’t exist

print(str[6])  

Output

P

Y

T

H

O

N

IndexError: string index out of range

Slice operator [] in String

As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can use the: (colon) operator in Python to access the substring from the given string.

Example

Example

str =’HELLOWORLD’ 

print(str[-1]) 

print(str[-3]) 

print(str[-2:]) 

print(str[-4:-1]) 

print(str[-7:-2]) 

# Reversing the given string 

print(str[::-1])

# Search Character out of index

print(str[-12])

Output

D

R

LD

ORL

LOWOR

DLROWOLLEH

print(str[-12])

IndexError: string index out of range

Reassigning Strings

Updating the content of the strings is as easy as assigning it to a new string. The string object doesn’t support item assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are immutable in Python.

Example

str = “PYTHON”   

str[0] = “p”   

print(str)

Output

str[0] = “p“

TypeError: ‘str’ object does not support item assignment

Example

str = “PYTHON”

print(str)

str= “python”   

print(str)

output:

PYTHON

python

Deleting the String

As we know that strings are immutable. We cannot delete or remove the characters from the string.  But we can delete the entire string using the del keyword.

str=”PYTHON”

print(str)

del str[0]

#print String after delete

print(“*******”)

print(str)

Output:

del str[0]

TypeError: ‘str’ object doesn’t support item deletion

Example

str=”PYTHON”

print(str)

del str

#print String after delete

print(“*******”)

print(str)

Output:

PYTHON

*******

<class ‘str’>

String Operators

OperatorDescription
+It is known as concatenation operator used to join the strings given either side of the operator.
*It is known as repetition operator. It concatenates the multiple copies of the same string.
[]It is known as slice operator. It is used to access the sub-strings of a particular string.
[:]It is known as range slice operator. It is used to access the characters from the specified range.
inIt is known as membership operator. It returns if a particular sub-string is present in the specified string.
not inIt is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string.
%It is used to perform string formatting. It makes use of the format specifies used in C programming like %d or %f to map their values in python. We will discuss how formatting is done in python.

Example on String Operator:

str1 = “Python”    

str2 = “Program”   

print(str1*3) # prints PythonPythonPython 

print(str1+str2)# prints PythonProgram    

print(str1[4]) # prints o               

print(str2[2:4]); # prints og                   

print(‘h’ in str1) # prints True as “h” is  present in str1

print(‘m’ in str1) # prints False as “m” is not present in str1

print(‘am’ not in str2) # prints False as “am” is present in str2.

print(‘n’ not in str2) # prints True as “n” is not present in str2.

print(“The string str : %s”%(str1)) # prints The string str : Python

Output

PythonPythonPython

PythonProgram

o

og

True

False

False

True

The string str : Python

String Functions

1.count()

The count() method returns the number of times a specified value appears in the string.

Syntax:  string.count(value, start, end)

ParameterDescription
valueRequired. A String. The string to value to search for
startOptional. An Integer. The position to start the search. Default is 0
endOptional. An Integer. The position to end the search. Default is the end of the string

Example: Return the number of times the value “apple” appears in the string:

txt = “I love apples, apple are my favorite fruit”

x = txt.count(“apple”)

print(x)

Output:  2

Example: Search from index 10 to 24:

txt = “I love apples, apple are my favorite fruit”

x = txt.count(“apple”, 10, 24)

print(x)

Output:  1

2.find()

The find() method finds the first occurrence of the specified value.

The find() method returns -1 if the value is not found.

Syntax: string.find(value, start, end)

ParameterDescription
ValueRequired. The value to search for
StartOptional. Where to start the search.Default is 0
EndOptional. Where to end the search. Default is to the end of the string

Example: To find the first occurrence of the letter “e” in txt:

txt = “Hello, welcome to my world.”

x = txt.find(“e”)

print(x)

Output:  1

Example 2: Where in the text is the first occurrence of the letter “e” when you only search between position 5 and 10?:

txt = “Hello,welcome to my world.”

x = txt.find(“e”, 5, 10)

print(x)

Output:  8

3-rfind(): The rfind() searches the string for a specified value and returns the last position of where it was found.

Example: 

  • The rfind() method finds the last occurrence of the specified value.
  • The rfind() method returns -1 if the value is not found.

Syntax:  string.rfind(value, start, end)

Example: Where in the text is the last occurrence of the string “nielit”?:

txt = “nielit has started o level course nielit”

x = txt.rfind(“nielit”)

print(x)

Output: 43

Example: Where in the text is the last occurrence of the letter “e” when you only search between position 5 and 10?:

txt = “Hello, welcome to NIELIT”

x = txt.rfind(“e”, 5, 10)

print(x)

Output: 8

Example: If the value is not found, the rfind() method returns -1

txt = “Hello, welcome to NIELIT”

x = txt.rfind(‘nielit’)

print(x)

Output:  -1

String Functions Contd..

4-capitalize(): 

This method converts the first character to upper case. The capitalize() method returns a string where the first character is upper case.

Example: Upper case the first letter in this sentence:

txt = “hello, welcome to NIELIT”

x = txt.capitalize()

print (x)

Output: Hello, welcome to nielit.

5-title() 

The title() method returns a string where the first character in every word is upper case. Like a header, or a title.

Example:

txt = “python programming using string”

x = txt.title()

print(x)

Output: Python Programming Using String

If the word contains a number or a symbol, the first letter after that will be converted to upper case.

Example: 

txt = ” 3rd generation python”

x = txt.title()

print(x)

Output: 3Rd Generation Python

Example: Note that the first letter after a non-alphabet letter is converted into a upper case letter:

txt = “hello b2b2b2 and 3g3g3g”

x = txt.title()

print(x)

Output: Hello B2B2B2 And 3G3G3G

6-lower()

The lower() method returns a string where all characters are lower case. Symbols and Numbers are ignored.

Example: txt = “Welcome To NIELIT”

x = txt.lower()

print(x)

Output: welcome to nielit

7-upper()

The upper() method returns a string where all characters are in upper case. Symbols and Numbers are ignored.

Example: txt = “Welcome To NIELIT”

x = txt.upper()

print(x)

Output: WELCOME TO NIELIT

8-islower()

The islower() method returns True if all the characters are in lower case, otherwise False. Numbers, symbols and spaces are not checked, only alphabet characters.

Example: txt = “hello world!”

x = txt.islower()

print(x)

Output: True

9-isupper()

The isupper() method returns True if all the characters are in upper case, otherwise False. Numbers, symbols and spaces are not checked, only alphabet characters.

Example: txt = “PYTHON PROGRAM”

x = txt.isupper()

print(x)

Output: True

10-istitle()

The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False. Symbols and numbers are ignored.

Example:

a = “HELLO, AND WELCOME TO MY WORLD”

b = “Hello”

c = “22 Names”

d = “This Is %’!?”

print(a.istitle())

print(b.istitle())

print(c.istitle())

print(d.istitle())

Output:

False

True

True

True

11-replace()

The replace() method replaces a specified phrase with another specified phrase.

Syntax: string.replace(oldvalue, newvalue, count)

Parameter Values

ParameterDescription
oldvalueRequired. The string to search for
newvalueRequired. The string to replace the old value with
countOptional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences

Example: Replace all occurrence of the word “one”:

  txt = “one one was a race horse, two two was one too.”

  x = txt.replace(“one”, “three”)

  print(x)

Output: three three was a race horse, two two was three too.

Example: Replace the two first occurrence of the word “one”:

  txt = “one one was a race horse, two two was one too.”

  x = txt.replace(“one”, “three”, 2)

  print(x)

Output: three three was a race horse, two two was one too.

12-strip()

The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove)

Syntax  string.strip(characters)

Parameter Values

ParameterDescription
charactersOptional. A set of characters to remove as leading/trailing characters

Example: Remove spaces at the beginning and at the end of the string:

  txt = ” banana “

  x = txt.strip()

  print(x)

Output: banana

Example: Remove the leading and trailing characters other than space

txt = “,,,,,rrttgg…..apple….rrr”

x = txt.strip(“,.grt”)

print(x)

Output:  apple

String Functions Contd..

lstrip()

The lstrip() method removes any leading characters (space is the default leading character to remove)

Syntax  : string.lstrip(characters)

Where, character is Optional. A set of characters to remove as leading characters

Example: txt = “,,,,,ssaaww…..banana.. “

x = txt.lstrip(“,.asw”)

print(x)

Output:  banana..

Note: Only leading character on left side will be removed.

rstrip()

The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.

Syntax:  string.rstrip(characters)

Where, characters is optional. A set of characters to remove as trailing characters

Example: txt = “banana,,,,,ssaaww…..”

x = txt.rstrip(“,.asw”)

print(x)

Output:  banana..   

Note: Only leading character on right side will be removed.

split():

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.

Syntax  string.split(separator, maxsplit)

ParameterDescription
separatorOptional. Specifies the separator to use when splitting the string. By default any whitespace is a separator
maxsplitOptional. Specifies how many splits to do. Default value is -1, which is “all occurrences”

Example: txt = “hello, my name is Peter, I am 26 years old”

  x = txt.split(“, “)

  print(x)

Output: [‘hello’, ‘my name is Peter’, ‘I am 26 years old’]

partition()

The partition() method searches for a specified string, and splits the string into a tuple containing three elements.

  • The first element contains the part before the specified string.
  • The second element contains the specified string.
  • The third element contains the part after the string.

Syntax  string.partition(value)

Where, value is required. The value is the string to search for

Example txt = “I could eat bananas all day”

x = txt.partition(“bananas”)

print(x)

Output: (‘I could eat ‘, ‘bananas’, ‘ all day’)

Search for the word “bananas”, and return a tuple with three elements:

1 – everything before the “banana”

2 – the “banana”

3 – everything after the “banana”

join()

The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.

Example: join all items in a dictionary into a string, using a the word “and” as separator:

List1 =(“apple”,”Bannana”)

mySeparator = ” and “

x = mySeparator.join(List1)

print(x)

Output:  apple and Bannana

isspace()

The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.

Example:  txt = ”   s   “

x = txt.isspace()

print(x)

Output:  False