Python Notes
Python Notes
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.
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:
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:
The self-parameter
_ _init_ _ method
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.
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:
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.
o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Class
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.
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
Inheritance
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.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many,
and morph means shape. By polymorphism, we understand that one task
can be performed in different ways. For example - you have a class
animal, and all animals speak. But they speak differently. Here, the
"speak" behavior is polymorphic in a sense and depends on the animal.
So, the abstract "animal" concept does not actually "speak", but specific
animals (like dogs and cats) have a concrete implementation of the action
"speak".
Encapsulation
Data Abstraction
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.
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.
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:
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:
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:
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:
Explanation -
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.
Important Notes
File Organizer: Write a Python program that organizes the file in a directory based on the extension
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.
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.
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:
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
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
Variables at the class level are known as class variables, whereas variables at
the instance level are known as instance 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.
Syntax:
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
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
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 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 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.
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() 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.
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.
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:
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
Output
5
3
Examples of user-defined polymorphic functions:
Python3
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Output
5
9
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.
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.
Python3
def func(obj):
obj.capital()
obj.language()
obj.type()
obj_ind = India()
obj_usa = USA()
func(obj_ind)
func(obj_usa)
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!"
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.
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.
Code
1.
2. # Python type() function when single argument is passed
3. my_word = " Javatpoint "
4. print(type(my_word))
Output:
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.
Code
1.
2. # Python type() function when three arguments are passed
3. BaseClass = type(' BaseClass ', (), { 'a' : 100})
4. print(type(BaseClass))
Output:
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' >.
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:
class CustomError(Exception):
...
pass
try:
...
except CustomError:
...
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
Enter a number: 14
Exception occurred: Invalid Age
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
def fun():
print("Welcome to GFG")
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")
fun()
Output:
Welcome to GFG
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:
return num3
# Driver code
num1, num2 = 5, 15
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
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(3)
Output:
even
odd
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
print("x: ", x)
print("y: ", y)
# 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.
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("Case-1:")
nameAge("Suraj", 27)
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
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
def myFun(*argv):
print(arg)
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):
# Driver code
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
def evenOdd(x):
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
Python3
# Python program to
# demonstrate accessing of
def f1():
def f2():
print(s)
f2()
# Driver's code
f1()
Output:
I love GeeksforGeeks
print(cube(7))
print(cube_v2(7))
Output:
343
343
return num**2
print(square_value(2))
print(square_value(-4))
Output:
4
16
Python3
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20
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):
# to x.
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
# to x.
x = 20
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
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
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
print(func(2, 2))
Output:
4
1099
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.
*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
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
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
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
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
python3
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
Output:
args: ('geeks', 'for', 'geeks')
kwargs: {'first': 'Geeks', 'mid': 'for', 'last': 'Geeks'}
Python Scope
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
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 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:
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
Output:
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:
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
Output:
Code
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:
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.
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
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
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.
1. def my_function(fname):
2. print(fname + " Id")
3. my_function("Emil")
4. my_function("Phone")
Email Id
Phone Id
1. def shout(text):
2. return text.upper()
3. print(shout('Hello World'))
4. yell = shout
5. print(yell('Hello Coders'))
HELLO WORLD
HELLO CODERS
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()
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 -
In this article, we will learn the uses of the map function in Python.
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.
# input list
inputList = [3, 5, 1, 6, 10]
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 −
# input Dictionary
inputDictionary = {2, 3, 4, 5, 6, 7, 8, 9}
Example
The following code converts all the items in a tuple to lowercase using the
lower() and map() functions −
# input tuple
inputTuple = ('HELLO', 'TUTORIALSPOINT', 'pyTHON', 'CODES')
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}"
return y*y*y
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
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.
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]]
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.
Example:
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
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:
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.
Output:
Code
Output:
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.
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:
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
Output:
To import all the objects from a module within the present namespace,
use the * symbol and the from and import keyword.
Syntax:
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.
Output:
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.
Code
Output:
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
Output:
List of functions:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__for
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
if 'q' == line.rstrip():
break
print(f'Input : {line}')
print("Exit")
Output:
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(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.
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).
Code
Output:
1659877305.6220002
On your machine, the reference point used to calculate the epoch might
differ significantly. Therefore might receive a different output.
Code
Output:
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
Return
Output:
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.
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.
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.
Code
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 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.
Code
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