Python Tutorial - GeeksforGeeks

06 Jul, 2022
Python is a high-level programming language and is widely being used among the developers’ community. Python was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets developers work quickly and integrate systems more efficiently. This Python tutorial provides learners (either beginner or experienced developer) with the topics from Python basics to advanced topics with examples.
Topics:
Key features and applications
Download and installation
How to run a Python program
Fundamentals of PythonIndentationCommentsVariablesOperators
Indentation
Comments
Variables
Operators
Basics of Input/Output
Data typesNumericStringListTupleBooleanSetDictionary
Numeric
String
List
Tuple
Boolean
Set
Dictionary
Decision making
Control flow (Loops)While and while-else loopFor and for-else looprange() function
While and while-else loop
For and for-else loop
range() function
Loop control statementsBreakContinuepass
Break
Continue
pass
FunctionsFunction with argumentsLambda functions
Function with arguments
Lambda functions
OOPS conceptClass and ObjectsConstructors and DestructorsInheritanceEncapsulationPolymorphism
Class and Objects
Constructors and Destructors
Inheritance
Encapsulation
Polymorphism
File Handling
Modules and Packages
Regular expressions
Exception handling
 
Python has many reasons for being popular and in demand. A few of the reasons are mentioned below.
Emphasis on code readability, shorter codes, ease of writing.
Programmers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.
Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.
It provides extensive support libraries(Django for web development, Pandas for data analytics etc)
Dynamically typed language(Data type is based on value assigned)
Philosophy is “Simplicity is the best”.
Python is a lot easier to code and learn. Python programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Python codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Python Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below:
Windows don’t come with Python preinstalled, it needs to be installed explicitly. But unlike windows, most of the Linux OS have Python pre-installed, also macOS comes with Python pre-installed.To check if your device is pre-installed with Python or not, just go to Command Line(For Windows, search for cmd in the Run dialog( + R), for Linux open the terminal using Ctrl+Alt+T, for macOS use control+Option+Shift+T.
Now run the following command:For Python2
python --version

For Python3
python3 --version

If Python is already installed, it will generate a message with the Python version available.
Before starting with the installation process, you need to download it. For that all versions of Python for Windows, Linux, and MacOS are available on python.org.
Windows
Linux
MacOS
Download the Python and follow the further instructions for the installation of Python.
Beginning the installation.
Windows
Linux
MacOS
Run the Python Installer from downloads folder. Make sure to mark Add Python 3.7 to PATH otherwise you will have to do it explicitly.It will start installing python on windows.
After installation is complete click on Close.Bingo..!! Python is installed. Now go to windows and type IDLE.
For almost every Linux system, the following commands would work definitely.
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update
$ sudo apt-get install python3.8

To verify the installation enter following commands in your Terminal.
python3

Download and install Homebrew Package ManagerEnter following command in macOS terminal./usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Enter system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS.
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Enter system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS.
Install Python Latest Version on macOS / macOS XOpen Terminal and enter the following command.brew install python3
After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal apppythona fa-hand-o-right
pip3

Open Terminal and enter the following command.
brew install python3

After command processing is complete, Python’s version 3 would be installed on your mac.
To verify the installation enter following commands in your Terminal app
pythona fa-hand-o-right

pip3

Let’s consider a simple Hello World Program.
Generally, there are two ways to run a Python program.
Using IDEs: You can use various IDEs(Pycharm, Jupyter Notebook, etc.) which can be used to run Python programs.
Using Command-Line: You can also use command line options to run a Python program. Below steps demonstrate how to run a Python program on Command line in Windows/Unix Operating System:
Open Commandline and then to compile the code type python HelloWorld.py. If your code has no error then it will execute properly and output will be displayed.
Open Terminal of your Unix/Linux OS and then to compile the code type python HelloWorld.py. If your code has no error then it will execute properly and output will be displayed.
Python uses indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right. You can understand it better by looking at the following lines of code.
Output:
Logging on to geeksforgeeks...
All set !

The lines print(‘Logging on to geeksforgeeks...’) and print(‘retype the URL.’) are two separate code blocks. The two blocks of code in our example if-statement are both indented four spaces. The final print(‘All set!’) is not indented, and so it does not belong to the else-block.
Note: For more information, refer  Indentation in Python.
Comments are useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. There are two types of comment in Python:
Single line comments: Python single line comment starts with hashtag symbol with no white spaces.# This is a comment # Print “GeeksforGeeks !” to console print("GeeksforGeeks") Run on IDE
Multi-line string as comment: Python multi-line comment is a piece of text enclosed in a delimiter (“””) on each end of the comment.""" This would be a multiline comment in Python that spans several lines and describes geeksforgeeks. A Computer Science portal for geeks. It contains  well written, well thought  and well-explained computer science  and programming articles,  quizzes and more.  ... """print("GeeksForGeeks") Run on IDE
Note: For more information, refer  Comments in Python.
Variables in Python are not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it.
Output:
45
1456.8
John

Note: For more information, refer  Python Variables.
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. These operators can be categorized based upon their different functionality:
Arithmetic operators: Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division.# Examples of Arithmetic Operator a = 9b = 4   # Addition of numbers add = a + b # Subtraction of numbers  sub = a - b # Multiplication of number  mul = a * b # Division(float) of number  div1 = a / b # Division(floor) of number  div2 = a // b # Modulo of both number mod = a % b    # print results print(add) print(sub) print(mul) print(div1) print(div2) print(mod)Run on IDEOutput:13
5
36
2.25
2
1

Output:
13
5
36
2.25
2
1

Relational Operators: Relational operators compares the values. It either returns True or False according to the condition.# Examples of Relational Operators a = 13b = 33   # a > b is False print(a > b)    # a < b is True print(a < b)    # a == b is False print(a == b)    # a != b is True print(a != b)    # a >= b is False print(a >= b)    # a <= b is True print(a <= b)Run on IDEOutput:False
True
False
True
False
True

Output:
False
True
False
True
False
True

Logical Operators: Logical operators perform Logical AND, Logical OR and Logical NOT operations.# Examples of Logical Operator a = Trueb = False   # Print a and b is False print(a and b)    # Print a or b is True print(a or b)    # Print not a is False print(not a) Run on IDEOutput:False
True
False

Output:
False
True
False

Bitwise operators: Bitwise operator acts on bits and performs bit by bit operation.# Examples of Bitwise operators a = 10b = 4   # Print bitwise AND operation   print(a & b)    # Print bitwise OR operation print(a | b)    # Print bitwise NOT operation  print(~a)    # print bitwise XOR operation  print(a ^ b)    # print bitwise right shift operation  print(a >> 2)    # print bitwise left shift operation  print(a << 2)Run on IDEOutput:0
14
-11
14
2
40

Output:
0
14
-11
14
2
40

Assignment operators: Assignment operators are used to assign values to the variables.
Special operators: Special operators are of two types-Identity operator that contains is and is not.Membership operator that contains in and not in.# Examples of Identity and # Membership operator  a1 = 'GeeksforGeeks'b1 = 'GeeksforGeeks' # Identity operatorprint(a1 is not b1)print(a1 is b1) # Membership operatorprint("G" in a1)print("N" not in b1)Run on IDEOutput:False
True
True
True

Identity operator that contains is and is not.
Membership operator that contains in and not in.
Output:
False
True
True
True

Note: For more information, refer  Basic Operators in Python.
Python provides us with two inbuilt functions to read the input from the keyboard.
raw_input(): This function works in older version (like Python 2.x). This function takes exactly what is typed from the keyboard, convert it to string and then return it to the variable in which we want to store. For example:# Python program showing  # a use of raw_input()    g = raw_input("Enter your name : ") print g Run on IDE
input(): This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether the user entered a string or a number or list. For example:# Python program showing  # a use of input()    val = input("Enter your value: ") print(val)Run on IDE
Note: For more information, refer  Python input() and raw_input().
The simplest way to produce output is using the print() function where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string before writing to the screen.
Output:
GeeksForGeeks
x = 5
GFG
Python@GeeksforGeeks

Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
In Python, numeric data type represent the data which has numeric value. Numeric value can be interger, floating number or even complex numbers. These values are defined as int, float and complex class in Python.
Output:
Type of a:  <class 'int'>

Type of b:  <class 'float'>

Type of c:  <class 'complex'>

In Python, a sequence is the ordered collection of similar or different data types. Sequences allow storing multiple values in an organized and efficient fashion. There are several sequence types in Python –
String
List
Tuple
1) String: A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class. Strings in Python can be created using single quotes or double quotes or even triple quotes.
Output:
Welcome to the Geeks World
I'm a Geek
I'm a Geek and I live in a world of "Geeks"

Accessing elements of string –
Output:
G
s

Deleting/Updating from a String –
In Python, Updation or deletion of characters from a String is not allowed because Strings are immutable. Only new strings can be reassigned to the same name.
Output:
Traceback (most recent call last):
File “/home/360bb1830c83a918fc78aa8979195653.py”, line 6, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment

Traceback (most recent call last):
File “/home/499e96a61e19944e7e45b7a6e1276742.py”, line 8, in
del String1[2]
TypeError: ‘str’ object doesn’t support item deletion

Note: For more information, refer  Python String.
Refer to the below articles to know more about Strings:
String Slicing in Python
Python String Concatenation
Python String Interpolation
Python programming questions on String
2) List: Lists are just like the arrays, declared in other languages. A single list may contain DataTypes like Integers, Strings, as well as Objects. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. It is represented by list class.
Output:
[]
['GeeksForGeeks', 'Geeks']
[['Geeks', 'For'], ['Geeks']]

Adding Elements to a List: Using append(), insert() and extend()
Output:
[1, 2]
['Geeks', 1, 2, 12]
['Geeks', 1, 2, 12, 8, 'Geeks', 'Always']

Accessing elements from the List –
Use the index operator [ ] to access an item in a list. In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Output:
1
3
6
4

Removing Elements from the List: Using remove() and pop()
Output:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
[1, 2, 3, 4, 7, 8, 9, 10, 11]

Note: For more information, refer  Python List.
Refer to the below articles to know more about List:
Iterate over a list in Python
Python List Comprehension and Slicing
Python programming questions on List
3) Tuple: Tuple is an ordered collection of Python objects much like a list. The important difference between a list and a tuple is that tuples are immutable. It is represented by tuple class. In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence.
Output:
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
((0, 1, 2, 3), ('python', 'geek'))

Accessing element of a tuple –
Use the index operator [ ] to access an item in a tuple.
Output:
1
5

Deleting/updating elements of tuple –
Items of a tuple cannot be deleted as tuples are immutable in Python. Only new tuples can be reassigned to the same name.
Output:
Traceback (most recent call last):
  File "/home/084519a8889e9b0103b874bbbb93e1fb.py", line 11, in 
    tuple1[0] = -1
TypeError: 'tuple' object does not support item assignment

Traceback (most recent call last):
  File "/home/ffb3f8be85dd393bde5d0483ff191343.py", line 12, in 
    del tuple1[2]
TypeError: 'tuple' object doesn't support item deletion

Note: For more information, refer  Python Tuples.
Refer to the below articles to know more about tuples:
Unpacking a Tuple in Python
Operations on Tuples
Python programming questions on Tuples
Booleans are data type with one of the two built-in values, True or False. It is denoted by the class bool.
Output:
<class 'bool'>
False
True

In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces {}, separated by ‘comma’.
Output:
{'o', 'r', 'k', 'G', 'e', 's', 'F'}
{'Geeks', 'For'}

Adding elements: Using add() and update()
Output:
{8, (6, 7)}
{8, 10, 11, (6, 7)}

Accessing a Set: One can loop through the set items using a for loop as set items cannot be accessed by referring to an index.
Output:
Geeks For

Removing elements from a set: Using remove(), discard(), pop() and clear()
Output:
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}
{1, 2, 3, 4, 7, 10, 11, 12}
{2, 3, 4, 7, 10, 11, 12}
set()

Note: For more information, refer  Python Sets.
Refer to the below articles to know more about Sets:
Iterate over a set in Python
frozenset() in Python
Python programming questions on Sets
Dictionary in Python is an unordered collection of data values, used to store data values like a map. Dictionary holds key:value pair. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’. A Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’.
Output:
{}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Nested Dictionary:
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

Note: For more information, refer  Python Nested Dictionary.
Adding elements to a Dictionary: One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Output:
{0: 'Geeks', 2: 'For', 3: 1}
{0: 'Geeks', 2: 'Welcome', 3: 1}

Accessing elements from a Dictionary: In order to access the items of a dictionary refer to its key name or use get() method.
Output:
For
Geeks

Removing Elements from Dictionary: Using pop() and popitem()
Output:
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 6: 'To', 7: 'Geeks'}
{6: 'To', 7: 'Geeks'}

Note: For more information, refer  Python Dictionary.
Refer to the below articles to know more about dictionary:
Operations on Dictionary
Iterate over a dictionary in Python
Python programming questions on dictionary
Decision Making in programming is similar to decision making in real life. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.
Decision-making statements in Python
if statement
if..else statements
nested if statements
if-elif ladder
Example 1: To demonstrate if and if-else
Output:
Even Number
Odd Number

Example 2: To demonstrate nested-if and if-elif
Output:
Number is divisible by both 2 and 5
a is 10

Note: For more information, refer  Decision Making in Python.
Loops in programming come into use when we need to repeatedly execute a block of statements. For example: Suppose we want to print “Hello World” 10 times. This can be done with the help of loops. The loops in Python are:
While and while-else loop# Python program to illustrate  # while and while-else loopi = 0while (i < 3):          i = i + 1    print("Hello Geek")     # checks if list still # contains any element  a = [1, 2, 3, 4] while a:     print(a.pop())    i = 10while i < 12:      i += 1    print(i)      breakelse: # Not executed as there is a break      print("No Break") Run on IDEOutput:Hello Geek
Hello Geek
Hello Geek
4
3
2
1
11
Note: For more information, refer  Python While Loops.
Output:
Hello Geek
Hello Geek
Hello Geek
4
3
2
1
11

Note: For more information, refer  Python While Loops.
For and for-else loop# Python program to illustrate  # Iterating over a list  print("List Iteration")  l = ["geeks", "for", "geeks"]  for i in l:      print(i)      # Iterating over a String  print("\nString Iteration")      s = "Geeks"for i in s :      print(i)       print("\nFor-else loop")for i in s:      print(i)  else: # Executed because no break in for      print("No Break\n")     for i in s:      print(i)      breakelse: # Not executed as there is a break      print("No Break")  Run on IDEOutput:List Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

For-else loop
G
e
e
k
s
No Break

G
Note: For more information, refer  Python For Loops.
Output:
List Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

For-else loop
G
e
e
k
s
No Break

G

Note: For more information, refer  Python For Loops.
range() function: range() allows user to generate a series of numbers within a given range. Depending on how many arguments user is passing to the function. This function takes three arguments.1) start: integer starting from which the sequence of integers is to be returned2) stop: integer before which the sequence of integers is to be returned.3) step: integer value which determines the increment between each integer in the sequencefilter_none# Python program to demonstrate# range() function    for i in range(5):     print(i, end =" ") print() for i in range(2, 9):     print(i, end =" ") print() # incremented by 3 for i in range(15, 25, 3):     print(i, end =" ") Run on IDEOutput:0 1 2 3 4 
2 3 4 5 6 7 8 
15 18 21 24 
Note: For more information, refer  Python range() function.
1) start: integer starting from which the sequence of integers is to be returned2) stop: integer before which the sequence of integers is to be returned.3) step: integer value which determines the increment between each integer in the sequencefilter_none
Output:
0 1 2 3 4 
2 3 4 5 6 7 8 
15 18 21 24 

Note: For more information, refer  Python range() function.
Refer to the below articles to know more about Loops:
Understanding for-loop in Python
Backward iteration in Python
Loop control statements change execution from its normal sequence. Following are the loop control statements provided by Python:
Break: Break statement in Python is used to bring the control out of the loop when some external condition is triggered.
Continue: Continue statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
Pass: Pass statement is used to write empty loops. Pass is also used for empty control statement, function and classes.
Output:
g 
g k f o r g k 
g e e k s f o r g e e k s 

Note: For more information, refer  break, continue and pass in Python.
Functions are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, provides better readability of the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. A function can also perform some specific task without returning anything. In Python, def keyword is used to create functions.
Output:
Hello Geeks
55

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.# Python program to demonstrate # default arguments   def myFun(x, y = 50):     print("x: ", x)     print("y: ", y)    # Driver codemyFun(10)Run on IDEOutput:('x: ', 10)
('y: ', 50)

Output:
('x: ', 10)
('y: ', 50)

Keyword arguments: The idea is to allow caller to specify argument name with values so that caller does not need to remember 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') Run on IDEOutput:('Geeks', 'Practice')
('Geeks', 'Practice')

Output:
('Geeks', 'Practice')
('Geeks', 'Practice')

Variable length arguments: In Python a function can also have variable number of arguments. This can be used in the case when we do not know in advance the number of arguments that will be passed into a function.# Python program to demonstrate# variable length arguments  # variable argumentsdef myFun1(*argv):      for arg in argv:          print(arg, end =" ")          # variable keyword argumentsdef myFun2(**kwargs):    for key, value in kwargs.items():         print ("% s == % s" %(key, value))    # Driver code myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks')print()myFun2(first ='Geeks', mid ='for', last ='Geeks')Run on IDEOutput:Hello Welcome to GeeksforGeeks 
first == Geeks
last == Geeks
mid == for

Output:
Hello Welcome to GeeksforGeeks 
first == Geeks
last == Geeks
mid == for

Note: For more information, refer  Functions in Python.
Refer to the below articles to know more about functions:
Python Inner Functions
Python return statement
Call function from another function
In Python, the lambda/anonymous function means that a function is without a name. The lambda keyword is used to create anonymous functions. Lambda function can have any number of arguments but has only one expression.
Output:
343
[0, 2, 4, 6, 8]

Note: For more information, refer  Python lambda (Anonymous Functions).
Refer to the below articles to know more about Lambda:
Python programming questions on Lambda
Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.
Class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values.
Output:
mamal
I'm a mamal
I'm a dog

Note: For more information, refer  Python Classes and Objects.
The self
self represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
Note: For more information, refer  self in Python class.
Constructors: Constructors are generally used for instantiating an object.The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. In Python the __init__() method is called the constructor and is always called when an object is created. There can be two types of constructors:
Default constructor: The constructor which is called implicilty and do not accept any argument.
Parameterized constructor:Constructor which is called explicitly with parameters is known as parameterized constructor.
Output:
3000

Note: For more information, refer  Constructors in Python.
Destructors: Destructors are called when an object gets destroyed. The __del__() method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected.
Output:
Employee created.
Destructor called, Employee deleted.

Note: For more information, refer  Destructors in Python.
Inheritance is the ability of any class to extract and use features of other classes. It is the process by which new classes called the derived classes are created from existing classes called Base classes.
Output:
Geek1 False
Geek2 True

Note: For more information, refer  Python inheritance.
Encapsulation describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data.
Output:
Traceback (most recent call last):
  File "/home/5a605c59b5b88751d2b93dd5f932dbd5.py", line 20, in 
    obj = Derived()
  File "/home/5a605c59b5b88751d2b93dd5f932dbd5.py", line 18, in __init__
    print(self.__a) 
AttributeError: 'Derived' object has no attribute '_Derived__a'

Note: For more information, refer  Encapsulation in Python.
Polymorphism refers to the ability of OOPs programming languages to differentiate between entities with the same name efficiently. This is done by Python with the help of the signature of these entities.
Output:
Inside A
Inside B

Refer to the articles to know more about OOPS:
Bound, unbound, and static methods in Python
Multiple inheritance in Python
__new__ in Python
File handling is the ability of Python to handle files i.e. to read and write files along with many other file handling options. Python treats files differently as text or binary and this is important. Each line of code includes a sequence of characters and they form a text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {, } or newline character.
Basic File Handling operations in Python are:
1) Open a file: Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode). Python provides six Access Modes:
Note: For more information, refer  Open a File in Python.
2) Close the file: close() function closes the file and frees the memory space acquired by that file.
3) Reading from a File: There are three ways to read data from a text file.
read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.File_object.read([n])
File_object.read([n])
readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.File_object.readline([n])
File_object.readline([n])
readlines(): Reads all the lines and return them as each line a string element in a list.File_object.readlines()
File_object.readlines()
Let’s suppose the file looks like this:
Output:
Output of Read function is 
Code is like humor. When you have to explain it, its bad.

Output of Readline function is 
Code is like humor. When you have to explain it, its bad.

Output of Readlines function is 
['Code is like humor. When you have to explain it, its bad.']

Note: For more information, refer  How to read from a file in Python.
4) Writing to a file: There are two ways to write in a file.
write(): Inserts the string str1 in a single line in the text file.File_object.write(str1)
File_object.write(str1)
writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3] 
File_object.writelines(L) for L = [str1, str2, str3] 
Output:
Note: For more information, refer  Writing to file in Python.
Refer to the below articles to know more about File-Handling:
Python seek() function
Python tell() function
OS Module in Python
Programs on OS module
A module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, which can be considered as a module named GFG which can be imported with the help of import statement.
Let’s create a simple module named GFG.
To use the above created module, create a new Python file in the same directory and import GFG module using the import statement.
Output:
GeeksforGeeks
Noida
Employee name: Nikhil
Employee position: Developer

Note: For more information, refer  Python Modules.
Packages are a way of structuring many packages and modules which helps in a well-organized hierarchy of data set, making the directories and modules easy to access.
To create a package in Python, we need to follow these three simple steps:
First, we create a directory and give it a package name, preferably related to its operation.
Then we put the classes and the required functions in it.
Finally we create an __init__.py file inside the directory, to let Python know that the directory is a package.
Example: Let’s create a package for cars.
First we create a directory and name it Cars.
Then we need to create modules. We will create 2 modules – BMW and AUDI.For Bmw.py# Python code to illustrate the Modules class Bmw:      def __init__(self):         self.models = ['i8', 'x1', 'x5', 'x6']         def outModels(self):         print('These are the available models for BMW')         for model in self.models:             print('\t % s ' % model)Run on IDEFor Audi.py# Python code to illustrate the Module class Audi:      def __init__(self):         self.models = ['q7', 'a6', 'a8', 'a3']        def outModels(self):         print('These are the available models for Audi')         for model in self.models:             print('\t % s ' % model) Run on IDE
For Bmw.py
For Audi.py
Finally we create the __init__.py file. This file will be placed inside the Cars directory and can be left blank.
Now, let’s use the package that we created. To do this make a sample.py file in the same directory where Cars package is located and add the following code to it:
Output:
Note: For more information, refer  Create and Access a Python Package.
Module Regular Expressions(RE) specifies a set of strings(pattern) that matches it. To understand the RE analogy, MetaCharacters are useful, important and will be used in functions of module re. There are a total of 14 metacharacters:
\   Used to drop the special meaning of character
    following it (discussed below)
[]  Represent a character class
^   Matches the beginning
$   Matches the end
.   Matches any character except newline
?   Matches zero or one occurrence.
|   Means OR (Matches with any of the characters
    separated by it.
*   Any number of occurrences (including 0 occurrences)
+   One ore more occurrences
{}  Indicate the number of occurrences of a preceding RE 
    to match.
()  Enclose a group of REs

The most frequently used methods are:
re.findall(): Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.# A Python program to demonstrate working of # findall() import re       string = """Hello my Number is 123456789 and              my friend's number is 987654321"""   # A sample regular expression to find digits. regex = '\d+'               match = re.findall(regex, string) print(match) Run on IDEOutput:['123456789', '987654321']
In the above example, metacharacter blackslash ‘\’ has a very important role as it signals various sequences. If the blackslash is to be used without its special meaning as metacharacter, use’\\’.\d   Matches any decimal digit, this is equivalent
     to the set class [0-9].
\D   Matches any non-digit character.
\s   Matches any whitespace character.
\S   Matches any non-whitespace character
\w   Matches any alphanumeric character, this is
     equivalent to the class [a-zA-Z0-9_].
\W   Matches any non-alphanumeric character.

Output:
['123456789', '987654321']

In the above example, metacharacter blackslash ‘\’ has a very important role as it signals various sequences. If the blackslash is to be used without its special meaning as metacharacter, use’\\’.
\d   Matches any decimal digit, this is equivalent
     to the set class [0-9].
\D   Matches any non-digit character.
\s   Matches any whitespace character.
\S   Matches any non-whitespace character
\w   Matches any alphanumeric character, this is
     equivalent to the class [a-zA-Z0-9_].
\W   Matches any non-alphanumeric character.

re.compile(): Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions.# A Python program to demonstrate working of # compile() import re    # it is equivalent to [abcde].p = re.compile('[a-e]')  print(p.findall("Aye, said Mr. Gibenson Stark")) Run on IDEOutput:['e', 'a', 'd', 'b', 'e', 'a']

Output:
['e', 'a', 'd', 'b', 'e', 'a']

re.match(): This function attempts to match pattern to whole string. The re.match function returns a match object on success, None on failure.# A Python program to demonstrate working # of re.match(). import re   def findMonthAndDate(string):            regex = r"([a-zA-Z]+) (\d+)"    match = re.match(regex, string)            if match == None:          print("Not a valid date")        return       print("Given Data: % s" % (match.group()))    print("Month: % s" % (match.group(1)))    print("Day: % s" % (match.group(2)))          # Driver Code findMonthAndDate("Jun 24") print("") findMonthAndDate("I was born on June 24") Run on IDEOutput:Given Data: Jun 24
Month: Jun
Day: 24

Not a valid date

Output:
Given Data: Jun 24
Month: Jun
Day: 24

Not a valid date

re.search(): This method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string.# A Python program to demonstrate working of re.match(). import re   regex = r"([a-zA-Z]+) (\d+)"   match = re.search(regex, "I was born on June 24")    if match != None:          print("Match at index % s, % s" % (match.start(), match.end()))       # this will print "June 24"     print("Full match: % s" % (match.group(0)))       # this will print "June"     print("Month: % s" % (match.group(1)))       # this will print "24"     print("Day: % s" % (match.group(2)))    else:     print("The regex pattern does not match.")Run on IDEOutput:Match at index 14, 21
Full match: June 24
Month: June
Day: 24

Output:
Match at index 14, 21
Full match: June 24
Month: June
Day: 24

Note: For more information, refer  Regular Expression in Python.
Like other languages, Python also provides the runtime errors via exception handling method with the help of try-except.
How try-except works?
First try clause is executed i.e. the code between try and except clause.
If there is no exception, then only try clause will run, except clause is finished.
If any exception occurred, try clause will be skipped and except clause will run.
If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception left unhandled, then the execution stops.
A try statement can have more than one except clause.
Code 1: No exception, so try clause will run.
Output:
Yeah ! Your answer is : 1

Code 2: There is an exception so only except clause will run.
Output:
Sorry ! You are dividing by zero 

Else Clause: In python, you can also use else clause on try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.
Output:
Yeah ! Your answer is : 1
No exception raised

Raising Exception: The raise statement allows the programmer to force a specific exception to occur. This must be either an exception instance or an exception class. To know more about the list of exception class  click here.
Output:
Traceback (most recent call last):
  File "/home/4678cd3d633b2ddf9d19fde6283f987b.py", line 4, in 
    raise NameError("Hi there")  # Raise Error 
NameError: Hi there

Note: For more information, refer  Python exception handling.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.