Professional Documents
Culture Documents
Python Tutorial
Last Updated : 22 Jul, 2022
Python is a general-purpose high-level programming language and is widely used among the de-
velopers’ community. Python was mainly developed for emphasis on code readability, and its syn-
tax allows programmers to express concepts in fewer lines of code. This Python tutorial provides
learners (either beginner or experienced developers) with topics from Python basics to advanced
Python has many reasons for being popular and in demand. A few of the reasons are mentioned
below.
Programmers can express logical concepts in fewer lines of code in comparison to lan-
Application Areas
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 be-
cause 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 in-
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
What if Python already exists? Let’s check
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 2/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Login
dows, most of the Linux OS have Python pre-installed, also macOS comes with Python pre-in-
Register
stalled.
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.
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
Windows
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 3/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Linux
MacOS
Download the Python and follow the further instructions for the installation of Python.
Windows
Run the P ython Installer from downloads folder. Make sure to mark Add P ython 3.7 to PATH
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 4/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Login Register
Linux
For almost every Linux system, the following commands would work definitely.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 5/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
python3
MacOS
Download and install Homebrew Package Manager
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Sale Ends Today!
DSA Data Structures Algorithms Write & Earn Interview Preparation Topic-wise Practice
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 6/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
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 ver-
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
Install Python Latest Version on macOS / macOS X
that you have read and understood our
Cookie Policy &
Privacy Policy
Open Terminal and enter the following command.
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 7/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Login Register
After command processing is complete, Python’s version 3 would be installed on your mac.
pythona fa-hand-o-right
pip3
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 8/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Using IDEs: You can use various IDEs(P ycharm, Jupyter Notebook, etc.) which can be used
Using Command-Line: You can also use command line options to run a P ython program.
Below steps demonstrate how to run a P ython program on Command line in Windows/Unix
Operating System:
Windows
Open Commandline and then to compile the code type python HelloWorld.py. If your code has no
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
error then it will execute properly and output will be displayed.
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 9/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Unix/Linux
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.
Fundamentals of Python
Python Indentation
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
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
better by looking at the following lines of code.
Start Your Coding Journey Now!
site = 'gfg'
Login Register
if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')
Run on IDE
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 fi-
nal print(‘All set!’) is not indented, and so it does not belong to the else-block.
Python Comments
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: P ython single line comment star ts with hashtag symbol with no
white spaces.
# This is a comment
# Print “GeeksforGeeks !” to console
print("GeeksforGeeks")
Run on IDE
"""
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
We use well-explained
cookies computer
to ensure you have the science
best browsing experience on our website. By using our site, you
acknowledge
and programming articles,
that you have read and understood our
Cookie Policy &
Privacy Policy
quizzes and more.
… Got It !
""" ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 11/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
print("GeeksForGeeks")
Start Your Coding Journey Now! Login Register
Run on IDE
Variables
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.
#!/usr/bin/python
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Run on IDE
Output:
45
1456.8
John
Operators
Operators are the main building block of any programming language. Operators allow the pro-
grammer to perform different kinds of operations on operands. These operators can be catego-
Arithmetic operators: Arithmetic operators are used to per form mathematical operations
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
# Examples of Arithmetic Operator
a = 9 Got It !
b = 4 ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 12/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Start Your Coding Journey Now!
# Addition of numbers
add = a + b
Login Register
# 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 IDE
Output:
13
36
2.25
Relational Operators: Relational operators compares the values. It either returns True or
Start Your Coding Journey Now!
# a <= b is True
print(a <= b)
Login Register
Run on IDE
Output:
False
True
False
True
False
True
Logical Operators: Logical operators per form Logical AND, Logical OR and Logical NOT
operations.
Output:
False
True
False
Bitwise operators: Bitwise operator acts on bits and per forms bit by bit operation.
Run on IDE
Output:
14
-11
14
40
A ssignment operators: A ssignment operators are used to assign values to the variables.
Output:
False
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
True
that you have read and understood our
Cookie Policy &
Privacy Policy
True
Got It !
True
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 15/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Basics of Input/Output
Python provides us with two inbuilt functions to read the input from the keyboard.
raw_input(): This function works in older version (like P ython 2.x). This function takes ex-
actly what is typed from the keyboard, conver t it to string and then return it to the variable
input(): This function first takes the input from the user and then evaluates the expression,
which means P ython automatically identifies whether the user entered a string or a num-
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
Start Your Coding Journey Now!
# code for disabling the softspace feature
print('G', 'F', 'G', sep ='')
Login Register
# using end argument
print("Python", end = '@')
print("GeeksforGeeks")
Run on IDE
Output:
GeeksForGeeks
x = 5
GFG
Python@GeeksforGeeks
Data Types
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 ever ything is an object in
Python programming, data types are actually classes and variables are instance (object) of these
classes.
Numeric
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 com‐
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
plex class in Python.that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
# Python program to ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 17/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Output:
Sequence Type
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
Login Register
Welcome to the Geeks World
I'm a Geek
Output:
In Python, Updation or deletion of characters from a String is not allowed because Strings are im-
#WePython Program
use cookies to have
to ensure you Update
the best/browsing
delete experience on our website. By using our site, you
acknowledge
# character of a thatString
you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
String1 = "Hello, I'm a Geek" ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 19/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Start Your Coding Journey Now!
# Updating a character
String1[2] = 'p'
Login Register
# Deleting a character
del String1[2]
Run on IDE
Output:
String1[2] = ‘p’
del String1[2]
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.
Run on IDE
Output:
[]
['GeeksForGeeks', 'Geeks']
Output:
[1, 2]
['Geeks', 1, 2, 12]
Use the index operator [ ] to access an item in a list. In Python, negative sequence indexes repre-
sent positions from the end of the array. Instead of having to compute the offset as in
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
# Python program thatto
you demonstrate
have read and understood our
Cookie Policy &
Privacy Policy
# accessing of element from list
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 21/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Start Your Coding Journey Now!
List = [1, 2, 3, 4, 5, 6]
Login Register
# accessing a element
print(List[0])
print(List[2])
# Negative indexing
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
Run on IDE
Output:
Output:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Refer to the below articles to know more about List:
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 22/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
3) Tuple: Tuple is an ordered collection of Python objects much like a list. The important differ-
ence 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
Output:
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
Start Your Coding Journey Now!
# Accessing element using Negative
# Indexing
Login Register
print(tuple1[-1])
Run on IDE
Output:
Items of a tuple cannot be deleted as tuples are immutable in Python. Only new tuples can be re-
Output:
tuple1[0] = -1
del tuple1[2]
WeRefer
use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
to the below articles to know more about tuples:
Got It !
Unpacking a Tuple in Python
Operations on Tuples ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 24/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Login Register
Boolean
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
Set
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
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 25/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Login Register
{'o', 'r', 'k', 'G', 'e', 's', 'F'}
{'Geeks', 'For'}
Output:
Accessing a Set: One can loop through the set items using a for loop as set items cannot be ac-
Output:
Geeks For
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
Removing elements that
fromyou ahave
set:read and understood
Using our
Cookie, Policy
remove(), discard() pop() &
Privacy Policy
and clear()
Got It !
# Python program to demonstrate ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 26/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Output:
set()
frozenset() in Python
Dictionary
Dictionar y in Python is an unordered collection of data values, used to store data values like a
map. Dictionar y holds key:value pair. Each key-value pair in a Dictionar y is separated by a colon :,
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
whereas each key is separated by a ‘comma’. A Dictionar y can be created by placing a sequence of
that you have read and understood our
Cookie Policy &
Privacy Policy
{} braces, separated by ‘comma’.
Got It !
elements within curly
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 27/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Output:
{}
Nested Dictionary:
Output:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Got It !
Note: For more information, refer Python Nested Dictionar y.
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 28/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Output:
Accessing elements from a Dictionary: In order to access the items of a dictionar y refer to its key
Output:
For
Geeks
}
Start Your Coding Journey Now!
# using pop()
Login Register
Dict.pop(5)
print(Dict)
# using popitem()
Dict.popitem()
print(Dict)
Run on IDE
Output:
Operations on Dictionar y
Decision Making
Decision Making in programming is similar to decision making in real life. A programming lan-
guage 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
if statement
if..else statements
nested if statements
if-elif ladder
#WePython
use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
program to demonstrate
# decision making that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
a = 10 ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 30/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
b = 15
Start Your Coding Journey Now!
# if to check even number
Login Register
if a % 2 == 0:
print("Even Number")
# if-else to check even or odd
if b % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Run on IDE
Output:
Even Number
Odd Number
Output:
a is 10
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
Control flow (Loops)
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 31/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Login
For example: Suppose we want to print “Hello World” 10 times. This can be done with the help of
Register
loops. The loops in Python are:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
Output:
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 32/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
StartHello
Your Coding Journey Now!
Geek
Hello Geek
Login Register
Hello Geek
11
for i in s:
Start Your Coding Journey Now!
print(i)
break
Login Register
else: # Not executed as there is a break
print("No Break")
Run on IDE
Output:
List Iteration
geeks
for
geeks
String Iteration
For-else loop
No Break
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.
3) step: integer value which determines the increment between each integer in the sequence
filter_none
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 34/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Output:
0 1 2 3 4
2 3 4 5 6 7 8
15 18 21 24
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Refer to the below articles to know more about Loops:
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 35/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Loop control statements change execution from its normal sequence. Following are the loop con-
Break : Break statement in P ython is used to bring the control out of the loop when some
ing 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
Output:
g k f o r g k
g e e k s f o r g e e k s
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Note: For more information, refer break, continue and pass in Python.
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 36/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Functions
Start Your Coding Journey Now! Login Register
Functions are generally the block of codes or statements in a program that gives the user the abil-
ity to reuse the same code which ultimately saves the excessive use of memor y, 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 func-
tion can also perform some specific task without returning anything. In Python, def keyword is
Output:
Hello Geeks
55
Start Your Coding Journey Now!
# Driver code
myFun(10)
Login Register
Run on IDE
Output:
Keyword arguments: The idea is to allow caller to specif y argument name with values so
Output:
('Geeks', 'Practice')
('Geeks', 'Practice')
Variable length arguments: In P ython a function can also have variable number of argu-
ments. This can be used in the case when we do not know in advance the number of argu-
Output:
first == Geeks
last == Geeks
mid == for
Lambda functions
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 argu-
Output:
343
[0, 2, 4, 6, 8]
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Note: For more information, refer Python lambda (Anonymous Functions).
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 39/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
polymorphism, etc in programming. The main aim of OOP is to bind together the data and the func-
tions 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 func-
tions, which can be accessed and used by creating an instance of that class. A class is like a blue-
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class
def fun(self):
Start Your Coding Journey Now!
print("I'm a", self.attr1)
print("I'm a", self.attr2)
Login Register
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
Run on IDE
Output:
mamal
I'm a mamal
I'm a dog
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.
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
Default constructor: The constructor which is called implicilty and do not accept any
argument.
self.first = f
Start Your Coding Journey Now!
self.second = s
Login Register
def calculate(self):
print(self.first + self.second)
# Invoking parameterized constructor
obj = Addition(1000, 2000)
# perform Addition
obj.calculate()
Run on IDE
Output:
3000
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
Output:
Employee created.
Inheritance
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 42/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Login
by which new classes called the derived classes are created from existing classes called Base
Register
classes.
Output:
Geek1 False
Geek2 True
Encapsulation
Encapsulation describes the idea of wrapping data and the methods that work on data within one
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
unit. This puts restrictions on accessing variables and methods directly and can prevent the acci-
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 43/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Output:
obj = Derived()
print(self.__a)
Polymorphism
Polymorphism refers to the ability of OOPs programming languages to differentiate between enti-
ties with the same name efficiently. This is done by Python with the help of the signature of these
entities.
# Driver's code
Start Your Coding Journey Now!
a = A()
a.show()
Login Register
b = B()
b.show()
Run on IDE
Output:
Inside A
Inside B
__new__ in Python
File Handling
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 binar y 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.
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
Read Only (‘r’) Open text file for reading. The handle is po-
sitioned at the beginning of the file.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 45/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Write Only (‘w’) Open the file for writing. For existing file,
the data is truncated and over-written. The
handle is positioned at the beginning of the
file.
Write and Read (‘w+’) Open the file for reading and writing. For
Append Only (‘a’) Open the file for writing. The handle is posi-
Append and Read (‘a+’) Open the file for reading and writing. The
handle is positioned at the end of the file.
2) Close the file: close() function closes the file and frees the memor y space acquired by that file.
3) Reading from a File: There are three ways to read data from a text file.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 46/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
StartFile_object.read([n])
Your Coding Journey Now! Login Register
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])
readlines(): Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
file1.close()
Start Your Coding Journey Now! Login Register
Output:
Code is like humor. When you have to explain it, its bad.
Code is like humor. When you have to explain it, its bad.
['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.
write(): Inser ts the string str1 in a single line in the text file.
File_object.write(str1)
writelines(): For a list of string elements, each string is inser ted in the text file. Used to in-
Output:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 48/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
OS Module in Python
Programs on OS module
Modules
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
class Employee():
Start Your Coding Journey Now!
def __init__(self, name, position):
Login Register
self. name = name
self.position = position
def show(self):
print("Employee name:", self.name)
print("Employee position:", self.position)
To use the above created module, create a new Python file in the same director y and import GFG
Output:
GeeksforGeeks
Noida
Packages
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.
First, we create a director y and give it a package name, preferably related to its operation.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
Finally we create an __init__.py file inside the director y, to let P ython know that the direc-
that you have read and understood our
Cookie Policy &
Privacy Policy
tor y is a package.
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 50/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Login Register
First we create a director y and name it Cars.
Then we need to create modules. We will create 2 modules – BMW and AUDI.
For Bmw.py
For Audi.py
Finally we create the __init__.py file. This file will be placed inside the Cars director y and
Now, let’s use the package that we created. To do this make a sample.py file in the same director y
where Cars package is located and add the following code to it:
Output:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 51/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Note: For more information, refer Create and Access a Python Package.
Regular expressions(RegEx)
Python RegEx is a powerful text matching tool that uses a pre-defined pattern to match the text. It
can identify the presence or absence of text by comparing it to a specific pattern, and it can also
divide a pattern into one or more sub-patterns. Below is the list of metacharacters:
separated by it.
to match.
The string is scanned left-to-right, and matches are returned in the order found.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
# A Python that program
you havetoreaddemonstrate working
and understood our
Cookie of&
Privacy Policy
Policy
# findall()
import re Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 52/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Start Your Coding Journey Now!
string = """Hello my Number is 123456789 and
Login Register
my friend's number is 987654321"""
# A sample regular expression to find digits.
regex = '\d+'
match = re.findall(regex, string)
print(match)
Run on IDE
Output:
['123456789', '987654321']
In the above example, metacharacter blackslash ‘\’ has a ver y important role as it signals
various sequences. If the blackslash is to be used without its special meaning as metachar-
re.compile(): Regular expressions are compiled into pattern objects, which have methods
for various operations such as searching for pattern matches or per forming string
substitutions.
Output:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
['e', 'a', 'd', 'b', 'e', 'a']
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 53/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Output:
Month: Jun
Day: 24
re.search(): This method either returns None (if the pattern doesn’t match), or a
re.MatchObject that contains information about the matching par t of the string.
Output:
Month: June
Day: 24
Exception handling
Like other languages, Python also provides the runtime errors via exception handling method with
First tr y clause is executed i.e. the code between tr y and except clause.
If there is no exception, then only tr y clause will run, except clause is finished.
If any exception occurred, tr y 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 tr y statements. If the exception left unhandled, then the execution stops.
Run on IDE
Start Your Coding Journey Now! Login Register
Output:
Output:
Else Clause: In python, you can also use else clause on tr y-except block which must be present
after all the except clauses. The code enters the else block only if the tr y clause does not raise an
exception.
Output:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Yeah ! Your answer is : 1
No exception raised
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 56/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
Login
cur. This must be either an exception instance or an exception class. To know more about the list of
Register
exception class click here.
Output:
NameError: Hi there
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Load Comments
feedback@geeksforgeeks.org
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Company Got It !
Learn
▲
About Us Algorithms
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 57/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks
About Us Algorithms
News
Top News
Languages
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin
@geeksforgeeks
, Some rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 58/58