0% found this document useful (0 votes)
4 views84 pages

Python Notes

The document provides an overview of classes and objects in Python, explaining how classes serve as templates for creating objects with shared characteristics and behaviors. It covers the syntax for creating classes, the role of the __init__ method as a constructor, and the distinction between class variables and instance variables. Additionally, it discusses key object-oriented programming concepts such as inheritance, polymorphism, encapsulation, and the differences between class, instance, and static methods.

Uploaded by

yogitachavan0117
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views84 pages

Python Notes

The document provides an overview of classes and objects in Python, explaining how classes serve as templates for creating objects with shared characteristics and behaviors. It covers the syntax for creating classes, the role of the __init__ method as a constructor, and the distinction between class variables and instance variables. Additionally, it discusses key object-oriented programming concepts such as inheritance, polymorphism, encapsulation, and the differences between class, instance, and static methods.

Uploaded by

yogitachavan0117
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 84

Classes and Objects in Python

Python is an object-oriented programming language that offers classes,


which are a potent tool for writing reusable code. To describe objects with
shared characteristics and behaviours, classes are utilised. We shall
examine Python's ideas of classes and objects in this article.

Classes in Python :
In Python, a class is a user-defined data type that contains both the data
itself and the methods that may be used to manipulate it. In a sense,
classes serve as a template to create objects. They provide the
characteristics and operations that the objects will employ.

Suppose a class is a prototype of a building. A building contains all the


details about the floor, rooms, doors, windows, etc. we can make as many
buildings as we want, based on these details. Hence, the building can be
seen as a class, and we can create as many objects of this class.

Creating Classes in Python


In Python, a class can be created by using the keyword class, followed by
the class name. The syntax to create a class is given below.

Syntax

1. class ClassName:
2. #statement_suite

In Python, we must notice that each class is associated with a documentation string
which can be accessed by using <class-name>.__doc__. A class contains a statement
suite including fields, constructor, function, etc. definition.

Example:

Code:

1. class Person:
2. def __init__(self, name, age):
3. # This is the constructor method that is called when creating a new Person o
bject
4. # It takes two parameters, name and age, and initializes them as attributes
of the object
5. self.name = name
6. self.age = age
7. def greet(self):
8. # This is a method of the Person class that prints a greeting message
9. print("Hello, my name is " + self.name)

Name and age are the two properties of the Person class. Additionally, it
has a function called greet that prints a greeting.
Objects in Python:
An object is a particular instance of a class with unique characteristics and
functions. After a class has been established, you may make objects
based on it. By using the class constructor, you may create an object of a
class in Python. The object's attributes are initialised in the constructor,
which is a special procedure with the name __init__.

Syntax:

1. # Declare an object of a class


2. object_name = Class_Name(arguments)

Example:

Code:

1. class Person:
2. def __init__(self, name, age):
3. self.name = name
4. self.age = age
5. def greet(self):
6. print("Hello, my name is " + self.name)
7.
8. # Create a new instance of the Person class and assign it to the variable person1
9. person1 = Person("Ayan", 25)
10. person1.greet()

Output:

"Hello, my name is Ayan"

The self-parameter

The self-parameter refers to the current instance of the class and


accesses the class variables. We can use anything instead of self, but it
must be the first parameter of any function which belongs to the class.

_ _init_ _ method

In order to make an instance of a class in Python, a specific function called


__init__ is called. Although it is used to set the object's attributes, it is
often referred to as a constructor.

The self-argument is the only one required by the __init__ method. This
argument refers to the newly generated instance of the class. To initialise
the values of each attribute associated with the objects, you can declare
extra arguments in the __init__ method.

Class and Instance Variables


All instances of a class exchange class variables. They function
independently of any class methods and may be accessed through the
use of the class name. Here's an illustration:

Code:

1. class Person:
2. count = 0 # This is a class variable
3.
4. def __init__(self, name, age):
5. self.name = name # This is an instance variable
6. self.age = age
7. Person.count += 1 # Accessing the class variable using the name of the cla
ss
8. person1 = Person("Ayan", 25)
9. person2 = Person("Bobby", 30)
10. print(Person.count)

Output:

Whereas, instance variables are specific to each instance of a class. They


are specified using the self-argument in the __init__ method. Here's an
illustration:

Code:

1. class Person:
2. def __init__(self, name, age):
3. self.name = name # This is an instance variable
4. self.age = age
5. person1 = Person("Ayan", 25)
6. person2 = Person("Bobby", 30)
7. print(person1.name)
8. print(person2.age)

Output:

Ayan
30

Class variables are created separately from any class methods and are
shared by all class copies. Every instance of a class has its own instance
variables, which are specified in the __init__ method utilising the self-
argument.

Conclusion:
In conclusion, Python's classes and objects notions are strong ideas that
let you write reusable programmes. You may combine information and
capabilities into a single entity that is able to be used to build many
objects by establishing a class. Using the dot notation, you may access an
object's methods and properties after it has been created. You can
develop more logical, effective, and manageable code by comprehending
Python's classes and objects.

Python 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.

o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o 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.

Syntax

1. class ClassName:
2. <statement-1>
3. .
4. .
5. <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:

1. class car:
2. def __init__(self,modelname, year):
3. self.modelname = modelname
4. self.year = year
5. def display(self):
6. print(self.modelname,self.year)
7.
8. c1 = car("Toyota", 2016)
9. c1.display()

Output:

Toyota 2016

In the above example, we have created the class named car, and it has
two attributes modelname and year. We have created a c1 object to
access the class attribute. The c1 object will allocate memory for these
values. We will learn more about class and object in the next tutorial.

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

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

Index Object-oriented Programming Procedural Programming

1. Object-oriented programming is the problem-solving Procedural programming uses a list of


approach and used where computation is done by instructions to do computation step by
using objects.

2. It makes the development and maintenance easier. In procedural programming, It is not ea


the codes when the project becomes le

3. It simulates the real world entity. So real-world It doesn't simulate the real world. It wo
problems can be easily solved through oops. step by step instructions divided into
parts called functions.

4. It provides data hiding. So it is more secure than Procedural language doesn't provide a
procedural proper way for data binding, so it is le
languages. You cannot access private data from
anywhere.

5. Example of object-oriented programming Example of procedural languages are: C, F


languages is C++, Java, .Net, Python, C#, etc.

The difference between object-oriented and procedure-oriented


programming is given below:

Difference between Class Method, Static Method, and Instance Method

In this tutorial, we will learn about the class method, static method, and
instance method. These methods are the core concepts of object-oriented
programming in Python. Every Python enthusiast should be familiar with
these methods and how to use them as per the requirements. Let's briefly
introduce instance, class, and static methods.

What are Instance Methods?

As its name suggests, the instance methods are bound to the class
instance and perform a set of actions on the data/value given by the
object (instance) variables. If we use the instance variable inside the
methods, these methods are called instance methods. It can modify the
object state. The self keyword is the first parameter to work with the
instance method, and the self refers to the current object.

Example -

1. class Employee:
2. # constructor
3. def __init__(self, name, department):
4. # Instance variable
5. self.name = name
6. self.department = department
7.
8. # instance method to access instance variable
9. def show(self):
10. print('Name:', self.name, 'Department:', self.department)
11.
12. obj = Employee('Craig', 'IT')
13. obj.show()

Output:

Name: Craig Department: IT

Explanation -

We have defined the constructor that creates the instance variable using
the Python object in the above code. In the show() function, we accessed
both variables using the self keyword. We can access and modify the
instance variable using the below code.

Example - 2

1. class Employee:
2. # constructor
3. def __init__(self, name, department):
4. # Instance variable
5. self.name = name
6. self.department = department
7.
8. # instance method to access instance variable
9. def show(self):
10. print('Name:', self.name, 'Department:', self.department)
11.
12. obj = Employee('Craig', 'IT')
13. obj.show()
14. obj.name = 'Mathew'
15. obj.department = 'HR'
16. obj.show()

Output:

Name: Craig Department: IT


Name: Mathew Department: HR

Explanation -

We can see that we accessed the instance variable and changed its value.
In the show() function, the instance method printed the updated values.

Class Methods

The class methods are bound to the class, not to the instance. It can
modify the class state means it can change class configuration globally. It
can access only the class variable. The class methods are used to create
the factory methods. The syntax of class methods is different; instead of
taking self parameter, they accept cls as a parameter that points to the
class. It can't modify the instance state. However, the changes made by
the class method reflect all instances of the class.
The @classemethod decorator or classmethod() defines the class
methods. Let's understand the following example.

Example -

1. class Employee:
2. # class variable
3. salary = 25000
4. def __init__(self, name, department):
5. # Instance variable
6. self.name = name
7. self.department = department
8.
9. # instance method to access instance variable
10. def show(self):
11. print('Name:', self.name, 'Department:', self.department, 'Salary:', Employe
e.salary)
12.
13. def change_salary(cls, salary):
14. cls.salary = salary
15.
16. obj = Employee('Craig', 'IT')
17. obj.show()
18. Employee.change_salary(45000)
19. obj.show()

Output:

Name: Craig Department: IT Salary: 25000


Name: Craig Department: IT Salary: 45000
Explanation -

In the above code, we have defined the class variable name salary and
the class method change_salary(). The change_salary() function
accessed the class variable salary, and it used to modify the salary for all
the employees. We have done the same in the object creation part.

Static Method

The Static methods neither use self nor cls parameter; general utility
methods perform the task in isolation. Static methods in Python are
similar to those found in Java and C++, and they can't modify the
behavior of the class or instance. The @staticmethod decorator
or staticmethod() method defines the static methods. Let's see the
below example. The static methods can be accessed using the class name
and instance of the class.

Example -

1. class Employee:
2. @staticmethod
3. def sample_method(x):
4. print('Inside static method', x*x)
5.
6. # call static method
7. Employee.sample_method(10)
8.
9. # can be called using object
10. emp = Employee()
11. emp.sample_method(10)

Output:

Inside static method 100


Inside static method 100

Explanation -

We have created a static method that takes x as an argument in the


above method. We calculated multiplication with itself, and we accessed
the static method using the class name and the instance.

Let's understand the difference between class, instance, and static


methods.

Class Methods vs. Static Methods vs. Instance Methods

We will describe some essential differences between these methods using


some parameters. These differences will help you get more understanding
of oops concepts.
Method Call
o Instance methods can be accessed using the object/instance of the class.
o The class methods and static methods can be accessed using the class
name and the object of the class.

Modification
o Instance methods can modify the behavior of the instance variables.
o Class methods can modify the behavior of the class, that reflects to the
entire class so with the all instances of the class.
o Static methods perform their tasks in isolation. They didn't have any
interaction with the class or instance methods.

Attributes Access
o The instance method can access the both class variable and instance
variables.
o The class method can access the class variables.
o The static method cannot access the class variables and static variables.
Therefore, it cannot change the behavior of the class or instance state.

Class Bound and Instance Bound


o The instance methods are bound with the object of the class so that we
can access them using object.
o It is good practice to access the class methods and static methods using
the class name because they are bound to the class.

Important Notes

o To get an good command on the oops concept of Python, we need to


understand the class, instance, and static method.
o Instance methods use self parameter to access the class instance.
o Class methods don't require a class instance. They use the cls parameter
instead of self parameter.
o The static method neither uses a self nor the self. They act as the regular
functions but can access through the class name.
o The static and class methods communicate and (to a certain degree)
enforce developer intent about class design. It can have maintenance
benefits.

File Organizer: Write a Python program that organizes the file in a directory based on the extension

The general process to construct a Python program that organizes files in


a directory is as follows:

1. Identify the Directory - You must find the source directory to be


organized. It is important to take note of the files contained in that
directory. The files could be of different types or a particular type.
Following are the snapshots of the source directory before organizing the
directory.

Define the path of the source directory containing the file to be organized:

For example:

1. Source_dir = "C:\Users\DELL\Desktop\Temp"

In our program, we have taken input from the user for the source
directory.

2. Define the Category - It is important to define the categories you


want to organize based on the types of files stored in the directory. For
example, if you wish to organize the directory containing images. You
might want to categorize them based on the year, month, date, image
type, location where they were taken, etc.

This is how you can define the categories of the files:

1. # Create a dictionary to map file extensions to their respective folders


2. extension_map = {
3. '.jpg': 'Images',
4. '.png': 'Images',
5. '.gif': 'Images',
6. '.jpeg': 'Images',
7. '.pdf': 'PDF Files',
8. '.txt': 'Text Files',
9. '.docx': 'Word Document',
10. '.xlsx': 'Excel Files',
11. '.pptx': 'PowerPoint Persentations',
12. '.ppt': 'PowerPoint Persentations',
13. '.mp3': 'Audio',
14. '.wav': 'Audio',
15. '.mp4': 'Video',
16. '.avi': 'Video',
17. '.exe': 'Executable Files',
18. '.py': 'Python Files',
19. '.cpp': 'C++ Files',
20. '.c': 'C Files',
21. '.java': 'Java Files',
22. '.html': 'HTML Files',
23. '.css': 'CSS Files',
24. '.js': 'Javascript Files',
25. '.zip': 'Zip_Files'
26. }
3. Define the path of the Destination - In some cases, you might want
to move the files to different locations. For that, you must define the
destination path.

For Example:

1. Destination_dir = "C:\Users\DELL\Desktop\Temp"

The paths of the source and destination directories are the same. So, the
program will organize the files in the source directory.

In our program, we have also taken input from the user for the destination
directory. Also

4. Write code to sort files - Write a code to sort the files based on the
chosen category in the directory. You must read the files in the directory,
extract the relevant metadata (such as the creation date or file type), and
then move the files to the correct category directory using Python's built-
in functions.

Following is the code that sorts the files based on the type of the file and
moves all the file to their respective directory.

1. # Loop through each file in the source directory and


2. # Move it to the appropriate folder in the destination directory
3. for filename in os.listdir(source_dir):
4.
5. # Get the file extension in lowercase
6. file_ext = os.path.splitext(filename)[-1].lower()
7.
8. # Check if the file extension is in the extension_map dictionary
9. if file_ext in extension_map:
10.
11. # Create the full path to the source file
12. src_path = os.path.join(source_dir, filename)
13.
14. # Create the full path to the destination file
15. dest_path = os.path.join(dest_dir, extension_map[file_ext], filename)
16.
17. # Move the file to the appropriate folder in the destination directory
18. shutil.move(src_path, dest_path)

5. Test Your Code - Once the program has been developed, test it on a small subset of
files to ensure it functions as intended. If there are any problems, you can fix the code
and test it once more to ensure it is functioning properly. Otherwise, you might lose your
data.

6. Run the code on the source directory - Now, you are ready to arrange all of the
files in the directory. For that, you can execute the code on the source directory. Before
running the code, it's crucial to make sure that you have a backup of the files in case
something goes wrong.

Code:
1. # Python program to arrange the files in a directory based on the file's extension
2. # Import the necessary modules
3. import os
4. import shutil
5.
6. # Define the source directory containing the files to be organized
7. # Taking raw input which won't interpret escape characters
8. source_dir = input(r"Enter the source directory path : ").replace('\\', '/')
9.
10. # Define the destination directory where the organized files will be moved to
11. # Taking raw input which won't interpret escape characters
12. dest_dir = input(r"Enter the destination directory path : ").replace('\\', '/')
13.
14. # Create a dictionary to map file extensions to their respective folders
15. extension_map = {
16. '.jpg': 'Images',
17. '.png': 'Images',
18. '.gif': 'Images',
19. '.jpeg': 'Images',
20. '.pdf': 'PDF Files',
21. '.txt': 'Text Files',
22. '.docx': 'Word Document',
23. '.rtf': 'Word Document',
24. '.xlsx': 'Excel Files',
25. '.pptx': 'PowerPoint Persentations',
26. '.ppt': 'PowerPoint Persentations',
27. '.mp3': 'Audio',
28. '.wav': 'Audio',
29. '.mp4': 'Video',
30. '.avi': 'Video',
31. '.exe': 'Executable Files',
32. '.py': 'Python Files',
33. '.cpp': 'C++ Files',
34. '.c': 'C Files',
35. '.java': 'Java Files',
36. '.html': 'HTML Files',
37. '.css': 'CSS Files',
38. '.js': 'Javascript Files',
39. '.zip': 'Zip_Files'
40. }
41.
42. # Create the destination folders if they don't already exist
43. for folder_name in set(extension_map.values()):
44. os.makedirs(os.path.join(dest_dir, folder_name), exist_ok=True)
45.
46. # Loop through each file in the source directory and
47. # Move it to the appropriate folder in the destination directory
48. for filename in os.listdir(source_dir):
49.
50. # Get the file extension in lowercase
51. file_ext = os.path.splitext(filename)[-1].lower()
52.
53. # Check if the file extension is in the extension_map dictionary
54. if file_ext in extension_map:
55.
56. # Create the full path to the source file
57. src_path = os.path.join(source_dir, filename)
58.
59. # Create the full path to the destination file
60. dest_path = os.path.join(dest_dir, extension_map[file_ext], filename)
61.
62. # Move the file to the appropriate folder in the destination directory
63. shutil.move(src_path, dest_path)

Output:

Enter the source directory path : C:\Users\DELL\Desktop\Temp


Enter the destination directory path : C:\Users\DELL\Desktop\Temp

The program has successfully organized the files in the directory .

Explanation:

o The os and shutil modules are imported to perform file system operations and move files between
directories.
o The source_dir and dest_dir variables are defined using the input() function to get user input for the
source and destination directories. The .replace('\\', '/') method is used to replace backslashes with
forward slashes in the file paths to ensure compatibility across different operating systems.
o The extension_map dictionary is defined to map file extensions to their respective folders. Each file
extension is key in the dictionary, and its value is the folder name where files with that extension
should be moved.
o The set() function is used to get a set of unique folder names from the values of the extension_map
o A for loop is then used to iterate over the set of folder names and create each folder in the destination
directory using os.makedirs(). The exist_ok=True argument ensures that the function does not raise
an error if the folder already exists.
o Another for loop is used to iterate over each file in the source directory using listdir(). For each file,
the os.path.splitext() function is used to get the file extension in lowercase. We then check if the
extension is in the extension_map. If it is, we use shutil.move() to move the file to the appropriate
folder in the destination directory

Special Methods

In this section, we will learn about a variety of instance methods that


are reserved by Python, which affect an object’s high level behavior and
its interactions with operators. These are known as special
methods. __init__ is an example of a special method; recall that it
controls the process of creating instances of a class. Similarly, we will
see that __add__ controls the behavior of an object when it is operated
on by the + symbol, for example. In general, the names of special
methods take the form of __<name>__ , where the two underscores
preceed and succeed the name. Accordingly, special methods can also
be referred to as “dunder” (double-underscore) methods. Learning to
leverage special methods will enable us to design elegant and powerful
classes of objects.

These methods give us complete control over the various high-level interfaces
that we use to interact with objects. Let’s make a simple class with nonsensical
behavior to demonstrate our ability to shape how our class behaves:
Variable in Python

Object-oriented programming lets the developers use variables at the class


level or the instance level. Variables are necessary symbols standing in for a
value we are utilizing in a program.

Variables at the class level are known as class variables, whereas variables at
the instance level are known as instance variables.

Whenever we expect that the variables are about to be consistent across


instances, or whenever we have to initialize a variable, then that variable can be
defined at the class level. Whenever we look forward to the variables that will
alter significantly across instances, then that variable can be defined at the
instance level.

Among various principles of software development is the principle of DRY, which


is abbreviated for Don't Repeat Yourself. This principle is focused towards
restrictive replication within the code, and object-oriented programming obeys
the DRY principle since it decreases redundancy.

In the following tutorial, we will understand the class as well as instance


variables in Object-Oriented Programming in the Python programming language.
We will also discuss the fundamental differences between these two variables.

So, let's get begun.

Understanding the Class Variables

Class Variables are declared inside the construction of class. Since these
variables are owned by the class itself, they are shared by all class instances.
They, therefore, will usually have the equivalent value for each instance unless
we are utilizing the class variable in order to initialize a variable.

Class Variables are defined outside of all the methods by convention, classically
placed right under the header class and before the method of constructor and
other functions.

Let us consider the following syntax of a class variable.

Syntax:

1. # defining the class


2. class Class_name:
3. # declaring the variable in the class
4. var = "xyz"

The "var" variable is assigned the "xyz" value in the above snippet of code.

We can define an object of the Class_name class (we will call it "myObj") and
print the variable with the help of the dot notation:

Syntax:
1. # defining the class
2. class Class_name:
3. # declaring the variable in the class
4. var = "xyz"
5. # instantiating the class
6. myObj = Class_name()
Python Inheritance

Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides


code reusability to the program because we can use an existing class to create a new
class instead of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class. In this section of the tutorial,
we will discuss inheritance in detail.

In python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name. Consider the following syntax to inherit a base
class into the derived class.

Syntax
1. class derived-class(base class):
2. <class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider
the following syntax.

Syntax
1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>
Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()

Output:

dog barking
Animal Speaking
Python Multi-Level inheritance

Multi-Level inheritance is possible in python like other object-oriented languages. Multi-


level inheritance is archived when a derived class inherits another derived class. There is
no limit on the number of levels up to which, the multi-level inheritance is archived in
python.

The syntax of multi-level inheritance is given below.

Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
7. .
8. .
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()
14. d.speak()
15. d.eat()

Output:

dog barking
Animal Speaking
Eating bread...

Python Multiple inheritance

Python provides us the flexibility to inherit multiple base classes in the child class.
The syntax to perform multiple inheritance is given below.

Syntax
1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
10. <class-suite>
11.
12. class Derived(Base1, Base2, ...... BaseN):
13. <class-suite>
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))

Output:

30
200
0.5

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.

Consider the following example.

Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(issubclass(Derived,Calculation2))
12. print(issubclass(Calculation1,Calculation2))

Output:

True
False

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.

Consider the following example.

Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10.d = Derived()
11. print(isinstance(d,Derived))

Output:

True

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.

Consider the following example to perform method overriding in python.

Example
1. class Animal:
2. def speak(self):
3. print("speaking")
4. class Dog(Animal):
5. def speak(self):
6. print("Barking")
7. d = Dog()
8. d.speak()

Output:

Barking
Real Life Example of method overriding
1. class Bank:
2. def getroi(self):
3. return 10;
4. class SBI(Bank):
5. def getroi(self):
6. return 7;
7.
8. class ICICI(Bank):
9. def getroi(self):
10. return 8;
11. b1 = Bank()
12. b2 = SBI()
13. b3 = ICICI()
14. print("Bank Rate of interest:",b1.getroi());
15. print("SBI Rate of interest:",b2.getroi());
16. print("ICICI Rate of interest:",b3.getroi());

Output:

Bank Rate of interest: 10


SBI Rate of interest: 7
ICICI Rate of interest: 8

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.

Consider the following example.

Example
1. class Employee:
2. __count = 0;
3. def __init__(self):
4. Employee.__count = Employee.__count+1
5. def display(self):
6. print("The number of employees",Employee.__count)
7. emp = Employee()
8. emp2 = Employee()
9. try:
10. print(emp.__count)
11. finally:
12. emp.display()

Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'
Polymorphism in Python



What is Polymorphism: The word polymorphism means having
many forms. In programming, polymorphism means the same
function name (but different signatures) being used for different
types. The key difference is the data types and number of
arguments used in function.
Example of inbuilt polymorphic functions:
 Python3
# 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]))

Output
5
3
Examples of user-defined polymorphic functions:

 Python3

# A simple Python function to demonstrate


# Polymorphism

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


return x + y+z

# Driver code
print(add(2, 3))
print(add(2, 3, 4))

Output
5
9

Polymorphism with class methods:


The below code shows how Python can use two different class types,
in the same way. We create a for loop that iterates through a tuple
of objects. Then call the methods without being concerned about
which class type each object is. We assume that these methods
actually exist in each class.

 Python3
class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi is the most widely spoken language of India.")

def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")

def type(self):
print("USA is a developed country.")

obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()

Output
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

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.
 Python3
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.

Polymorphism with a Function and objects:


It is also possible to create a function that can take any object,
allowing for polymorphism. In this example, let’s create a function
called “func()” which will take an object which we will name “obj”.
Though we are using the name ‘obj’, any instantiated object will be
able to be called into this function. Next, let’s give the function
something to do that uses the ‘obj’ object we passed to it. In this
case, let’s call the three methods, viz., capital(), language() and
type(), each of which is defined in the two classes ‘India’ and ‘USA’.
Next, let’s create instantiations of both the ‘India’ and ‘USA’ classes
if we don’t have them already. With those, we can call their action
using the same func() function:

 Python3
def func(obj):
obj.capital()
obj.language()
obj.type()

obj_ind = India()
obj_usa = USA()

func(obj_ind)
func(obj_usa)

Code: Implementing Polymorphism with a Function

 Python3
class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi is the most widely spoken language of India.")

def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")

def type(self):
print("USA is a developed country.")

def func(obj):
obj.capital()
obj.language()
obj.type()
obj_ind = India()
obj_usa = USA()

func(obj_ind)
func(obj_usa)

Output
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
Simple example of polymorphism:
polymorphism in Python using inheritance and method overriding:

 Python3

class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement this method")

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

# Create a list of Animal objects


animals = [Dog(), Cat()]

# Call the speak method on each object


for animal in animals:
print(animal.speak())
Python type() Function
The type() function in Python is a built-in function that returns the type of
the predetermined object or constructs another class dynamically.

o Assuming a single argument is passed to the function, it returns the type


of that object.
o In the case that three arguments are passed, it returns another new type
of object.

The type() function is regularly utilised in metaprogramming, where


projects can adjust themselves during runtime. Using the type() function,
a program can dynamically build new classes and change existing ones.
This is particularly valuable in libraries and frameworks where new classes
should be made depending on the input of the user.

Syntax:
1.
2. type(object)
3. type(name, bases, dict)
Parameters:
object: The type() returns the type of this object if one parameter is
specified.

name (optional): It is the name of the class.

bases (optional): It specifies the base classes.

dict (optional): It specifies the namespace with the definition for the
class.

Returns:
It returns the type of the specified object if a single argument is passed to
the type(). If three arguments are passed, it returns a new type of object.

Python type() Function: Single argument


Let's see an example of the type() function when single argument is
passed:

Code
1.
2. # Python type() function when single argument is passed
3. my_word = " Javatpoint "
4. print(type(my_word))

Output:

< class 'str'>

Explanation:

In the above example, we have utilised the type() function to find out the
type of the string object my_word. The type() function returns < class ' str
'>, showing that my_word is a string object.

Python type() Function: Three arguments


Let's see an example of the type() function when three arguments are
passed:

Code

1.
2. # Python type() function when three arguments are passed
3. BaseClass = type(' BaseClass ', (), { 'a' : 100})
4. print(type(BaseClass))

Output:

< class 'type'>

Explanation:

In the above example, we have utilised the type() function to create another new class,
BaseClass. We have passed three arguments to the type() function: the name of the new
class BaseClass, a void tuple showing that there are no base classes, and a word
reference "a" with a value of 100. At last, we have printed the type of the BaseClass
object utilising the type() function, which returns <class 'type' >.

Python type() Function Example

The below example shows how to get the type of an object.

Code

1.
2. # Python program for type() function
3. # List
4. List = [4, 5]
5. print(type(List))
6. # Dictionary
7. Dict = {4: 'four', 5: 'five'}
8. print(type(Dict))
9. # Class
10. class Python:
11. a = 0
12.
13. InstanceOfPython = Python()
14. print(type(InstanceOfPython))

Output:

<class 'list'>
<class 'dict'>
<class '__main__.Python'>

Explanation:

In the above example, we have taken a list object 'List' that contains some
values, and in return, it prints the type of the List. In the second case, we
have taken a dictionary object 'Dict' that contains some values, and in
return, it prints the type of the Dict. Then, we have defined a class named
as Python and produced an InstanceOfPython which prints its type.

Conclusion:

In conclusion, the type() function in Python is a built-in function that is


utilised to find out the type of an object or to create a new class in a
dynamic way. The type() function takes one or three arguments and is a
useful asset for metaprogramming in Python.

Python Custom Exceptions

In the previous tutorial, we learned about different built-in exceptions in


Python and why it is important to handle exceptions. .
However, sometimes we may need to create our own custom exceptions
that serve our purpose.

Defining Custom Exceptions


In Python, we can define custom exceptions by creating a new class that
is derived from the built-in Exception class.
Here's the syntax to define custom exceptions,

class CustomError(Exception):
...
pass

try:
...

except CustomError:
...

Here, CustomError is a user-defined error which inherits from


the Exception class.
Note:

 When we are developing a large Python program, it is a good


practice to place all the user-defined exceptions that our program
raises in a separate file.
 Many standard modules define their exceptions separately
as exceptions.py or errors.py (generally but not always).

Example: Python User-Defined Exception


# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass

# you need to guess this number


number = 18

try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote")

except InvalidAgeException:
print("Exception occurred: Invalid Age")
Run Code

Output
If the user input input_num is greater than 18,

Enter a number: 45
Eligible to Vote

If the user input input_num is smaller than 18,

Enter a number: 14
Exception occurred: Invalid Age

In the above example, we have defined the custom


exception InvalidAgeException by creating a new class that is derived from
the built-in Exception class.
Here, when input_num is smaller than 18, this code generates an exception.

Python Functions is a block of statements that return the specific task. The idea
is to put some commonly or repeatedly done tasks together and make a function so
that instead of writing the same code again and again for different inputs, we can do
the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability

Python Function Declaration


The syntax to declare a function is:
Syntax of Python Function Declaration

Types of Functions in Python

There are mainly two types of functions in Python.


 Built-in library function: These are Standard functions in Python that are
available to use.
 User-defined function: We can create our own functions based on our
requirements.
Creating a Function in Python
We can create a user-defined function in Python, using the def keyword. We can add
any type of functionalities and properties to it as we require.
Python3
# A simple Python function

def fun():

print("Welcome to GFG")

Calling a Python Function

After creating a function in Python we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.

Python3
# A simple Python function
def fun():

print("Welcome to GFG")

# Driver code to call a function

fun()

Output:
Welcome to GFG

Python Function with Parameters

If you have experience in C/C++ or Java then you must be thinking about the return
type of the function and data type of arguments. That is possible in Python as well
(specifically for Python 3.5 and above).
Defining and calling a function with parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
The following example uses arguments and parameters that you will learn later in this
article so you can come back to it again if not understood.
Python3
def add(num1: int, num2: int) -> int:

"""Add two numbers"""

num3 = num1 + num2

return num3

# Driver code

num1, num2 = 5, 15

ans = add(num1, num2)

print(f"The addition of {num1} and {num2} results {ans}.")

Output:
The addition of 5 and 15 results 20.
Note: The following examples are defined using syntax 1, try to convert them in
syntax 2 for practice.
Python3
# some more functions

def is_prime(n):

if n in [2, 3]:

return True

if (n == 1) or (n % 2 == 0):

return False

r = 3

while r * r <= n:

if n % r == 0:

return False

r += 2

return True

print(is_prime(78), is_prime(79))

Output:
False True

Python Function Arguments


Arguments are the values passed inside the parenthesis of the function. A function can
have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the
number passed as an argument to the function is even or odd.

# A simple Python function to check

# whether x is even or odd

def evenOdd(x):

if (x % 2 == 0):

print("even")

else:

print("odd")

# Driver code to call the function


evenOdd(2)

evenOdd(3)

Output:
even
odd

Types of Python Function Arguments

Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following 4 types of function arguments.
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)
Let’s discuss each type in detail.
Default Arguments
A default argument is a parameter that assumes a default value if a value is not
provided in the function call for that argument. The following example illustrates
Default arguments.
Python3
# Python program to demonstrate

# default arguments

def myFun(x, y=50):

print("x: ", x)

print("y: ", y)

# Driver code (We call myFun() with only

# argument)

myFun(10)

Output:
x: 10
y: 50
Like C++ default arguments, any number of arguments in a function can have a
default value. But once we have a default argument, all the arguments to its right must
also have default values.
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the
caller does not need to remember the order of parameters.

# Python program to demonstrate Keyword Arguments

def student(firstname, lastname):

print(firstname, lastname)

# Keyword arguments

student(firstname='Geeks', lastname='Practice')

student(lastname='Practice', firstname='Geeks')

Output:
Geeks Practice
Geeks Practice

Positional Arguments

We used the Position argument during the function call so that the first argument (or
value) is assigned to name and the second argument (or value) is assigned to age. By
changing the position, or if you forget the order of the positions, the values can be
used in the wrong places, as shown in the Case-2 example below, where 27 is
assigned to the name and Suraj is assigned to the age.
def nameAge(name, age):

print("Hi, I am", name)

print("My age is ", age)

# You will get correct output because

# argument is given in order

print("Case-1:")

nameAge("Suraj", 27)

# You will get incorrect output because

# argument is not in order

print("\nCase-2:")
nameAge(27, "Suraj")

Output:
Case-1:
Hi, I am Suraj
My age is 27

Case-2:
Hi, I am 27
My age is Suraj

Arbitrary Keyword Arguments

In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable
number of arguments to a function using special symbols. There are two special
symbols:
 *args in Python (Non-Keyword Arguments)
 **kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument
Python3
# Python program to illustrate

# *args for variable number of arguments

def myFun(*argv):

for arg in argv:

print(arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output:
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments
Python3
# Python program to illustrate
# *kwargs for variable number of keyword argument

def myFun(**kwargs):

for key, value in kwargs.items():

print("%s == %s" % (key, value))

# Driver code

myFun(first='Geeks', mid='for', last='Geeks')

Output:
first == Geeks
mid == for
last == Geeks

Docstring

The first string after the function is called the Document string or Docstring in short.
This is used to describe the functionality of the function. The use of docstring in
functions is optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function:
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function
Python3
# A simple Python function to check

# whether x is even or odd

def evenOdd(x):

"""Function to check if the number is even or odd"""

if (x % 2 == 0):

print("even")

else:

print("odd")
# Driver code to call the function

print(evenOdd.__doc__)

Output:
Function to check if the number is even or odd

Python Function within Functions


A function that is defined inside another function is known as the inner function or
nested function. Nested functions are able to access variables of the enclosing scope.
Inner functions are used so that they can be protected from everything happening
outside the function.

Python3
# Python program to

# demonstrate accessing of

# variables of nested functions

def f1():

s = 'I love GeeksforGeeks'

def f2():

print(s)

f2()

# Driver's code

f1()

Output:
I love GeeksforGeeks

Anonymous Functions in Python


In Python, an anonymous function means that a function is without a name. As we
already know the def keyword is used to define the normal functions and the lambda
keyword is used to create anonymous functions.
Python3
# Python code to illustrate the cube of a number

# using lambda function

def cube(x): return x*x*x


cube_v2 = lambda x : x*x*x

print(cube(7))

print(cube_v2(7))

Output:
343
343

Return Statement in Python Function


The function return statement is used to exit from a function and go back to the
function caller and return the specified value or data item to the caller. The syntax for
the return statement is:
return [expression_list]
The return statement can consist of a variable, an expression, or a constant which is
returned at the end of the function execution. If none of the above is present with the
return statement a None object is returned.
Example: Python Function Return Statement
Python3
def square_value(num):

"""This function returns the square

value of the entered number"""

return num**2

print(square_value(2))

print(square_value(-4))

Output:
4
16

Pass by Reference and Pass by Value


One important thing to note is, in Python every variable name is a reference. When we
pass a variable to a function, a new reference to the object is created. Parameter
passing in Python is the same as reference passing in Java.

Python3
# Here x is a new reference to same list lst

def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified

# after function call.

lst = [10, 11, 12, 13, 14, 15]

myFun(lst)

print(lst)

Output:
[20, 11, 12, 13, 14, 15]
When we pass a reference and change the received reference to something else, the
connection between the passed and received parameter is broken. For example,
consider the below program as follows:

Python3
def myFun(x):

# After below line link of x with previous

# object gets broken. A new object is assigned

# to x.

x = [20, 30, 40]

# Driver Code (Note that lst is not modified

# after function call.

lst = [10, 11, 12, 13, 14, 15]

myFun(lst)

print(lst)

Output:
[10, 11, 12, 13, 14, 15]
Another example demonstrates that the reference link is broken if we assign a new
value (inside the function).

Python3
def myFun(x):
# After below line link of x with previous

# object gets broken. A new object is assigned

# to x.

x = 20

# Driver Code (Note that x is not modified

# after function call.

x = 10

myFun(x)

print(x)

Output:
10
Exercise: Try to guess the output of the following code.
Python3
def swap(x, y):

temp = x

x = y

y = temp

# Driver code

x = 2

y = 3

swap(x, y)

print(x)

print(y)

Output:
2
3

Python User-defined functions


All the functions that are written by any of us come under the
category of user-defined functions. Below are the steps for writing
user-defined functions in Python.
 In Python, a def keyword is used to declare user-defined
functions.
 An indented block of statements follows the function name
and arguments which contains the body of the function.
Syntax:
def function_name():
statements
.
.
Example: Here we have created the fun function and then called
the fun() function to print the statement.
Python3
# Declaring a function

def fun():

print("Inside function")

# Driver's code

# Calling function

fun()

Output:
Inside function
Python Parameterized Function
The function may take arguments(s) also called parameters as
input within the opening and closing parentheses, just after the
function name followed by a colon.
Syntax:
def function_name(argument1, argument2, ...):
statements
.
.
Example:
A simple Python function to check whether x is even or odd.
Python3
def evenOdd( x ):

if (x % 2 == 0):
print("even")

else:

print("odd")

# Driver code

evenOdd(2)

evenOdd(3)

Output:
even
odd
Python Default arguments
A default argument is a parameter that assumes a default value if a
value is not provided in the function call for that argument. The
following example illustrates Default arguments.
Example: We call myFun() with the only argument.
Python3
# Python program to demonstrate

# default arguments

def myFun(x, y = 50):

print("x: ", x)

print("y: ", y)

# Driver code

myFun(10)

Output:
x: 10
y: 50
How to pass optional parameters to a
function in Python?



In Python, when we define functions with default values for certain
parameters, it is said to have its arguments set as an option for the
user. Users can either pass their values or can pretend the function
to use theirs default values which are specified.
In this way, the user can call the function by either passing those
optional parameters or just passing the required parameters.
There are two main ways to pass optional parameters in python
 Without using keyword arguments.
 By using keyword arguments.
Passing without using keyword arguments
Some main point to be taken care while passing without using
keyword arguments is :
The order of parameters should be maintained i.e. the order

in which parameters are defined in function should be
maintained while calling the function.
 The values for the non-optional parameters should be
passed otherwise it will throw an error.
 The value of the default arguments can be either passed or
ignored.
Below are some codes which explain this concept.
Example 1:
 Python3

# Here b is predefined and hence is optional.


def func(a, b=1098):
return a+b

print(func(2, 2))

# this 1 is represented as 'a' in the function and


# function uses the default value of b
print(func(1))

Output:
4
1099

Passing collections as Parameters to a function


in Python//passing collections to the function
In Python, we can also pass a collection as a list, tuple, set, or dictionary
as a parameter to a function. Here the changes made to the collection
also affect the collection outside the function. But if it is redefined then
the collection outside the function does not gets affected. Because the
redefined collection becomes local for the function. For example, consider
the following code.
Python code to pass a list as parameter.
def sample_function(list_1, list_2):
list_1.append([6, 7, 8])
print(f'Inside function list 1 is {list_1}')
list_2 = [40, 50, 60]
print(f'Inside function list 2 is {list_2}')

my_list_1 = [1, 2, 3, 4, 5]
my_list_2 = [10, 20, 30]
sample_function(my_list_1, my_list_2)
print(f'Outside function list 1 is {my_list_1}')
print(f'Outside function list 2 is {my_list_2}')

When we run the above example code, it produces the following output.

In the above example code, the list_1 was modified, so the changes made
in the function also affect outside the function. But the list_2 was
redefined, it does not affect the my_list_2 outside the function.

Function arguments in Python


In Python, there are different ways to pass arguments to a function. They
are as follows.

 Positional Arguments (or) Required Arguments


 Default Arguments
 Keyword Arguments
 Variable-length Arguments

How to use variable-length


arguments in a function in
Python?
PythonProgrammingServer Side Programming

As the name implies, an argument with a variable length can take on a


variety of values. You define a variable argument using a '*', for example
*args, to show that the function can take a variable number of arguments.

Observations on Python's variable-length arguments are as follows.

 The designation "*args" for variable length arguments is not required.


The only thing needed is *; the variable name can be anything, like
*names or *numbers.
 You can send zero or more arguments to a function using a variable
length argument.
 A tuple is used to store the values passed to *args.
 A formal argument may come before a variable args but not after one.
You can use keyword arguments following a variable argument.

*args in function
To pass a variable number of arguments to a function in Python, use the
special syntax *args in the function specification. It is used to pass a variable-
length, keyword-free argument list. By convention, the sign * is frequently
used with the word args in the syntax for taking in a variable number of
arguments.

You can accept additional arguments using *args than the number of formal
arguments you previously defined. Any number of additional arguments can
be added to your current formal parameters using *args (including zero extra
arguments).

For instance, we wish to create a multiply function that can multiple any
number of inputs simultaneously. The use of variable parameters makes your
function more adaptable in situations where the precise number of
arguments is unknown at first. Imagine that you have a function that adds
numbers. The special syntax *args in function definitions in Python is
used to pass a variable number of arguments to a function. It is
used to pass a non-keyworded, variable-length argument list.
 The syntax is to use the symbol * to take in a variable
number of arguments; by convention, it is often used with
the word args.
 What *args allows you to do is take in more arguments
than the number of formal arguments that you previously
defined. With *args, any number of extra arguments can be
tacked on to your current formal parameters (including
zero extra arguments).
 For example, we want to make a multiply function that
takes any number of arguments and is able to multiply
them all together. It can be done using *args.
 Using the *, the variable that we associate with the *
becomes iterable meaning you can do things like iterate
over it, run some higher-order functions such as map and
filter, etc.

Example 1

The following example demonstrates the usage of a regular function with


fixed number of parameters.

def add(num1, num2):


return num1+num2
print(add(4,5))
Output

The output generated is as follows.

You can specify that a function accepts a variable number of arguments and
can be used to add up to 'n' numbers by altering the argument to *args.
Example 2

The following example demonstrates the usage of a function that takes


variable length arguments.

def add_num(*args):
sum = 0
for num in args:
sum += num
return sum
result = add_num(1, 2, 3)
print('Sum is', result)
result = add_num(10, 20, 30, 40)
print('Sum is', result)
22
result = add_num(5, 6, 7, 8, 9)
print('Sum is', result)
Output

The output generated is as follows.

Sum is 6
Sum is 100
Sum is 35

**kwargs in a function
A keyworded, variable-length argument list is passed using the specific
syntax **kwargs in Python function declarations. With the double star, we use
the name kwargs. The double star's ability to pass through keyword
arguments is the cause for this (and any number of them).When passing a
variable into a function, you can give it a name using a keyword parameter.

The kwargs can be viewed as a dictionary that associates each term with the
value that is passed along with it. Because of this, there doesn't appear to be
any sequence in which the kwargs were printed out when we iterate through
them. The special syntax **kwargs in function definitions in Python
is used to pass a keyworded, variable-length argument list. We use
the name kwargs with the double star. The reason is that the
double star allows us to pass through keyword arguments (and any
number of them).
 A keyword argument is where you provide a name to the
variable as you pass it into the function.
 One can think of the kwargs as being a dictionary that
maps each keyword to the value that we pass alongside it.
That is why when we iterate over the kwargs there doesn’t
seem to be any order in which they were printed out.

Example

The following example takes arguments using **kwargs.

def intro(**data):
print("\nData type of argument:",type(data))
for key, value in data.items():
print("{} is {}".format(key,value))
intro(EmployeeName="George", Lastname="Jackson", Age=22,
Phone=1234567890)
intro(Firstname="James", Lastname="Jude",
Email="[email protected]", Country="USA", Age=25,
Phone=9876543210)
Output

The output generated is as follows.

Data type of argument: <class 'dict'>


EmployeeName is George
Lastname is Jackson
Age is 22
Phone is 1234567890

Data type of argument: <class 'dict'>


Firstname is James
Lastname is Jude
Email is [email protected]
Country is USA
Age is 25
Phone is 9876543210
Using both *args and **kwargs in Python to call a function
Example 1:
Here, we are passing *args and **kwargs as an argument in the myFun
function. Passing *args to myFun simply means that we pass the positional and
variable-length arguments which are contained by args. so, “Geeks” pass to the
arg1 , “for” pass to the arg2, and “Geeks” pass to the arg3. When we pass
**kwargs as an argument to the myFun it means that it accepts keyword
arguments. Here, “arg1” is key and the value is “Geeks” which is passed to
arg1, and just like that “for” and “Geeks” pass to arg2 and arg3 respectively.
After passing all the data we are printing all the data in lines.

 python3

def myFun(arg1, arg2, arg3):


print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)

# Now we can use *args or **kwargs to


# pass arguments to this function :
args = ("Geeks", "for", "Geeks")
myFun(*args)

kwargs = {"arg1": "Geeks", "arg2": "for", "arg3": "Geeks"}


myFun(**kwargs)

Output:
arg1: Geeks

arg2: for

arg3: Geeks

arg1: Geeks

arg2: for

arg3: Geeks

Example 2:
Here, we are passing *args and **kwargs as an argument in the myFun function.
where ‘geeks’, ‘for’, ‘geeks’ is passed as *args, and first=”Geeks”, mid=”for”,
last=”Geeks” is passed as **kwargs and printing in the same line.

 python3

def myFun(*args, **kwargs):


print("args: ", args)
print("kwargs: ", kwargs)

# Now we can use both *args ,**kwargs


# to pass arguments to this function :
myFun('geeks', 'for', 'geeks', first="Geeks", mid="for", last="Geeks")

Output:
args: ('geeks', 'for', 'geeks')
kwargs: {'first': 'Geeks', 'mid': 'for', 'last': 'Geeks'}

Python Scope

A variable is only available from inside the region it is created. This is


called scope.

Variable Scope in Python

Variables in Python language serve as the storage units for the various
data values and data structures. When a variable is assigned to any
Python object, it then points toward that object since they are reference,
or a pointer, to that particular object in the memory location. Python
programming language is not "statically typed," unlike other languages
like C/C++/JAVA. Variables do not have to have their types or initial values
declared before use. When a variable is initially given a value, it is
considered to have been formed.

Code

1. # Python program to show how variables are assigned to the data v


alues
2.
3. # Assigning a variable name to an integer
4. integer = 45
5.
6. # Assigning a variable name to a floating point number
7. floating = 1456.8
8.
9. # Assigning a variable name to a string
10.string = "John"
11.
12.print("This value is stored in the variable 'integer':- ", integer)
13. print("This value is stored in the variable 'floating':- ", floating
)
14.print("This value is stored in the variable 'string':- ", string)
Output:

This value is stored in the variable 'integer':- 45


This value is stored in the variable 'floating':- 1456.8
This value is stored in the variable 'string':- John

Scope of a Variable

The scope of a Python variable refers to the area where we may locate it
and, if necessary, access it.

Global and Local Variables

Global variables are those we declare and define outside of any functions
but not specific to any of them. Any section of the program can make use
of them.

Code

1. # Python program to show how any function can use global variable
s
2.
3. # Declaring a global variable
4. a = 2
5.
6. # Accessing the global variable in the main function
7. print("This is in the main function:- ", a)
8.
9. # Defining a function that uses the global variable
10.def f1():
11. print("This is in function 'f1()':- ", a)
12.
13. # Defining another function that uses the global variable
14.def f2():
15. print("This is in function 'f2()':- ", a)
16.
17. # Calling the functions
18.f1()
19. f2()

Output:

This is in the main function:-


2
This is in function 'f1()':-
2
This is in function 'f2()':-
2

Suppose a variable is defined within the local scope of that function and
has the same name as the global variable. In that case, it will only display
the value supplied to the variable inside that particular function and not
the value assigned in the global scope.

Code

1. # Python program to show function accesses the variable value that


is in the function's scope
2.
3. # Declaring a global variable
4. a = "This is assigned in the global scope."
5.
6. # Defining a function that has a variable having the name same as the glo
bal variable
7. def func():
8. a = "This is defined inside the function."
9. print(a)
10.
11. # Calling the function
12.func()

Output:

This is defined inside the function.

Before defining the function func(), the variable 'a' is assigned to a string
that states, "This is assigned in the global scope.". The print(a) statement
of the function func() will first search for variable 'a' in its local scope.
Since there is already a variable 'a' assigned to a different string, the
function will print the value of this variable and will not go in the global
scope. The function, in this case, will not use the value of variable 'a' from
the global scope.

What will be the result of modifying the value of variable 'a' inside the
function 'func()' is the next question. Will it also have an impact on the
global variable 'a'? The following snippet of code is used to test it:

Code
1. # Python program to show function accesses the variable value that
is in the function's scope
2.
3. # Declaring a global variable
4. a = "This is assigned in the global scope."
5.
6. # Defining a function that has a variable having the name same as the glo
bal variable
7. def func():
8. a = "This is defined inside the function."
9. print("Accessed in the local scope of function:- ", a)
10.
11. # Calling the function
12.func()
13.
14.# Accessing the variable a in the global scope after changing its value insi
de the function
15. print("Accessed in the global scope:- ", a)

Output:

Accessed in the local scope of function:- This is defined inside the


function.
Accessed in the global scope:- This is assigned in the global scope.

We must use the Python global keyword to make the preceding program
function. Only when making assignments or changing the variable value
do we need to use the Python global keyword inside a function. The global
keyword is not necessary for displaying and accessing a variable present
in the global scope. Why? Since the assignment to the variable 'a' inside
of func(), Python "presumes" that we desire to access the local variable,
which is why the initial print command returns the variable's value in the
local scope. If a variable is modified or assigned inside a function without
being defined as a global variable, it is considered a local variable. The
following example demonstrates how to use the global keyword to instruct
the Python interpreter that we wish to modify the global variable:

Code

1. # Python program to show function accesses the variable value that


is in the function's scope
2.
3. # Declaring a global variable
4. a = "This is assigned in the global scope."
5.
6. # Defining a function that uses the global keyword before assigning a new
value to the global variable
7. def func():
8. global a
9. a = "This is defined inside the function."
10.
11. print("Accessed in the local scope of function:- ", a)
12.
13. # Calling the function
14.func()
15.
16.# Accessing the variable a in the global scope after changing its value insi
de the function
17. print("Accessed in the global scope:- ", a)

Output:

Accessed in the local scope of function:- This is defined inside the


function.
Accessed in the global scope:- This is defined inside the function.

Summarising the Global Local Variable Scope.

Code

1. # Python program to summarise the global and local variable scope.

2.
3. # Defining a variable in the global scope
4. a = 'in the global scope'
5.
6. # This function will print the global variable because there does not exist a
ny local variable 'a'
7. def func():
8. print('Inside func(): ', a)
9.
10.# This function will print the value assigned to the local variable 'a'
11. # Because we are not using the global keyword
12.def local():
13. a = 'inside function local()'
14. print('Inside local(): ', a)
15.
16.# This function will modify the global variable because we are using the gl
obal keyword
17. def global_():
18. global a
19. a = 'changed inside function global_()'
20. print('Inside global_() : ', a)
21.
22.# Calling the functions
23. # Value of 'a' in global scope after each function call
24.print('global: ', a)
25. func()
26.print('global: ', a)
27. local()
28.print('global: ', a)
29. global_()
30.print('global: ', a)

Output:

global: in the global scope


Inside func(): in the global scope
global: in the global scope
Inside local():
inside function local()
global: in the global scope
Inside global_() :
changed inside function global_()
global: changed inside function global_()

First-Class Citizens in Python

First-class citizens are entities that enable support for all the operations
facilitating other fellow entities.

These entities are often used : while passing an argument , returning a value
from function , conditional modifications & value assignment.
In this article, we will look at the implementation & usage of first-class
citizens in Python 3.x or earlier. Also, we will be learning what all entities get
the tag of being First Class citizens.

These citizens include Variables along with functions.

Let’s first get familiar with the data types that are part of First-
class citizens

 Integers
 Floating type
 Complex Numbers
 Strings

All four types mentioned above are given the tag of being first-class citizens
in Python 3.x. Or earlier.

Example
#Declaration of an integer
print("hello world")
int_inp=int(input())
print("This is a First class Citizen of "+str(type(int_inp)))
#Declaration of floating type
float_inp=float(input())
print("This is a First class Citizen of "+str(type(float_inp)))
#Declaration of complex numbers
complex_inp=complex(input())
print("This is a First class Citizen of "+str(type(complex_inp)))
#Declaration of Strings
str_inp=input()
print("This is a First class Citizen of "+str(type(str_inp)))

Input
2
23.4
4+7j
tutorialspoint

Output
This is a First class Citizen of <class 'int'>
This is a First class Citizen of <class 'float'>
This is a First class Citizen of <class 'complex'>
This is a First class Citizen of <class 'str'>

Now Let’s take a look at some functions which are referred to as first class
citizens

First class objects are uniformly handled in Python language. Being


objectoriented every entity refers to a default object which can be
referenced and dereferenced at any point of time. Storage may be done
using data structures or control structures.

Now we will look whether python supports first-class functions or not. So


any language is said to support first-class functions when it treats
functions as firstclass objects.

Example
# Python program
# functions being be treated as objects
def comp_name(text):
return text.isupper()
print(comp_name("TUTORIALSPOINT"))
new_name = comp_name #referencing a function with the object
print(new_name("TutorialsPoint"))

Output

True
False

Pass function as parameter python//Passing


Functions to a Function
In this article, we are discussing the pass function as a parameter in
python. Functions can take multiple arguments. These arguments can be
objects, variables (of the same or different data types), and functions.
Python functions are the first elegant gadgets.

Within the following instance, a feature is assigned to a variable. This


project no longer names a function. This takes the feature object pointed
to by "shout" and creates a second call, "yell," pointing to it.
Facts may be exceeded to features as arguments. Arguments are unique
after the characteristic call-in parentheses. You could add as many
arguments as possible; separate them with commas.

The following example has a function with one argument (fname). At the
same time, the function is referred to as passing the name used in the
characteristic to print the overall call.

Example 1: Right here, we give an instance of the pass function as a


parameter in python. The example is given below -

1. def my_function(fname):
2. print(fname + " Id")
3. my_function("Emil")
4. my_function("Phone")

Result: We assemble the above program, and after compilation, we run


the program. Then the result is given below -

Email Id
Phone Id

Example 2: Right here, we give another instance of the pass function as


a parameter in python. The example is given below -

1. def shout(text):
2. return text.upper()
3. print(shout('Hello World'))
4. yell = shout
5. print(yell('Hello Coders'))

Result: We assemble the above program, and after compilation, we run


the program. Then the result is given below -

HELLO WORLD
HELLO CODERS

Wrapper Function: A wrapper function or decorator allows you to wrap


another function and extend it without permanently changing the
behavior of the wrapped function. In the decorator, the function is taken
as an argument of another function and called inside the wrapper
function.

Example 1: Right here, we give an instance of a wrapper function as a


parameter in python. The example is given below -

1. def hello_decorator(func):
2. def inner1():
3. print ("Hello coders, it is before the function execution")
4. func ()
5. print ("It is after the function execution")
6. return inner1
7. def function_to_be_used():
8. print ("It is inside of this function")
9. function_to_be_used = hello_decorator(function_to_be_used)
10. function_to_be_used()

Result: We assemble the above program, and after compilation, we run


the program. Then the result is given below -

Hello coders, it is before the function execution


It is inside of this function
It is after the function execution

Lambda wrapper function: In Python, a nameless function approach


that the character has no call. As you recognize, the def keyword defines
ordinary functions, and the lambda keyword is used to create anonymous
functions. This characteristic will have a variety of arguments but
evaluates and returns the simplest expression.

A lambda function also can have every other character as an argument.


The subsequent example suggests a primary Lambda characteristic
surpassed every other Lambda function as a controversy.

Example 1: Right here, we give an instance of the lambda wrapper


function as a parameter in python. The example is given below -

1. square = lambda a:a * a


2. cube = lambda func:func**3
3. print ("The square of 4 is:"+str (square (4)))
4. print ("\nThe cube of "+str (square (4)) +" is :" +str (cube (square (
4))))

Result: We assemble the above program, and after compilation, we run


the program. Then the result is given below -

The square of 4 is:16


The cube of 16 is: 4096

Higher order function: Since functions are objects, we can pass them
as arguments to other features. Capabilities that take other features as
arguments are also referred to as better-order functions. The subsequent
instance creates a Greet feature that takes a feature as an issue.
Example 1: Right here, we give an instance of a higher order function as
a parameter in python. The example is given below -

1. def shout(text):
2. return text.upper()
3. def whisper(text):
4. return text.lower()
5. def greet(function):
6. greeting = function ("Hello, we are created by a higher order func
tion passed as an argument.")
7. print(greeting)
8. greet(shout)
9. greet(whisper)

Result: We assemble the above program and run the program after
compilation. Then the result is given below -

HELLO, WE ARE CREATED BY A HIGHER ORDER FUNCTION PASSED AS AN ARGUMENT.


hello, we are created by a higher order function passed as an argument.

What is the use of the map function in Python?

In this article, we will learn the uses of the map function in Python.

What is a map() Function?


Python's map() function applies a function to each item in an iterator that is
provided as input. A list, tuple, set, dictionary or string can all be used as
iterators, and they all return iterable map objects. Map() is a built-in Python
function.

Syntax
map(function, iterator1,iterator2 ...iteratorN)
Parameters
 function − It is necessary to provide a map with a function that will be
applied to all of the iterator's available items.
 iterator − a mandatory iterable object. It could be a list, tuple, etc.
The map() function accepts multiple iterator objects as arguments.
Return Value

The map() method will apply the specified function to each item in the
iterator and produce a tuple, list, or another iterable map object.

How map() Function Works?


The function and iterable object are the two inputs for the map() function.
The function passed to map() is a normal function, and it will loop through
each value in the specified iterable object.

Using a map() with a list of Numbers


Example
The following program adds 5 to each element in a list using the map()
function in Python −
# creating a function that accepts the number as an argument
def exampleMapFunction(num):
# adding 5 to each number in a list and returning it
return num+5

# input list
inputList = [3, 5, 1, 6, 10]

# Passing above defined exampleMapFunction function


# and given list to the map() function
# Here it adds 5 to every element of the given list
modifiedList = map(exampleMapFunction, inputList)
# printing the modifies list(map object)
print(modifiedList)
# converting the map object to the list and printing it
print("Adding 5 to each element in a list using map():\n",
list(modifiedList))
Output
<map object at 0x7fb106076d10>
Adding 5 to each element in a list using map():
[8, 10, 6, 11, 15]

Using map() with Dictionary


Python uses dictionaries to implement what is more commonly referred to as
an associative array. A dictionary is a collection of key-value pairs. It is
defined using the curly brackets ().

Dictionaries are dynamic and changing. They can be changed and removed
as required. Dictionary items are accessible using keys, but list elements are
retrieved by their position in the list via indexing, which is how dictionaries
vary from lists.

Since the dictionary is an iterator, you can utilize it inside of the map()
function.

Example

The following program adds 5 to each element in a dictionary using the map()
function in Python −

# creating a function that accepts the number as an argument


def exampleMapFunction(num):
# adding 5 to each number in a dictionary and returning it
return num + 5

# input Dictionary
inputDictionary = {2, 3, 4, 5, 6, 7, 8, 9}

# passing above defined exampleMapFunction function


# and input dictionary to the map() function
# Here it adds 5 to every element of the given dictionary
modifiedDict = map(exampleMapFunction, inputDictionary)
# printing the modified dictionary(map object)
print(modifiedDict)
# converting the map object to the list and printing it
print("Adding 5 to each element in a dictionary using map():\n",
list(modifiedDict))
Output
<map object at 0x7fb1060838d0>
Adding 5 to each element in a dictionary using map():
[7, 8, 9, 10, 11, 12, 13, 14]
Using map() with Tuple
In Python, a tuple is an object with elements separated by commas and
enclosed in round brackets.

Example

The following code converts all the items in a tuple to lowercase using the
lower() and map() functions −

# creating a function that accepts the number as an argument


def exampleMapFunction(i):
# converting each item in tuple into lower case
return i.lower()

# input tuple
inputTuple = ('HELLO', 'TUTORIALSPOINT', 'pyTHON', 'CODES')

# passing above defined exampleMapFunction function


# and input tuple to the map() function
# Here it converts every element of the tuple to lower case
modifiedTuple = map(exampleMapFunction, inputTuple)
# printing the modified tuple(map object)
print(modifiedTuple)

print('Converting each item in a tuple to lowercase:')


# converting the map object to the list and printing it
print(list(modifiedTuple))
Output
<map object at 0x7fb10f773590>
Converting each item in a tuple to lowercase:
['hello', 'tutorialspoint', 'python', 'codes']
Python Lambda Functions



Python Lambda Functions are anonymous functions means that
the function is without a name. As we already know the def keyword
is used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function
in Python.
Python Lambda Function Syntax
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.
Python Lambda Function Example
In the example, we defined a lambda function(upper) to convert a
string to its upper case using upper().
This code defines a lambda function named upper that takes a string
as its argument and converts it to uppercase using
the upper() method. It then applies this lambda function to the string
‘GeeksforGeeks’ and prints the result
 Python3
str1 = 'GeeksforGeeks'

upper = lambda string: string.upper()

print(upper(str1))

Output:
GEEKSFORGEEKS
Use of Lambda Function in Python
Let’s see some of the practical uses of the Python lambda function.
Condition Checking Using Python lambda function
Here, the ‘format_numric’ calls the lambda function, and the num
is passed as a parameter to perform operations.
 Python3
format_numeric = lambda num: f"{num:e}" if isinstance(num, int) else f"{num:,.2f}"

print("Int formatting:", format_numeric(1000000))

print("float formatting:", format_numeric(999999.789541235))


Output:
Int formatting: 1.000000e+06
float formatting: 999,999.79
Difference Between Lambda functions and def defined function
The code defines a cube function using both the ‘def' keyword and a
lambda function. It calculates the cube of a given number (5 in this
case) using both approaches and prints the results. The output is
125 for both the ‘def' and lambda functions, demonstrating that
they achieve the same cube calculation.
 Python3
def cube(y):

return y*y*y

lambda_cube = lambda y: y*y*y

print("Using function defined with `def` keyword, cube:", cube(5))

print("Using lambda function, cube:", lambda_cube(5))

Output:
Using function defined with `def` keyword, cube: 125
Using lambda function, cube: 125
As we can see in the above example, both the cube() function
and lambda_cube() function behave the same and as intended.
Let’s analyze the above example a bit more:
With lambda function Without lambda function

Supports single-line sometimes Supports any number of lines inside a


statements that return some value. function block

Good for performing short Good for any cases that require multiple
operations/data manipulations. lines of code.

Using the lambda function can sometime We can use comments and function
reduce the readability of code. descriptions for easy readability.

Practical Uses of Python lambda function


Python Lambda Function with List Comprehension
On each iteration inside the list comprehension, we are creating a
new lambda function with a default argument of x (where x is the
current item in the iteration). Later, inside the for loop, we are
calling the same function object having the default argument
using item() and get the desired value. Thus, is_even_list stores
the list of lambda function objects.
 Python3
is_even_list = [lambda arg=x: arg * 10 for x in range(1, 5)]

for item in is_even_list:

print(item())

Output:
10
20
30
40
Python Lambda Function with if-else
Here we are using the Max lambda function to find the maximum of
two integers.
 Python3
Max = lambda a, b : a if(a > b) else b

print(Max(1, 2))

Output:
2
Python Lambda with Multiple Statements
Lambda functions do not allow multiple statements, however, we
can create two lambda functions and then call the other lambda
function as a parameter to the first function. Let’s try to find the
second maximum element using lambda.
The code defines a list of sublists called ‘List'. It uses lambda
functions to sort each sublist and find the second-largest element in
each sublist. The result is a list of second-largest elements, which is
then printed. The output displays the second-largest element from
each sublist in the original list.
 Python3
List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]]

sortList = lambda x: (sorted(i) for i in x)


secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]

res = secondLargest(List, sortList)

print(res)

Output:
[3, 16, 9]
Lambda functions can be used along with built-in functions
like filter(), map() and reduce().
Python Modules

In this tutorial, we will explain how to construct and import custom Python
modules. Additionally, we may import or integrate Python's built-in
modules via various methods.

What is Modular Programming?

Modular programming is the practice of segmenting a single, complicated


coding task into multiple, simpler, easier-to-manage sub-tasks. We call
these subtasks modules. Therefore, we can build a bigger program by
assembling different modules that act like building blocks.

Modularizing our code in a big application has a lot of benefits.

Simplification: A module often concentrates on one comparatively small


area of the overall problem instead of the full task. We will have a more
manageable design problem to think about if we are only concentrating
on one module. Program development is now simpler and much less
vulnerable to mistakes.

Flexibility: Modules are frequently used to establish conceptual


separations between various problem areas. It is less likely that changes
to one module would influence other portions of the program if modules
are constructed in a fashion that reduces interconnectedness. (We might
even be capable of editing a module despite being familiar with the
program beyond it.) It increases the likelihood that a group of numerous
developers will be able to collaborate on a big project.

Reusability: Functions created in a particular module may be readily


accessed by different sections of the assignment (through a suitably
established api). As a result, duplicate code is no longer necessary.

Scope: Modules often declare a distinct namespace to prevent identifier


clashes in various parts of a program.
In Python, modularization of the code is encouraged through the use of
functions, modules, and packages.

What are Modules in Python?


A document with definitions of functions and various statements written in
Python is called a Python module.

In Python, we can define a module in one of 3 ways:

o Python itself allows for the creation of modules.


o Similar to the re (regular expression) module, a module can be primarily
written in C programming language and then dynamically inserted at run-
time.
o A built-in module, such as the itertools module, is inherently included in
the interpreter.

A module is a file containing Python code, definitions of functions,


statements, or classes. An example_module.py file is a module we will
create and whose name is example_module.

We employ modules to divide complicated programs into smaller, more


understandable pieces. Modules also allow for the reuse of code.

Rather than duplicating their definitions into several applications, we may


define our most frequently used functions in a separate module and then
import the complete module.

Let's construct a module. Save the file as example_module.py after


entering the following.

Example:

1. # Here, we are creating a simple Python program to show how to cr


eate a module.
2. # defining a function in the module to reuse it
3. def square( number ):
4. # here, the above function will square the number passed as the input
5. result = number ** 2
6. return result # here, we are returning the result of the function

Here, a module called example_module contains the definition of the


function square(). The function returns the square of a given number.
How to Import Modules in Python?
In Python, we may import functions from one module into our program, or
as we say into, another module.

For this, we make use of the import Python keyword. In the Python
window, we add the next to import keyword, the name of the module we
need to import. We will import the module we defined earlier
example_module.

Syntax:

1. import example_module

The functions that we defined in the example_module are not immediately


imported into the present program. Only the name of the module, i.e.,
example_ module, is imported here.

We may use the dot operator to use the functions using the module name.
For instance:

Example:

1. # here, we are calling the module square method and passing the v
alue 4
2. result = example_module.square( 4 )
3. print("By using the module square of number is: ", result )

Output:

By using the module square of number is: 16

There are several standard modules for Python. The complete list of
Python standard modules is available. The list can be seen using the help
command.

Similar to how we imported our module, a user-defined module, we can


use an import statement to import other standard modules.

Importing a module can be done in a variety of ways. Below is a list of


them.

Python import Statement


Using the import Python keyword and the dot operator, we may import a
standard module and can access the defined functions within it. Here's an
illustration.
Code

1. # Here, we are creating a simple Python program to show how to im


port a standard module
2. # Here, we are import the math module which is a standard module
3. import math
4. print( "The value of euler's number is", math.e )
5. # here, we are printing the euler's number from the math module

Output:

The value of euler's number is 2.718281828459045

Importing and also Renaming


While importing a module, we can change its name too. Here is an
example to show.

Code

1. # Here, we are creating a simple Python program to show how to im


port a module and rename it
2. # Here, we are import the math module and give a different name to it
3. import math as mt # here, we are importing the math module as
mt
4. print( "The value of euler's number is", mt.e )
5. # here, we are printing the euler's number from the math module

Output:

The value of euler's number is 2.718281828459045

The math module is now named mt in this program. In some situations, it


might help us type faster in case of modules having long names.

Please take note that now the scope of our program does not include the
term math. Thus, mt.pi is the proper implementation of the module,
whereas math.pi is invalid.

Python from...import Statement


We can import specific names from a module without importing the
module as a whole. Here is an example.

Code
1. # Here, we are creating a simple Python program to show how to im
port specific
2. # objects from a module
3. # Here, we are import euler's number from the math module using t
he from keyword
4. from math import e
5. # here, the e value represents the euler's number
6. print( "The value of euler's number is", e )

Output:

The value of euler's number is 2.718281828459045

Only the e constant from the math module was imported in this case.

We avoid using the dot (.) operator in these scenarios. As follows, we may
import many attributes at the same time:

Code

1. # Here, we are creating a simple Python program to show how to im


port multiple
2. # objects from a module
3. from math import e, tau
4. print( "The value of tau constant is: ", tau )
5. print( "The value of the euler's number is: ", e )

Output:

The value of tau constant is: 6.283185307179586


The value of the euler's number is: 2.718281828459045
Import all Names - From import * Statement

To import all the objects from a module within the present namespace,
use the * symbol and the from and import keyword.

Syntax:

1. from name_of_module import *

There are benefits and drawbacks to using the symbol *. It is not advised
to use * unless we are certain of our particular requirements from the
module; otherwise, do so.

Here is an example of the same.


Code

1. # Here, we are importing the complete math module using *


2. from math import *
3. # Here, we are accessing functions of math module without using th
e dot operator
4. print( "Calculating square root: ", sqrt(25) )
5. # here, we are getting the sqrt method and finding the square root
of 25
6. print( "Calculating tangent of an angle: ", tan(pi/6) )
7. # here pi is also imported from the math module

Output:

Calculating square root: 5.0


Calculating tangent of an angle: 0.5773502691896257

Locating Path of Modules

The interpreter searches numerous places when importing a module in


the Python program. Several directories are searched if the built-in
module is not present. The list of directories can be accessed using
sys.path. The Python interpreter looks for the module in the way
described below:

The module is initially looked for in the current working directory. Python
then explores every directory in the shell parameter PYTHONPATH if the
module cannot be located in the current directory. A list of folders makes
up the environment variable known as PYTHONPATH. Python examines
the installation-dependent set of folders set up when Python is
downloaded if that also fails.

Here is an example to print the path.

Code

1. # Here, we are importing the sys module


2. import sys
3. # Here, we are printing the path using sys.path
4. print("Path of the sys module in the system is:", sys.path)

Output:

Path of the sys module in the system is:


['/home/pyodide', '/home/pyodide/lib/Python310.zip', '/lib/Python3.10',
'/lib/Python3.10/lib-dynload', '', '/lib/Python3.10/site-packages']
The dir() Built-in Function

We may use the dir() method to identify names declared within a module.

For instance, we have the following names in the standard module str. To
print the names, we will use the dir() method in the following way:

Code

1. # Here, we are creating a simple Python program to print the direct


ory of a module
2. print( "List of functions:\n ", dir( str ), end=", " )

Output:

List of functions:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__for

Python sys Module





The sys module in Python provides various functions and variables
that are used to manipulate different parts of the Python runtime
environment. It allows operating on the interpreter as it provides
access to the variables and functions that interact strongly with the
interpreter. Let’s consider the below example.
Sys Module in Python
Python sys.version
In this example, sys.version is used which returns a string
containing the version of Python Interpreter with some additional
information. This shows how the sys module interacts with the
interpreter. Let us dive into the article to get more information about
the sys module.
 Python3
import sys

print(sys.version)

Output:
3.6.9 (default, Oct 8 2020, 12:12:24)
[GCC 8.4.0]
Input and Output using Python Sys
The sys modules provide variables for better control over input or
output. We can even redirect the input and output to other devices.
This can be done using three variables –
 stdin
 stdout
 stderr
Read from stdin in Python
stdin: It can be used to get input from the command line directly. It
is used for standard input. It internally calls the input() method. It,
also, automatically adds ‘\n’ after each sentence.
Example:
This code reads lines from the standard input until the user
enters ‘q’. For each line, it prints “Input : ” followed by the line.
Finally, it prints “Exit”.
import sys

for line in sys.stdin:

if 'q' == line.rstrip():

break

print(f'Input : {line}')

print("Exit")

Output:

Python Math Module




Sometimes when working on some kind of financial or scientific
project it becomes necessary to implement mathematical
calculations in the project. Python provides the math module to
deal with such calculations. The math module provides the Python
math functions to deal with basic operations such as addition(+),
subtraction(-), multiplication(*), division(/) and advanced operations
like trigonometric, logarithmic, and exponential functions.
In this article, we learn about the math module from basics to
advanced using the help of a huge dataset containing functions
explained with the help of good examples.
Math Module in Python
The Python math module provides various values of
various constants like pi, and tau. Having such constants saves the
time of writing the value of each constant every time we want to use
it and that too with great precision. The constants provided by the
math module are –
 Euler’s Number
 Pi
 Tau
 Infinity
 Not a Number (NaN)
Let’s see each constant in detail.
Euler’s Number in Python
The math.e constant returns the Euler’s number: 2.71828182846.
Syntax:
math.e
Example: This code imports the math module and then prints the
value of the mathematical constant e.

import math

print (math.e)

Output:
2.718281828459045

Pi in Python
You all must be familiar with pi. The pi is depicted as either 22/7 or
3.14. math.pi provides a more precise value for the pi.
Syntax of Python math PI
math.pi
Example 1: This code imports the math module and then prints the
value of the mathematical constant pi.

import math

print (math.pi)

Output:
3.141592653589793
Example 2: Let’s find the area of the circle
The code utilizes the math module in Python, defines a radius and the
mathematical constant pi, and calculates the area of a circle using
the formula‘ A = pi * r * r'. It demonstrates the application of
mathematical concepts and the usage of the math module for
numerical calculations
import math

r = 4

pie = math.pi

print(pie * r * r)

Output:
50.26548245743669
Finding the factorial of the number
Using the factorial() function we can find the factorial of a number
in a single line of the code. An error message is displayed if number
is not integral.
Example: This code imports the math module, assigns the value 5
to the variable a, and then calculates and prints the factorial of a.

import math

a = 5

print("The factorial of 5 is : ", end="")

print(math.factorial(a))

Output:
The factorial of 5 is : 120
Python Time Module

We can always use Python's built-in time module whenever dealing with
time-related tasks. There are several ways to represent time in code,
including numbers, strings, and objects, thanks to this built-in module. It
also has additional features like the ability to get the current time, wait
until the code executes, pause programme execution, and measure the
code's effectiveness.

We will go in-depth on how to work with dates and times, as well as how
to represent time with floats, tuples, and struct_time. We will also learn
how to convert between various time representations and comprehend
suspend thread execution.
Python's time module is a very practical tool for manipulating functions
and objects that deal with time. Therefore, we must first import the
module in order to begin using the time module in Python.

Python's time module offers functions for dealing with time-related tasks.

Among the time-related tasks are,reading the current time, formatting the
time, dozing off for a predetermined period of time, and so forth.

Adding the time module

Since it is a part of Python's standard utility module, there is no need to


install the time module separately.

1. import time
What is an epoch?
The epoch, which varies depending on the platform, is the moment when
time begins. The epoch is January 1, 1970, 00:00:00 (UTC) on Windows
and most Unix systems, and leap seconds are not included in the
calculation of the number of seconds that have passed since the epoch.
We can use time to find out what the epoch is on a particular
platform.gmtime(0).

Python Time in Floating Number(Seconds)The first value returned by


the time.time() function is the duration in seconds since the epoch. This
function returns a floating data type for the time in order to handle
fractional seconds.

Code

1. # Import time module


2.
3. from time import time
4. print(time())

Output:

1659877305.6220002

On your machine, the reference point used to calculate the epoch might
differ significantly. Therefore might receive a different output.

To do this, pass the time.ctime() function the number of seconds returned


by the time() function.
Time in seconds can be entered into the time.ctime() function of the time
module, which will then calculate time up to those seconds and return a
24-character time string object. If there is no disagreement, time is
calculated up until the current moment.

Code

1. # Import time module


2.
3. import time
4.
5. current = time.ctime(2649877305.6210002)
6. print("Current time: ", current)

Output:

Current time: Wed June 7 08:21:45 2023


Python dir() Function

Python dir() function returns the list of names in the current local scope. If
the object on which method is called has a method named __dir__(), this
method will be called and must return the list of attributes. It takes a
single object type argument. The signature of the function is given below.

Signature

1. dir ([object])

Parameters

object: It takes an optional parameter.

Return

It returns a list of valid attributes of the object.

Let's see some examples of dir() function to understand it's functionality.

Python dir() Function Example 1

Let's create a simple example to get a list of valid attributes. It takes a


single parameter which is optional.

1. # Python dir() function example


2. # Calling function
3. att = dir()
4. # Displaying result
5. print(att)

Output:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__',


'__loader__', '__name__', '__package__',
'__spec__']

Parameters of dir() in Python


The dir function in python takes only one parameter:

 object(optional): i.e. we are not required to pass any parameters to know all the defined
names in the namespace. However, to know the attributes / properties of a particular object
you must pass it as a parameter.

This object could be a function, or a module, lists, strings or even dictionaries etc.

Return Values of dir() in Python


dir() in Python returns all the defined names in a namespace as a list. For different python
objects, the dir function in Python gives different results.

 If the input object is a class, a list of names containing all the valid attributes along with base
attributes is returned.
 If the input object are modules or library objects, the list of names of all attributes that are
contained in that module is returned.
 However, if no parameters are given to the function, it simply returns all the names in the
current local scope, of course in the form of a list.

What is the dir() function in Python?


The dir() function in python is one of the very powerful built-in functions. It is essentially
short for "directory", which does exactly as its name, provides us with all the names in the
current local scope in the form of a list.

Applications of dir() in Python

The dir() function in python is usually used for debugging purposes, in day to day
programming. The functionality of being able to return all attributes of the object passed to it
as a parameter in a list is useful when dealing with a plethora of classes and functions.

This function is also particularly helpful when you're working with a new module that you
created, or even an existing one and would like to know about all the available attributes and
functions. For example, you are working on mathematical equations and might want to know
if the 'math' module that you are working with, contains a function to calculate the gcd
(greatest common divisor) of two numbers. You can simply call the dir() in python and list
out all the available functions in the current namespace of the module as well as the inbuilt
functions.

Python Exceptions

When a Python program meets an error, it stops the execution of the rest
of the program. An error in Python might be either an error in the syntax
of an expression or a Python exception. We will see what an exception is.
Also, we will see the difference between a syntax error and an exception
in this tutorial. Following that, we will learn about trying and except blocks
and how to raise exceptions and make assertions. After that, we will see
the Python exceptions list.

What is an Exception?
An exception in Python is an incident that happens while executing a
program that causes the regular course of the program's commands to be
disrupted. When a Python code comes across a condition it can't handle, it
raises an exception. An object in Python that describes an error is called
an exception.

When a Python code throws an exception, it has two options: handle the
exception immediately or stop and quit.

Exceptions versus Syntax Errors


When the interpreter identifies a statement that has an error, syntax
errors occur. Consider the following scenario:

Code

1. #Python code after removing the syntax error


2. string = "Python Exceptions"
3.
4. for s in string:
5. if (s != o:
6. print( s )

Output:

if (s != o:
^
SyntaxError: invalid syntax
Try and Except Statement - Catching Exceptions
In Python, we catch exceptions and handle them using try and except
code blocks. The try clause contains the code that can raise an exception,
while the except clause contains the code lines that handle the exception.
Let's see if we can access the index from the array, which is more than
the array's length, and handle the resulting exception.

Code

1. # Python code to catch an exception and handle it using try and exc
ept code blocks
2.
3. a = ["Python", "Exceptions", "try and except"]
4. try:
5. #looping through the elements of the array a, choosing a range t
hat goes beyond the length of the array
6. for i in range( 4 ):
7. print( "The index and element from the array is", i, a[i] )
8. #if an error occurs in the try block, then except block will be execut
ed by the Python interpreter
9. except:
10. print ("Index out of range")

Output:

The index and element from the array is 0 Python


The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range

The code blocks that potentially produce an error are inserted inside the
try clause in the preceding example. The value of i greater than 2
attempts to access the list's item beyond its length, which is not present,
resulting in an exception. The except clause then catches this exception
and executes code without stopping it.

How to Raise an Exception


If a condition does not meet our criteria but is correct according to the
Python interpreter, we can intentionally raise an exception using the raise
keyword. We can use a customized exception in conjunction with the
statement.
If we wish to use raise to generate an exception when a given condition
happens, we may do so as follows:

Code

1. #Python code to show how to raise an exception in Python


2. num = [3, 4, 5, 7]
3. if len(num) > 3:
4. raise Exception( f"Length of the given list must be less than or eq
ual to 3 but is {len(num)}" )

Output:

1 num = [3, 4, 5, 7]
2 if len(num) > 3:
----> 3 raise Exception( f"Length of the given list must be less than
or equal to 3 but is {len(num)}" )

Exception: Length of the given list must be less than or equal to 3 but is
4

You might also like