You are on page 1of 58

11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

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

topics with examples.

Key features of Python

Python has many reasons for being popular and in demand. A few of the reasons are mentioned

below.

Emphasis on code readability, shor ter codes, ease of writing.

Programmers can express logical concepts in fewer lines of code in comparison to lan-

guages such as C++ or Java.

P ython suppor ts multiple programming paradigms, like object-oriented, imperative and

We use cookies to programming


functional ensure you have the
orbest browsing experience on our website. By using our site, you
acknowledge
procedural.

that you have read and understood our


Cookie Policy &
Privacy Policy
It provides extensive suppor t libraries(Django for web development, Pandas for data ana-

lytics etc) Got It !



https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 1/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

Start Your Coding Journey Now!


Dynamically typed language(Data type is based on value assigned)

Philosophy is “Simplicity is the best”.


Login Register

Application Areas

Getting started with Python Tutorial –

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-

structions provided below:

From #workforceplanning to managed


services and continued optimization,…
SPONSORED BY
VIALTO PARTNERS Learn More

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

Start Your Coding Journey Now!


Windows don’t come with Python preinstalled, it needs to be installed explicitly. But unlike win-

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.

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.

Download and Installation

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

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

Start Your Coding Journey Now! Login Register

Linux

MacOS

Download the Python and follow the further instructions for the installation of Python.

Beginning the installation.

Windows
Run the P ython Installer from downloads folder. Make sure to mark Add P ython 3.7 to PATH

other wise you will have to do it explicitly.

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

Start Your Coding Journey Now!


It will star t installing python on windows.

Login Register

After installation is complete click on Close.

Bingo..!! Python is installed. Now go to windows and type IDLE.

Linux
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

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

Start Your Coding Journey Now! Login Register

To verify the installation enter following commands in your Terminal.

python3

MacOS
Download and install Homebrew Package Manager

Enter following command in macOS terminal.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/ins

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

Start Your Coding Journey Now! Login Register

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-

sion 3 on your macOS.

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

StartbrewYour Coding Journey Now!


install python3

Login Register
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

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

Start Your Coding Journey Now! Login Register

How to run a Python program

Let’s consider a simple Hello World Program.

# Python program to print


# Hello World
 
print("Hello World")
Run on IDE

Generally, there are two ways to run a Python program.

Using IDEs: You can use various IDEs(P ycharm, Jupyter Notebook, etc.) which can be used

to run P ython programs.

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

Start Your Coding Journey Now! Login Register

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.

that you have read and understood our


Cookie Policy &
Privacy Policy

# Python program showing Got It !


# indentation ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 10/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

   
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.

Note: For more information, refer Indentation in Python.

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

Multi-line string as comment : P ython 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
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

Note: For more information, refer Comments in Python.

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

Note: For more information, refer Python Variables.

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-

rized based upon their different functionality:

Arithmetic operators: Arithmetic operators are used to per form mathematical operations

like addition, subtraction, multiplication and division.

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

False according to the condition.

# Examples of Relational Operators


a = 13
b = 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
We use cookies to != b)you have the best browsing experience on our website. By using our site, you
acknowledge
ensure
    that you have read and understood our
Cookie Policy &
Privacy Policy
# a >= b is False
print(a >= b) Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 13/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

   
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.

# Examples of Logical Operator


a = True
b = 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 IDE

Output:

False

True

False

Bitwise operators: Bitwise operator acts on bits and per forms bit by bit operation.

# Examples of Bitwise operators


a = 10
b = 4
   
# Print bitwise AND operation  
print(a
We use cookies to & b) you have the best browsing experience on our website. By using our site, you
acknowledge
ensure
    that you have read and understood our
Cookie Policy &
Privacy Policy
# Print bitwise OR operation
print(a | b) Got It !
    ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 14/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

# Print bitwise NOT operation 


Start Your Coding Journey Now!
print(~a)
   
Login Register
# 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 IDE

Output:

14

-11

14

40

A ssignment operators: A ssignment 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 operator
print(a1 is not b1)
print(a1 is b1)
 
# Membership operator
print("G" in a1)
print("N" not in b1)
Run on IDE

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

Start Your Coding Journey Now!


Note: For more information, refer Basic Operators in Python.
Login Register

Basics of Input/Output

Taking input from user –

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

in which we want to store. For example:

# Python program showing 


# a use of raw_input()
   
g = raw_input("Enter your name : ")
print g

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-

ber or list. For example:

# Python program showing 


# a use of input()
   
val = input("Enter your value: ")
print(val)

Note: For more information, refer Python input() and raw_input().

Printing output to console –

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.

# Python 3.x program showing


# how to print data on
# a screen
   
# One object is passed
print("GeeksForGeeks")
   
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
x = 5 that you have read and understood our
Cookie Policy &
Privacy Policy
# Two objects are passed
print("x =", x) Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 16/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

   
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

# demonstrate numeric value


Start Your Coding Journey Now!
   
print("Type of a: ", type(5))
Login Register
   
print("\nType of b: ", type(5.0))
   
c = 2 + 4j
print("\nType of c: ", type(c))
Run on IDE

Output:

Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>

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

even triple quotes.

# Python Program for 


# Creation of String 
     
# String with single quotes  
print('Welcome to the Geeks World')
     
# String with double quotes 
print("I'm a Geek")
     
# String with triple quotes
print('''I'm a Geek
We use cookies to ensure andtheIbest
you have live in experience
browsing a worldonof "Geeks"''')
our website. By using our site, you
acknowledge
that you have read and understood our
Cookie Policy &
Privacy Policy
Run on IDE
Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 18/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

Start Your Coding Journey Now!


Output:

Login Register
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 –

# Python Program to Access 


# characters of String 
     
String1 = "GeeksForGeeks"
     
# Printing First character
print(String1[0]) 
     
# Printing Last character
print(String1[-1]) 
Run on IDE

Output:

Deleting/Updating from a String –

In Python, Updation or deletion of characters from a String is not allowed because Strings are im-

mutable. Only new strings can be reassigned to the same name.

#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:

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.

# Python program to demonstrate  


# Creation of List  
     
# Creating a List 
List = [] 
print(List) 
     
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
# Creating a list of have
that you strings
read and understood our
Cookie Policy &
Privacy Policy
List = ['GeeksForGeeks', 'Geeks']
print(List)  Got It !
      ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 20/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

# Creating a Multi-Dimensional List 


Start Your Coding Journey Now!
List = [['Geeks', 'For'], ['Geeks']] 
print(List)
Login Register

Run on IDE

Output:

[]

['GeeksForGeeks', 'Geeks']

[['Geeks', 'For'], ['Geeks']]

Adding Elements to a List: Using append(), insert() and extend()

# Python program to demonstrate  


# Addition of elements in a List 
     
# Creating a List 
List = []
     
# Using append()
List.append(1) 
List.append(2)
print(List) 
   
# Using insert()
List.insert(3, 12) 
List.insert(0, 'Geeks')
print(List) 
   
# Using extend() 
List.extend([8, 'Geeks', 'Always']) 
print(List)
Run on IDE

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 repre-

sent 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].

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:

Removing Elements from the List: Using remove() and pop()

# Python program to demonstrate  


# Removal of elements in a List 
     
# Creating a List 
List = [1, 2, 3, 4, 5, 6,  
        7, 8, 9, 10, 11, 12]
 
# using Remove() method 
List.remove(5) 
List.remove(6)
print(List) 
   
# using pop()
List.pop()
print(List) 
Run on IDE

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.

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

Start Your Coding Journey Now!


Iterate over a list in Python

Python List Comprehension and Slicing


Login Register
Python programming questions on List

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

the use of parentheses for grouping of the data sequence.

# Python program to demonstrate  


# creation of Set 
     
# Creating an empty tuple 
Tuple1 = ()
print (Tuple1) 
     
# Creating a tuple of strings
print(('Geeks', 'For')) 
     
# Creating a Tuple of list 
print(tuple([1, 2, 4, 5, 6]))
 
# Creating a nested Tuple
Tuple1 = (0, 1, 2, 3) 
Tuple2 = ('python', 'geek') 
Tuple3 = (Tuple1, Tuple2)
print(Tuple3)
Run on IDE

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.

# Python program to 


# demonstrate accessing tuple
   
tuple1 = tuple([1,
We use cookies to ensure you 2,
have3, 4, browsing
the best 5]) experience on our website. By using our site, you
acknowledge
    that you have read and understood our
Cookie Policy &
Privacy Policy
# Accessing element using indexing
print(tuple1[0]) Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 23/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

   
Start Your Coding Journey Now!
# Accessing element using Negative
# Indexing
Login Register
print(tuple1[-1])
Run on IDE

Output:

Deleting/updating elements of tuple –

Items of a tuple cannot be deleted as tuples are immutable in Python. Only new tuples can be re-

assigned to the same name.

# Python program to 


# demonstrate updation / deletion
# from a tuple
   
tuple1 = tuple([1, 2, 3, 4, 5])
   
# Updating an element
tuple1[0] = -1
   
# Deleting an element
del tuple1[2]
Run on IDE

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.

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:

that you have read and understood our


Cookie Policy &
Privacy Policy

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

Start Your Coding Journey Now!


Python programming questions on Tuples

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.

# Python program to 


# demonstrate boolean type
   
print(type(True))
print(1>2)
print('a'=='a')
Run on IDE

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

placing the sequence inside curly braces {}, separated by ‘comma’.

# Python program to demonstrate  


# Creation of Set in Python 
     
# Creating a Set 
set1 = set() 
 
# Creating a Set of String 
set1 = set("GeeksForGeeks")
print(set1) 
   
# Creating a Set of List 
set1 = set(["Geeks", "For", "Geeks"])
print(set1) 
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 Run on IDE

Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 25/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

Start Your Coding Journey Now!


Output:

Login Register
{'o', 'r', 'k', 'G', 'e', 's', 'F'}

{'Geeks', 'For'}

Adding elements: Using add() and update()

# Python program to demonstrate  


# Addition of elements in a Set 
 
 
set1 = set()
     
# Adding to the Set using add()
set1.add(8)
set1.add((6, 7))
print(set1) 
   
# Additio to the Set using Update()  
set1.update([10, 11])
print(set1)
Run on IDE

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 ac-

cessed by referring to an index.

# Python program to demonstrate 


# Accessing of elements in a set 
     
# Creating a set 
set1 = set(["Geeks", "For", "Geeks"]) 
 
# Accessing using for loop
for i in set1: 
    print(i, end =" ")
Run on IDE

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

# Deletion of elements in a Set 


 Start Your Coding Journey Now!
set1 = set([1, 2, 3, 4, 5, 6,  
Login Register
            7, 8, 9, 10, 11, 12]) 
 
# using Remove() method 
set1.remove(5) 
set1.remove(6)
print(set1) 
 
# using Discard() method 
set1.discard(8) 
set1.discard(9)
print(set1) 
 
# Set using the pop() method 
set1.pop()
print(set1) 
 
# Set using clear() method 
set1.clear()
print(set1)
Run on IDE

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

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

# Creating an empty Dictionary 


Start Your Coding Journey Now!
Dict = {}
print(Dict) 
Login Register
 
# with Integer Keys 
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict) 
 
# with Mixed keys 
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print(Dict)
Run on IDE

Output:

{}

{1: 'Geeks', 2: 'For', 3: 'Geeks'}

{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Nested Dictionary:

# Creating a Nested Dictionary 


# as shown in the below image
Dict = {1: 'Geeks', 2: 'For', 
        3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}
   
print(Dict) 
Run on IDE

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'}}

that you have read and understood our


Cookie Policy &
Privacy Policy

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

Start Your Coding Journey Now!


Adding elements to a Dictionary: One value at a time can be added to a Dictionar y by defining

value along with the key e.g. Dict[Key] = ‘Value’.


Login Register

# Creating an empty Dictionary


Dict = {}
   
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print(Dict)
 
   
# Updating existing Key's Value
Dict[2] = 'Welcome'
print(Dict)
Run on IDE

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 dictionar y refer to its key

name or use get() method.

# Python program to demonstrate   


# accessing an element from a Dictionary  
     
# Creating a Dictionary  
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 
     
# accessing a element using key
print(Dict['name']) 
   
# accessing a element using get()
print(Dict.get(3))
Run on IDE

Output:

For

Geeks

Removing Elements from Dictionary: Using pop() and popitem()


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
# Initial Dictionary 
Dict = { 5 : 'Welcome', 6 : 'To', Got
7 :It'Geeks', 
!
        'A' : {1 : 'Geeks', 2 : 'For',▲3 : 'Geeks'},
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 29/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

       } 
Start Your Coding Journey Now!
     
# using pop() 
Login Register
Dict.pop(5)
print(Dict) 
 
# using popitem() 
Dict.popitem()
print(Dict) 
Run on IDE

Output:

{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 6: 'To', 7: 'Geeks'}

{6: 'To', 7: 'Geeks'}

Note: For more information, refer Python Dictionar y.

Refer to the below articles to know more about dictionary:

Operations on Dictionar y

Iterate over a dictionar y in Python

Python programming questions 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

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

#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

Example 2: To demonstrate nested-if and if-elif

# Python program to demonstrate


# decision making
 
a = 10
 
# Nested if to check whether a
# number is divisible by both 2 and 5
if a % 2 == 0:
    if a % 5 == 0:
        print("Number is divisible by both 2 and 5")
         
# is-elif
if (a == 11):
    print ("a is 11")
elif (a == 10):
    print ("a is 10")
else:
    print ("a is not present")
Run on IDE

Output:

Number is divisible by both 2 and 5

a is 10

Note: For more information, refer Decision Making in Python.

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

Start Your Coding Journey Now!


Loops in programming come into use when we need to repeatedly execute a block of statements.

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:

While and while-else loop

# Python program to illustrate 


# while and while-else loop
i = 0
while (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 = 10
while i < 12: 
    i += 1
    print(i) 
    break
else: # Not executed as there is a break 
    print("No Break")
Run on IDE

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
Output:

that you have read and understood our


Cookie Policy &
Privacy Policy

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

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: 
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
    print(i) 
else: # Executed that you have read and no
because understood
breakour
Cookie
in for  Policy &
Privacy Policy
    print("No Break\n")  Got It !
    ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 33/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

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

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 returned

2) 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 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

Start Your Coding Journey Now! Login Register

# 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 IDE

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.

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

Start Your Coding Journey Now!


Understanding for-loop in Python

Backward iteration in Python


Login Register

Loop control statements

Loop control statements change execution from its normal sequence. Following are the loop con-

trol statements provided by Python:

Break : Break statement in P ython 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 terminat-

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

statement, function and classes.

# Python program to demonstrate


# break, continue and pass
   
s = 'geeksforgeeks'
 
for letter in s:
    if letter == 'e' or letter == 's':
        break
    print(letter, end = " ")
print()
 
for letter in s:
    if letter == 'e' or letter == 's':
        continue
    print(letter, end = " ")
print()   
 
for letter in s:
    if letter == 'e' or letter == 's':
        pass
    print(letter, end = " ")
Run on IDE

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

used to create functions.

# Python program to demonstrate


# functions
 
 
# Defining functions
def ask_user():
    print("Hello Geeks")
 
# Function that returns sum
# of first 10 numbers
def my_func():
    a = 0
    for i in range(1, 11):
        a = a + i
    return a
     
# Calling functions
ask_user()
res = my_func()
print(res)
Run on IDE

Output:

Hello Geeks

55

Function with arguments

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
 
  cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
We use
def myFun(x, thatyyou
= have
50):read and understood our
Cookie Policy &
Privacy Policy
    print("x: ", x)
    print("y: ", y) Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 37/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

   
Start Your Coding Journey Now!
# Driver code
myFun(10)
Login Register

Run on IDE

Output:

('x: ', 10)

('y: ', 50)

Keyword arguments: The idea is to allow caller to specif y 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 IDE

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-

ments that will be passed into a function.

# Python program to demonstrate


# variable length arguments
 
 
# variable arguments
def myFun1(*argv): 
    for arg in argv: 
        print(arg, end =" ")
         
# variable keyword arguments
def myFun2(**kwargs):
    for key, value in kwargs.items():
        print ("% s == % s" %(key, value))
   
We use
# cookies
Driver to ensure
codeyou have the best browsing experience on our website. By using our site, you
acknowledge
myFun1('Hello', that you 'Welcome',
have read and understood
'to', our
Cookie Policy &
Privacy Policy
'GeeksforGeeks')
print() Got It !
myFun2(first ='Geeks', mid ='for',▲last ='Geeks')
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 38/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

Start Your Coding Journey Now! Login Register


Run on IDE

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

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-

ments but has only one expression.

# Python code to demonstrate  


# labmda function 
 
# Cube using lambda
cube = lambda x: x * x*x 
print(cube(7))
 
# List comprehension using lambda
a = [(lambda x: x * 2)(x) for x in range(5)]
print(a)
Run on IDE

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

Start Your Coding Journey Now!


Refer to the below articles to know more about Lambda:
Login Register
Python programming questions on Lambda

Object Oriented Programming

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 func-

tions that operate on them so that no other part of the code can access this data except that

function.

Classes and Objects

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-

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

# Python program to demonstrate


# classes and objects
   
class Dog: 
       
    # A simple class attribute
We use cookies=to "mamal"
    attr1 ensure you have the best browsing experience on our website. By using our site, you
acknowledge
    attr2 = "dog" that you have read and understood our
Cookie Policy &
Privacy Policy
    Got It !
    # A sample method   ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 40/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

    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

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 and Destructors

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.

# Python program to demonstrate


# constructors
 
 We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
class Addition:that you have read and understood our
Cookie Policy &
Privacy Policy
    # parameterized constructor
    def __init__(self, f, s): Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 41/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

        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

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.

# Python program to illustrate destructor


class Employee:
   
    # Initializing
    def __init__(self):
        print('Employee created.')
   
    # Deleting (Calling destructor)
    def __del__(self):
        print('Destructor called, Employee deleted.')
   
obj = Employee()
del obj
Run on IDE

Output:

Employee created.

Destructor called, Employee deleted.

Note: For more information, refer Destructors in Python.

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

Start Your Coding Journey Now!


Inheritance is the ability of any class to extract and use features of other classes. It is the process

Login
by which new classes called the derived classes are created from existing classes called Base
Register
classes.

# A Python program to demonstrate inheritance 


   
 
class Person():
       
    # Constructor
    def __init__(self, name):
        self.name = name
   
    # To get name
    def getName(self):
        return self.name
   
    # To check if this person is employee
    def isEmployee(self):
        return False
   
   
# Inherited or Sub class (Note Person in bracket)
class Employee(Person):
   
    # Here we return true
    def isEmployee(self):
        return True
   
# Driver code
emp = Person("Geek1")  # An Object of Person
print(emp.getName(), emp.isEmployee())
   
emp = Employee("Geek2") # An Object of Employee
print(emp.getName(), emp.isEmployee())
Run on IDE

Output:

Geek1 False

Geek2 True

Note: For more information, refer Python inheritance.

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-

that you have read and understood our


Cookie Policy &
Privacy Policy
dental modification of data.

Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 43/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

# Python program to demonstrate


Start Your Coding Journey Now!
# encapsulation
   
Login Register
# Creating a Base class
class Base:
    def __init__(self):
        self.a = "GeeksforGeeks"
        self.__c = "GeeksforGeeks"
   
# Creating a derived class
class Derived(Base):
    def __init__(self):
           
        # Calling constructor of
        # Base class
        Base.__init__(self) 
        print("Calling private member of base class: ")
        print(self.__a)
# Driver code
obj = Derived()
Run on IDE

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

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.

# Python program to demonstrate


# Polymorphism
 
 
class A():
    def show(self):
        print("Inside A")
         
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
class B(): that you have read and understood our
Cookie Policy &
Privacy Policy
    def show(self):
        print("Inside B") Got It !
          ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 44/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

# 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

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

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.

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:

ACCESS MODE DESCRIPTION

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

Start Your Coding Journey Now!


ACCESS MODE DESCRIPTION
Login Register
Read and Write (‘r+’) Open the file for reading and writing. The
handle is positioned at the beginning of the
file.

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

existing file, data is truncated and over-writ-


ten. The handle is positioned at the begin-
ning of the file.

Append Only (‘a’) Open the file for writing. The handle is posi-

tioned at the end of the file.

Append and Read (‘a+’) Open the file for reading and writing. The
handle is positioned at the end of the file.

# Open function to open the file "MyFile1.txt"  


# (same directory) in read mode and 
file1 = open("MyFile.txt", "r") 
     
# store its reference in the variable file1  
# and "MyFile2.txt" in D:\Text in file2 
file2 = open(r"D:\Text\MyFile2.txt", "r+") 

Note: For more information, refer Open a File in Python.

2) Close the file: close() function closes the file and frees the memor y space acquired by that file.

# Opening and Closing a file "MyFile.txt"


# for object name file1.
file1 = open("MyFile.txt", "a")
file1.close()

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()

Let’s suppose the file looks like this:

# Program to show various ways to 


# read data from a file.
   
file1 = open("data.txt", "r+")
   
print("Output of Read function is ")
print(file1.read())
print()
   
# seek(n) takes the file handle to the nth
# bite from the beginning. 
file1.seek(0)
   
print("Output of Readline function is ")
print(file1.readline())
print()
   
file1.seek(0)
   
#Wereadlines
use cookies to function 
ensure you have the best browsing experience on our website. By using our site, you
acknowledge
print("Output of thatReadlines function
you have read and understoodis ") Policy &
Privacy Policy
our
Cookie
print(file1.readlines())
print() Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 47/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

file1.close() 
Start Your Coding Journey Now! Login Register
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(): 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-

ser t multiple strings at a single time.

File_object.writelines(L) for L = [str1, str2, str3]

# Python program to demonstrate


# writing to file
   
# Opening a file
file1 = open('myfile.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"
   
# Writing a string to file
file1.write(s)
   
# Writing multiple strings
# at a time
file1.writelines(L)
   
# Closing file
file1.close()

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

Start Your Coding Journey Now! Login Register

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

Modules and Packages

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

help of import statement.

Let’s create a simple module named GFG.

# Python program to demonstrate


# modules
  
  
# Defining a function
def Geeks():
    print("GeeksforGeeks")
  
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
# Defining a variable that you have read and understood our
Cookie Policy &
Privacy Policy
location = "Noida"
   Got It !
# Defining a class ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 49/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

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

module using the import statement.

# Python program to demonstrate


# modules
  
  
import GFG
  
# Use the function created
GFG.Geeks()
  
# Print the variable declared
print(GFG.location) 
  
# Use the class created
emp = GFG.Employee("Nikhil", "Developer")
emp.show()

Output:

GeeksforGeeks

Noida

Employee name: Nikhil

Employee position: Developer

Note: For more information, refer Python Modules.

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.

To create a package in Python, we need to follow these three simple steps:

First, we create a director y and give it a package name, preferably related to its operation.

Then we put the classes and the required functions in it.

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

Start Your Coding Journey Now!


Example: Let’s create a package for cars.

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

# 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)

For 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)

Finally we create the __init__.py file. This file will be placed inside the Cars director y 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 director y

where Cars package is located and add the following code to it:

# Import classes from your brand new package


from Cars import Bmw
from Cars import Audi
    
# Create an object of Bmw class & call its method
ModBMW = Bmw()
ModBMW.outModels()
    
# Create an object of Audi class & call its method
ModAudi = Audi()
ModAudi.outModels()

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

Start Your Coding Journey Now! Login Register

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:

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

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-

acter, 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 per forming 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 IDE

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

Start Your Coding Journey Now!


re.match(): This function attempts to match pattern to whole string. The re.match function

returns a match object on success, None on failure.


Login Register

# 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 IDE

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 par t 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
We use attheindex
cookies to ensure you have % s,experience
best browsing % s" %on(match.start(),
our website. By using our match.end()))
site, you
acknowledge
    that you have read and understood our
Cookie Policy &
Privacy Policy
    # this will print "June 24"
    print("Full match: % s" % Got It !
(match.group(0)))
    ▲
https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 54/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

    # this will print "June"


Start Your Coding Journey Now!
    print("Month: % s" % (match.group(1))) Login
   
Register
    # this will print "24"
    print("Day: % s" % (match.group(2)))
   
else:
    print("The regex pattern does not match.")
Run on IDE

Output:

Match at index 14, 21

Full match: June 24

Month: June

Day: 24

Note: For more information, refer Regular Expression in Python.

Exception handling

Like other languages, Python also provides the runtime errors via exception handling method with

the help of tr y-except.

How try-except works?

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.

A tr y statement can have more than one except clause.

Code 1: No exception, so tr y clause will run.

# Python code to illustrate


# working of try() 
def divide(x, y):
    try:
        result = x // y
        print("Yeah ! Your answer is :", result)
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")
   
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
# Look at parameters and note the working of Program
that you have read and understood our
Cookie Policy &
Privacy Policy
divide(3, 2)
Got It !

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/ 55/58
11/6/22, 11:39 PM Python Tutorial - GeeksforGeeks

Run on IDE
Start Your Coding Journey Now! Login Register
Output:

Yeah ! Your answer is : 1

Code 2: There is an exception so only except clause will run.

# Python code to illustrate


# working of try() 
def divide(x, y):
    try:
        result = x // y
        print("Yeah ! Your answer is :", result)
    except:
        print("Sorry ! You are dividing by zero ")
   
# Look at parameters and note the working of Program
divide(3, 0)
Run on IDE

Output:

Sorry ! You are dividing by zero

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.

# Python code to illustrate


# working of try() 
def divide(x, y):
    try:
        result = x // y
        print("Yeah ! Your answer is :", result)
    except:
        print("Sorry ! You are dividing by zero ")
    else:
        print("No exception raised")
   
# Look at parameters and note the working of Program
divide(3, 2)
Run on IDE

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

Start Your Coding Journey Now!


Raising Exception: The raise statement allows the programmer to force a specific exception to oc-

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.

# Program to depict Raising Exception


   
try: 
    raise NameError("Hi there")  # Raise Error
except NameError:
    print("An exception")
    raise  # To determine whether the exception was raised or not
Run on IDE

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.

Load Comments

A-143, 9th Floor, Sovereign Corporate Tower,

Sector-136, Noida, Uttar Pradesh - 201305

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

Start Your Coding


Careers Journey Now! LoginData Structures Register
In Media SDE Cheat Sheet
Contact Us Machine learning
Privacy Policy CS Subjects
Copyright Policy Video Tutorials
Courses

News
Top News
Languages
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin

Web Development Contribute


Web Tutorials Write an Article
Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@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

You might also like