SlideShare a Scribd company logo
Python for Beginners(v3)
Dr.M.Rajendiran
Dept. of Computer Science and Engineering
Panimalar Engineering College
Install Python 3 On Ubuntu
Prerequisites
Step 1.A system running Ubuntu
Step 2.A user account with sudo privileges
Step 3.Access to a terminal command-line (Ctrl–Alt–T)
Step 4.Make sure your environment is configured to use
Python 3.8
2
Install Python 3
Now you can start the installation of Python 3.8.
$sudo apt install python3.8
Allow the process to complete and verify the Python
version was installed successfully
$python ––version
3
Installing and using Python on Windows is very simple.
Step 1: Download the Python Installer binaries
Step 2: Run the Executable Installer
Step 3: Add Python to environmental variables
Step 4: Verify the Python Installation
4
Python Installation
Open the Python website in your web browser.
https://www.python.org/downloads/windows/
Once the installer is downloaded, run the Python installer.
Add the following path
C:Program FilesPython37-32: for 64-bit installation
Once the installation is over, you will see a Python Setup
Successful window.
You are ready to start developing Python applications in
your Windows 10 system.
5
iPython Installation
If you already have Python installed, you can use pip to
install iPython using the following command:
$pip install iPython
To use it, type the following command in your computer’s
terminal:
$ipython
6
Compound Data Type
List
 List is an ordered sequence of items. Values in the list are called
elements.
 List of values separated by commas within square brackets[ ].
 Items in the lists can be of different data types.
Tuples
 A tuple is same as list.
 The set of elements is enclosed in parentheses.
 A tuple is an immutable list.
i.e. once a tuple has been created, you can't add elements to a
tuple or remove elements from the tuple.
 Tuple can be converted into list and list can be converted in to tuple.
Compound Data Type
Dictionary
 Dictionary is an unordered collection of elements.
 An element in dictionary has a key: value pair.
 All elements in dictionary are placed inside the curly braces{ }
 Elements in dictionaries are accessed via keys and not by their
position.
 The values of a dictionary can be any data type.
 Keys must be immutable data type.
List
1.List operations
2.List slices
3.List methods
4.List loop
5.Mutability
6.Aliasing
7.Cloning lists
8.List parameters
List
Operations on list
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
List
.
Operation Example Description
create a list
>>> a=[2,3,4,5,6,7,8,9,10]
>>> print(a)
[2, 3, 4, 5, 6, 7, 8, 9, 10]
we can create a list at compile
time
Indexing
>>> print(a[0])
2
>>> print(a[8])
10
>>> print(a[-1])
10
Accessing the item in the
position 0
Accessing the item in the
position 8
Accessing a last element using
negative indexing.
Slicing
>>> print(a[0:3])
[2, 3, 4]
>>> print(a[0:])
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Printing a part of the list.
Concatenation
>>>b=[20,30]
>>> print(a+b)
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
Adding and printing the items of
two lists.
Repetition
>>> print(b*3)
[20, 30, 20, 30, 20, 30]
Create a multiple copies of the
same list.
Updating
>>> print(a[2])
4
>>> a[2]=100
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Updating the list using index
value.
List
List slices
List slicing is an operation that extracts a subset of elements from an
list.
Operation Example Description
Membership
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
True
>>> 100 in a
False
>>> 2 not in a
False
Returns True if element is
present in list. Otherwise returns
false.
Comparison
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4]
>>> a==b
False
>>> a!=b
True
Returns True if all elements in
both elements are same.
Otherwise returns false
List
Syntax
listname[start:stop]
listname[start:stop:steps]
 Default start value is 0
 Default stop value is n-1
 [:] this will print the entire list
 [2:2] this will create a empty slice slices example
Slices Example Description
a[0:3]
>>> a=[9,8,7,6,5,4]
>>> a[0:3]
[9, 8, 7]
Printing a part of a list from 0 to
2.
a[:4] >>> a[:4]
[9, 8, 7, 6]
Default start value is 0. so prints
from 0 to 3
a[1:] >>> a[1:]
[8, 7, 6, 5, 4]
Default stop value will be n-1. so
prints from 1 to 5
List
List methods
 Methods used in lists are used to manipulate the data quickly.
 These methods work only on lists.
 They do not work on the other sequence types that are not mutable,
that is, the values cannot be changed.
Syntax
list name.method name( element/index/list)
Slices Example Description
list.append(element)
>>> a=[1,2,3,4,5]
>>> a.append(6)
>>> print(a)
[1, 2, 3, 4, 5, 6]
Add an element to the end of the
list
list.insert(index,element
)
>>> a.insert(0,0)
>>> print(a)
[0, 1, 2, 3, 4, 5, 6]
Insert an item at the defined
index
min(list) >>> min(a)
2
Return the minimum element in a
list
List
. Syntax Example Description
list.extend(b)
>>> b=[7,8,9]
>>> a.extend(b)
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
Add all elements of a list to the
another list
list,index(element)
>>> a.index(8)
8
Returns the index of the element
list.sort()
>>> a.sort()
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
Sort items in a list
list.reverse()
>>> a.reverse()
>>> print(a)
[9,8, 7, 6, 5, 4, 3, 2, 1, 0]
Reverse the order.
list.remove(element)
>>> a.remove(0)
>>> print(a)
[9,8,7, 6, 5, 4, 3, 2,1]
Removes an item from the list
list.copy()
>>> b=a.copy()
>>> print(b)
[9,8,7, 6, 5, 4, 3, 2,1]
Copy from a to b
len(list)
>>>len(a)
9
Length of the list
List
Try yourself:
list.pop()
list.pop(index)
list.remove(element)
list.count(element)
max(list)
list.clear()
del(list)
List
List loops
1. for loop
2. while loop
3. infinite loop
for Loop
 The for loop in python is used to iterate over a sequence (list, tuple,
string) or other iterable objects.
 Iterating over a sequence is called traversal.
 Loop continues until we reach the last item in the sequence.
 The body of for loop is separated from the rest of the code using
indentation.
Syntax:
for variable in sequence:
List
Example
Accessing element
a=[10,20,30,40,50]
for i in a:
print(i)
Output
10
20
30
40
50
Accessing index output
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(i)
output
0
1
2
3
4
Accessing element using range
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(a[i])
----------------------------------------------------------
print(id(a[i])) # for memory address
output
10
20
30
40
50
List
While loop
 The while loop is used to iterate over a block of code as long as the
test condition is true.
 When the condition is tested and the result is false, the loop body
will be skipped and the first statement after the while loop will be
executed.
Syntax:
while (condition):
body of the statement
Example: Sum of the elements in
list
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
Output
15
List
infinite Loop
 A loop becomes infinite loop if the condition becomes false.
 It keeps on running. Such loops are called infinite loop.
Example:
a=1
while (a==1):
n=int(input("enter the number"))
print("you entered:" , n)
Output
Enter the number 10
you entered:10
Enter the number 12
you entered:12
Enter the number 16
you entered:16
List
Mutability
 Lists are mutable.(It can be changed)
 Mutability is the ability for certain types of data to be changed without
entirely recreating it.
 An item can be changed in a list by accessing it directly as part of the
assignment statement.
 Using the indexing operator on the left side of an assignment, one of
the list items can be updated.
 Example:
>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
changing single element
>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
changing multiple element
List
Aliasing(copying)
 Creating a copy of a list is called aliasing.
 When you create a copy both list will be having same memory location.
 Changes in one list will affect another list.
 Aliasing refers to having different names for same list values.
Example:
a= [1, 2, 3 ,4 ,5]
b=a
print (b)
a is b
a[0]=100
print(a)
print(b)
[1, 2, 3, 4, 5]
[100,2,3,4,5]
[100,2,3,4,5]
List
Cloning
 Creating a copy of a same list of elements with different memory
locations is called cloning.
 Changes in one list will not affect locations of another list.
 Cloning is a process of making a copy of the list without modifying the
original list.
1. Slicing
2. list()method
3. copy() method
Example:
cloning using Slicing
>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False
List
. clonning using list() method
>>>a=[1,2,3,4,5]
>>>b=list(a)
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using copy() method
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False
List
List as parameters
 Arguments are passed by reference.
 If any changes are done in the parameter, then the changes also
reflects back in the calling function.
 When a list to a function is passed, the function gets a reference to the
list.
 Passing a list as an argument actually passes a reference to the list, not
a copy of the list.
 Lists are mutable, changes made to the elements.
 Example
def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Output
[2,3,4,5]
List
. Example 2:
def inside(a):
for i in range(0,len(a),1):
a[i]=a[i]+10
print(“inner”,a)
a=[1,2,3,4,5]
inside(a)
print(“outer”,a)
output
inner [11, 12, 13, 14, 15]
outer [11, 12, 13, 14, 15]
Example3:
def insert(a):
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
output
[30, 1, 2, 3, 4, 5]
List
Practice
1.list=[‘p’,’r’,’I’,’n’,’t’]
print list[-3:]
Ans:
Error, no parenthesis in print statement.
2.Listout built-in functions.
Ans:
max(3,4),min(3,4),len(“raj”),range(2,8,1),round(7.8),float(5),int(5.0)
3.List is mutable-Justify
Ans:
List is an ordered sequence of items. Values in the list are called elements/items.
List is mutable. i.e. Values can be changed.
a=[1,2,3,4,5,6,7,8,9,10]
a[2]=100
print(a) -> [1,2,100,4,5,6,7,8,9,10]
Advanced list processing
List Comprehension
 List comprehensions provide a brief way to apply operations on a list.
 It creates a new list in which each element is the result of applying a
given operation in a list.
 It consists of brackets containing an expression followed by a “for”
clause, then a list.
 The list comprehension always returns a result list.
Syntax
list=[ expression for item in list if conditional ]
Advanced list processing
.
List Comprehension output
>>>L=[x**2 for x in range(0,5)]
>>>print(L)
[0, 1, 4, 9, 16]
>>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
>>>[x for x in 'Python Programming' if x in
['a','e','i','o','u']]
['o', 'o', 'a', 'i']
>>>mixed=[1,2,"a",3,4.2]
>>> [x**2 for x in mixed if type(x)==int]
[1, 4, 9]
>>>[x+3 for x in [1,2,3]] [4, 5, 6]
>>> [x*x for x in range(5)] [0, 1, 4, 9, 16]
>>> num=[-1,2,-3,4,-5,6,-7]
>>> [x for x in num if x>=0]
[2, 4, 6]
>>> str=["this","is","an","example"]
>>> element=[word[0] for word in str]
>>> print(element)
['t', 'i', 'a', 'e']
Nested list
 List inside another list is called nested list.
Example
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57
Tuple
 A tuple is same as list, except in parentheses instead of square
brackets.
 A tuple is an immutable list. i.e. can not be changed.
 Tuple can be converted into list and list can be converted in to tuple.
Benefit:
 Tuples are faster than lists.
 Tuple can be protected the data.
 Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Tuple
 . Operations Example Description
Creating a tuple
>>>a=(20,40,60,”raj”,”man”) Creating the tuple with different
data types.
Indexing
>>>print(a[0])
20
Accessing the item in the position
0
Slicing
>>>print(a[1:3])
(40,60)
Displaying elements from 1st to
2nd.
Concatenation
>>> b=(2,4)
>>>print(a+b)
>>>(20,40,60,”raj”,”man”,2,4)
Adding tuple elements.
Repetition
>>>print(b*2)
>>>(2,4,2,4)
Repeating the tuple
Membership
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
True
>>> 2 not in a
False
If element is present in tuple
returns TRUE else FALSE
Comparison
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4)
>>> a==b
False
If all elements in both tuple same
display TRUE else FALSE
Tuple
Tuple methods
 Tuple is immutable. i.e. changes cannot be done on the elements of a
tuple once it is assigned.
Methods Example Description
tuple.index(element)
>>> a=(1,2,3,4,5)
>>> a.index(5)
4
Display the index number of
element.
tuple.count(element)
>>>a=(1,2,3,4,5)
>>> a.count(3)
1
Number of count of the given
element.
len(tuple)
>>> len(a)
5
The length of the tuple
min(tuple)
>>> min(a)
1
The minimum element in a tuple
max(tuple)
>>>max(a)
5
The maximum element in a tuple
del(tuple) >>>del(a) Delete the tuple.
Tuple
Convert tuple into list
Convert list into tuple
Methods
Example
Description
list(tuple)
>>>a=(1,2,3,4,5)
>>>a=list(a)
>>>print(a)
[1, 2, 3, 4, 5]
Convert the given tuple into
list.
Methods
Example
Description
tuple(list)
>>> a=[1,2,3,4,5]
>>> a=tuple(a)
>>> print(a)
(1, 2, 3, 4, 5)
Convert the given list into
tuple.
Tuple
Tuple Assignment
 Tuple assignment allows, variables on the left of an assignment operator and
values on the right of the assignment operator.
 Multiple assignment works by creating a tuple of expressions from the right
hand side, and a tuple of targets from the left, and then matching each
expression to a target.
 It is useful to swap the values of two variables.
Example:
Swapping using temporary variable Swapping using tuple assignment
a=20
b=50
temp=a
a=b
b=temp
print("value after swapping is",a,b)
a=20
b=50
(a,b)=(b,a)
print("value after swapping is",a,b)
Tuple
Multiple assignments
 Multiple values can be assigned to multiple variables using tuple
assignment.
Example
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Tuple
Tuple as return value
 A Tuple is a comma separated sequence of items.
 It is created with or without ( ).
 A function can return one value.
 if you want to return more than one value from a function then use tuple
as return value.
Example:
Program to find quotient and reminder output
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
enter a value:5
enter b value:4
reminder: 1
quotient: 1
Tuple
Tuple as argument
 The parameter name that begins with * gathers argument into a tuple.
Example
def printall(*args):
print(args)
printall(2,3,'a')
Output:
(2, 3, 'a')
Dictionaries
 Dictionary is an unordered collection of elements.
 An element in dictionary has a key:value pair.
 All elements in dictionary are placed inside the curly braces i.e. { }
 Elements in Dictionaries are accessed via keys.
 The values of a dictionary can be any data type.
 Keys must be immutable data type.
Operations on dictionary
1. Accessing an element
2. Update
3. Add element
4. Membership
Dictionaries
 . Operations Example Description
Creating a
dictionary
>>> a={1:"one",2:"two"}
>>> print(a)
{1: 'one', 2: 'two'}
Creating the dictionary with
different data types.
Accessing an
element
>>> a[1]
'one'
>>> a[0]
KeyError: 0
Accessing the elements by
using keys.
Update
>>> a[1]="ONE"
>>> print(a)
{1: 'ONE', 2: 'two'}
Assigning a new value to key.
Add element
>>> a[3]="three"
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three'}
Add new element in to the
dictionary with key.
Membership
a={1: 'ONE', 2: 'two', 3: 'three'}
>>> 1 in a
True
>>> 3 not in a
False
If the key is present in
dictionary returns TRUE else
FALSE
Dictionaries
Methods in dictionary
Method Example Description
Dictionary.copy()
a={1: 'ONE', 2: 'two', 3: 'three'}
>>> b=a.copy()
>>> print(b)
{1: 'ONE', 2: 'two', 3: 'three'}
copy dictionary ’a’ to
dictionary ‘b’
Dictionary.items()
>>> a.items()
dict_items([(1, 'ONE'), (2,
'two'), (3, 'three')])
It displays a list of
dictionary’s (key, value) tuple
pairs.
Dictionary.key() >>> a.keys()
dict_keys([1, 2, 3])
Displays list of keys in a
dictionary.
Dictionary.values()
>>> a.values()
dict_values(['ONE', 'two',
'three'])
Displays list of values in a
dictionary.
Dictionary.pop(key
)
>>> a.pop(3)
'three'
>>> print(a)
{1: 'ONE', 2: 'two'}
Remove the element with
key.
Dictionaries
Try yourself
Dictionary.setdefault(key,value)
Dictionary.update(dictionary)
Dictionary.fromkeys(key,value)
len(Dictionary name)
Dictionary.clear()
del(Dictionary name)
Comparison of List, Tuples and Dictionary
. List Tuple Dictionary
A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are static Values can be of any
data type and can
repeat.
Keys must be of
immutable type
Homogenous Heterogeneous Homogenous
Slicing can be done Slicing can be done Slicing can't be done
Assignment
1.Addition of matrix
2.Multiplication of matrix
3.Transpose of matrix
4.Selection sort
5.Insertion sort
6.Merge sort
7.Histogram
email:mrajen@rediffmail.com
.

More Related Content

PPTX
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PPT
Stl Containers
PDF
Python File Handling | File Operations in Python | Learn python programming |...
PPTX
Stack and Queue
PDF
Python multithreaded programming
PDF
Python programming : List and tuples
PPTX
Modules in Python Programming
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Stl Containers
Python File Handling | File Operations in Python | Learn python programming |...
Stack and Queue
Python multithreaded programming
Python programming : List and tuples
Modules in Python Programming

What's hot (20)

PPTX
C# Delegates
PPTX
Sql clauses by Manan Pasricha
PDF
Chapter 0 Python Overview (Python Programming Lecture)
PPT
Bsc cs ii-dbms- u-iii-data modeling using e.r. model (entity relationship model)
PDF
Python - gui programming (tkinter)
PPTX
Object oriented programming with python
PPTX
Classes and Objects in C#
PDF
Python : Regular expressions
PPSX
Modules and packages in python
PPTX
PPT
Python Dictionaries and Sets
PPTX
Map, Filter and Reduce In Python
PDF
Core_Java_with_SCJP_OCJP_Notes_By_Durga.pdf
PDF
Python list
PPTX
Generators In Python
PPTX
SQL - DML and DDL Commands
PPTX
Ado.Net Tutorial
PPTX
Methods for handling deadlock
PPTX
Python: Modules and Packages
C# Delegates
Sql clauses by Manan Pasricha
Chapter 0 Python Overview (Python Programming Lecture)
Bsc cs ii-dbms- u-iii-data modeling using e.r. model (entity relationship model)
Python - gui programming (tkinter)
Object oriented programming with python
Classes and Objects in C#
Python : Regular expressions
Modules and packages in python
Python Dictionaries and Sets
Map, Filter and Reduce In Python
Core_Java_with_SCJP_OCJP_Notes_By_Durga.pdf
Python list
Generators In Python
SQL - DML and DDL Commands
Ado.Net Tutorial
Methods for handling deadlock
Python: Modules and Packages
Ad

Similar to Python for Beginners(v3) (20)

PPTX
Python _dataStructures_ List, Tuples, its functions
PPTX
Python list tuple dictionary .pptx
PPTX
Python Programming for BCS Degree UNIT -4.pptx
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PPT
UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON
PDF
Python Programming: Lists, Modules, Exceptions
PPTX
Pythonlearn-08-Lists.pptx
PDF
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
PPT
Python List.ppt
PPTX
Chapter 15 Lists
PDF
Slicing in Python - What is It?
PDF
Lists and its functions in python for beginners
PPTX
Brief Explanation On List and Dictionaries of Python
PDF
PPTX
Python for the data science most in cse.pptx
PPTX
Python lists
PPTX
institute of techonolgy and education tr
PPTX
Pythonlearn-08-Lists (1).pptxaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
PPTX
List_tuple_dictionary.pptx
Python _dataStructures_ List, Tuples, its functions
Python list tuple dictionary .pptx
Python Programming for BCS Degree UNIT -4.pptx
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON
Python Programming: Lists, Modules, Exceptions
Pythonlearn-08-Lists.pptx
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
Python List.ppt
Chapter 15 Lists
Slicing in Python - What is It?
Lists and its functions in python for beginners
Brief Explanation On List and Dictionaries of Python
Python for the data science most in cse.pptx
Python lists
institute of techonolgy and education tr
Pythonlearn-08-Lists (1).pptxaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
List_tuple_dictionary.pptx
Ad

More from Panimalar Engineering College (8)

PPTX
Python for Data Science
PPTX
Python for Beginners(v2)
PPTX
Python for Beginners(v1)
PPTX
Introduction to Machine Learning
PPTX
PPTX
PPTX
PPT
Multiplexing,LAN Cabling,Routers,Core and Distribution Networks
Python for Data Science
Python for Beginners(v2)
Python for Beginners(v1)
Introduction to Machine Learning
Multiplexing,LAN Cabling,Routers,Core and Distribution Networks

Recently uploaded (20)

PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
Updated Idioms and Phrasal Verbs in English subject
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Cell Structure & Organelles in detailed.
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
History, Philosophy and sociology of education (1).pptx
Microbial disease of the cardiovascular and lymphatic systems
Practical Manual AGRO-233 Principles and Practices of Natural Farming
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
UNIT III MENTAL HEALTH NURSING ASSESSMENT
Chinmaya Tiranga quiz Grand Finale.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Orientation - ARALprogram of Deped to the Parents.pptx
Computing-Curriculum for Schools in Ghana
Updated Idioms and Phrasal Verbs in English subject
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Cell Structure & Organelles in detailed.
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Paper A Mock Exam 9_ Attempt review.pdf.
STATICS OF THE RIGID BODIES Hibbelers.pdf
Weekly quiz Compilation Jan -July 25.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Complications of Minimal Access Surgery at WLH
History, Philosophy and sociology of education (1).pptx

Python for Beginners(v3)

  • 1. Python for Beginners(v3) Dr.M.Rajendiran Dept. of Computer Science and Engineering Panimalar Engineering College
  • 2. Install Python 3 On Ubuntu Prerequisites Step 1.A system running Ubuntu Step 2.A user account with sudo privileges Step 3.Access to a terminal command-line (Ctrl–Alt–T) Step 4.Make sure your environment is configured to use Python 3.8 2
  • 3. Install Python 3 Now you can start the installation of Python 3.8. $sudo apt install python3.8 Allow the process to complete and verify the Python version was installed successfully $python ––version 3
  • 4. Installing and using Python on Windows is very simple. Step 1: Download the Python Installer binaries Step 2: Run the Executable Installer Step 3: Add Python to environmental variables Step 4: Verify the Python Installation 4
  • 5. Python Installation Open the Python website in your web browser. https://www.python.org/downloads/windows/ Once the installer is downloaded, run the Python installer. Add the following path C:Program FilesPython37-32: for 64-bit installation Once the installation is over, you will see a Python Setup Successful window. You are ready to start developing Python applications in your Windows 10 system. 5
  • 6. iPython Installation If you already have Python installed, you can use pip to install iPython using the following command: $pip install iPython To use it, type the following command in your computer’s terminal: $ipython 6
  • 7. Compound Data Type List  List is an ordered sequence of items. Values in the list are called elements.  List of values separated by commas within square brackets[ ].  Items in the lists can be of different data types. Tuples  A tuple is same as list.  The set of elements is enclosed in parentheses.  A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a tuple or remove elements from the tuple.  Tuple can be converted into list and list can be converted in to tuple.
  • 8. Compound Data Type Dictionary  Dictionary is an unordered collection of elements.  An element in dictionary has a key: value pair.  All elements in dictionary are placed inside the curly braces{ }  Elements in dictionaries are accessed via keys and not by their position.  The values of a dictionary can be any data type.  Keys must be immutable data type.
  • 9. List 1.List operations 2.List slices 3.List methods 4.List loop 5.Mutability 6.Aliasing 7.Cloning lists 8.List parameters
  • 10. List Operations on list 1. Indexing 2. Slicing 3. Concatenation 4. Repetitions 5. Updating 6. Membership 7. Comparison
  • 11. List . Operation Example Description create a list >>> a=[2,3,4,5,6,7,8,9,10] >>> print(a) [2, 3, 4, 5, 6, 7, 8, 9, 10] we can create a list at compile time Indexing >>> print(a[0]) 2 >>> print(a[8]) 10 >>> print(a[-1]) 10 Accessing the item in the position 0 Accessing the item in the position 8 Accessing a last element using negative indexing. Slicing >>> print(a[0:3]) [2, 3, 4] >>> print(a[0:]) [2, 3, 4, 5, 6, 7, 8, 9, 10] Printing a part of the list. Concatenation >>>b=[20,30] >>> print(a+b) [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30] Adding and printing the items of two lists. Repetition >>> print(b*3) [20, 30, 20, 30, 20, 30] Create a multiple copies of the same list. Updating >>> print(a[2]) 4 >>> a[2]=100 >>> print(a) [2, 3, 100, 5, 6, 7, 8, 9, 10] Updating the list using index value.
  • 12. List List slices List slicing is an operation that extracts a subset of elements from an list. Operation Example Description Membership >>> a=[2,3,4,5,6,7,8,9,10] >>> 5 in a True >>> 100 in a False >>> 2 not in a False Returns True if element is present in list. Otherwise returns false. Comparison >>> a=[2,3,4,5,6,7,8,9,10] >>>b=[2,3,4] >>> a==b False >>> a!=b True Returns True if all elements in both elements are same. Otherwise returns false
  • 13. List Syntax listname[start:stop] listname[start:stop:steps]  Default start value is 0  Default stop value is n-1  [:] this will print the entire list  [2:2] this will create a empty slice slices example Slices Example Description a[0:3] >>> a=[9,8,7,6,5,4] >>> a[0:3] [9, 8, 7] Printing a part of a list from 0 to 2. a[:4] >>> a[:4] [9, 8, 7, 6] Default start value is 0. so prints from 0 to 3 a[1:] >>> a[1:] [8, 7, 6, 5, 4] Default stop value will be n-1. so prints from 1 to 5
  • 14. List List methods  Methods used in lists are used to manipulate the data quickly.  These methods work only on lists.  They do not work on the other sequence types that are not mutable, that is, the values cannot be changed. Syntax list name.method name( element/index/list) Slices Example Description list.append(element) >>> a=[1,2,3,4,5] >>> a.append(6) >>> print(a) [1, 2, 3, 4, 5, 6] Add an element to the end of the list list.insert(index,element ) >>> a.insert(0,0) >>> print(a) [0, 1, 2, 3, 4, 5, 6] Insert an item at the defined index min(list) >>> min(a) 2 Return the minimum element in a list
  • 15. List . Syntax Example Description list.extend(b) >>> b=[7,8,9] >>> a.extend(b) >>> print(a) [0, 1, 2, 3, 4, 5, 6, 7, 8,9] Add all elements of a list to the another list list,index(element) >>> a.index(8) 8 Returns the index of the element list.sort() >>> a.sort() >>> print(a) [0, 1, 2, 3, 4, 5, 6, 7, 8,9] Sort items in a list list.reverse() >>> a.reverse() >>> print(a) [9,8, 7, 6, 5, 4, 3, 2, 1, 0] Reverse the order. list.remove(element) >>> a.remove(0) >>> print(a) [9,8,7, 6, 5, 4, 3, 2,1] Removes an item from the list list.copy() >>> b=a.copy() >>> print(b) [9,8,7, 6, 5, 4, 3, 2,1] Copy from a to b len(list) >>>len(a) 9 Length of the list
  • 17. List List loops 1. for loop 2. while loop 3. infinite loop for Loop  The for loop in python is used to iterate over a sequence (list, tuple, string) or other iterable objects.  Iterating over a sequence is called traversal.  Loop continues until we reach the last item in the sequence.  The body of for loop is separated from the rest of the code using indentation. Syntax: for variable in sequence:
  • 18. List Example Accessing element a=[10,20,30,40,50] for i in a: print(i) Output 10 20 30 40 50 Accessing index output a=[10,20,30,40,50] for i in range(0,len(a),1): print(i) output 0 1 2 3 4 Accessing element using range a=[10,20,30,40,50] for i in range(0,len(a),1): print(a[i]) ---------------------------------------------------------- print(id(a[i])) # for memory address output 10 20 30 40 50
  • 19. List While loop  The while loop is used to iterate over a block of code as long as the test condition is true.  When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Syntax: while (condition): body of the statement Example: Sum of the elements in list a=[1,2,3,4,5] i=0 sum=0 while i<len(a): sum=sum+a[i] i=i+1 print(sum) Output 15
  • 20. List infinite Loop  A loop becomes infinite loop if the condition becomes false.  It keeps on running. Such loops are called infinite loop. Example: a=1 while (a==1): n=int(input("enter the number")) print("you entered:" , n) Output Enter the number 10 you entered:10 Enter the number 12 you entered:12 Enter the number 16 you entered:16
  • 21. List Mutability  Lists are mutable.(It can be changed)  Mutability is the ability for certain types of data to be changed without entirely recreating it.  An item can be changed in a list by accessing it directly as part of the assignment statement.  Using the indexing operator on the left side of an assignment, one of the list items can be updated.  Example: >>> a=[1,2,3,4,5] >>> a[0]=100 >>> print(a) [100, 2, 3, 4, 5] changing single element >>> a=[1,2,3,4,5] >>> a[0:3]=[100,100,100] >>> print(a) [100, 100, 100, 4, 5] changing multiple element
  • 22. List Aliasing(copying)  Creating a copy of a list is called aliasing.  When you create a copy both list will be having same memory location.  Changes in one list will affect another list.  Aliasing refers to having different names for same list values. Example: a= [1, 2, 3 ,4 ,5] b=a print (b) a is b a[0]=100 print(a) print(b) [1, 2, 3, 4, 5] [100,2,3,4,5] [100,2,3,4,5]
  • 23. List Cloning  Creating a copy of a same list of elements with different memory locations is called cloning.  Changes in one list will not affect locations of another list.  Cloning is a process of making a copy of the list without modifying the original list. 1. Slicing 2. list()method 3. copy() method Example: cloning using Slicing >>>a=[1,2,3,4,5] >>>b=a[:] >>>print(b) [1,2,3,4,5] >>>a is b False
  • 24. List . clonning using list() method >>>a=[1,2,3,4,5] >>>b=list(a) >>>print(b) [1,2,3,4,5] >>>a is b false >>>a[0]=100 >>>print(a) >>>a=[100,2,3,4,5] >>>print(b) >>>b=[1,2,3,4,5] clonning using copy() method a=[1,2,3,4,5] >>>b=a.copy() >>> print(b) [1, 2, 3, 4, 5] >>> a is b False
  • 25. List List as parameters  Arguments are passed by reference.  If any changes are done in the parameter, then the changes also reflects back in the calling function.  When a list to a function is passed, the function gets a reference to the list.  Passing a list as an argument actually passes a reference to the list, not a copy of the list.  Lists are mutable, changes made to the elements.  Example def remove(a): a.remove(1) a=[1,2,3,4,5] remove(a) print(a) Output [2,3,4,5]
  • 26. List . Example 2: def inside(a): for i in range(0,len(a),1): a[i]=a[i]+10 print(“inner”,a) a=[1,2,3,4,5] inside(a) print(“outer”,a) output inner [11, 12, 13, 14, 15] outer [11, 12, 13, 14, 15] Example3: def insert(a): a.insert(0,30) a=[1,2,3,4,5] insert(a) print(a) output [30, 1, 2, 3, 4, 5]
  • 27. List Practice 1.list=[‘p’,’r’,’I’,’n’,’t’] print list[-3:] Ans: Error, no parenthesis in print statement. 2.Listout built-in functions. Ans: max(3,4),min(3,4),len(“raj”),range(2,8,1),round(7.8),float(5),int(5.0) 3.List is mutable-Justify Ans: List is an ordered sequence of items. Values in the list are called elements/items. List is mutable. i.e. Values can be changed. a=[1,2,3,4,5,6,7,8,9,10] a[2]=100 print(a) -> [1,2,100,4,5,6,7,8,9,10]
  • 28. Advanced list processing List Comprehension  List comprehensions provide a brief way to apply operations on a list.  It creates a new list in which each element is the result of applying a given operation in a list.  It consists of brackets containing an expression followed by a “for” clause, then a list.  The list comprehension always returns a result list. Syntax list=[ expression for item in list if conditional ]
  • 29. Advanced list processing . List Comprehension output >>>L=[x**2 for x in range(0,5)] >>>print(L) [0, 1, 4, 9, 16] >>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8] >>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i'] >>>mixed=[1,2,"a",3,4.2] >>> [x**2 for x in mixed if type(x)==int] [1, 4, 9] >>>[x+3 for x in [1,2,3]] [4, 5, 6] >>> [x*x for x in range(5)] [0, 1, 4, 9, 16] >>> num=[-1,2,-3,4,-5,6,-7] >>> [x for x in num if x>=0] [2, 4, 6] >>> str=["this","is","an","example"] >>> element=[word[0] for word in str] >>> print(element) ['t', 'i', 'a', 'e']
  • 30. Nested list  List inside another list is called nested list. Example >>> a=[56,34,5,[34,57]] >>> a[0] 56 >>> a[3] [34, 57] >>> a[3][0] 34 >>> a[3][1] 57
  • 31. Tuple  A tuple is same as list, except in parentheses instead of square brackets.  A tuple is an immutable list. i.e. can not be changed.  Tuple can be converted into list and list can be converted in to tuple. Benefit:  Tuples are faster than lists.  Tuple can be protected the data.  Tuples can be used as keys in dictionaries, while lists can't. Operations on Tuples: 1. Indexing 2. Slicing 3. Concatenation 4. Repetitions 5. Membership 6. Comparison
  • 32. Tuple  . Operations Example Description Creating a tuple >>>a=(20,40,60,”raj”,”man”) Creating the tuple with different data types. Indexing >>>print(a[0]) 20 Accessing the item in the position 0 Slicing >>>print(a[1:3]) (40,60) Displaying elements from 1st to 2nd. Concatenation >>> b=(2,4) >>>print(a+b) >>>(20,40,60,”raj”,”man”,2,4) Adding tuple elements. Repetition >>>print(b*2) >>>(2,4,2,4) Repeating the tuple Membership >>> a=(2,3,4,5,6,7,8,9,10) >>> 5 in a True >>> 2 not in a False If element is present in tuple returns TRUE else FALSE Comparison >>> a=(2,3,4,5,6,7,8,9,10) >>>b=(2,3,4) >>> a==b False If all elements in both tuple same display TRUE else FALSE
  • 33. Tuple Tuple methods  Tuple is immutable. i.e. changes cannot be done on the elements of a tuple once it is assigned. Methods Example Description tuple.index(element) >>> a=(1,2,3,4,5) >>> a.index(5) 4 Display the index number of element. tuple.count(element) >>>a=(1,2,3,4,5) >>> a.count(3) 1 Number of count of the given element. len(tuple) >>> len(a) 5 The length of the tuple min(tuple) >>> min(a) 1 The minimum element in a tuple max(tuple) >>>max(a) 5 The maximum element in a tuple del(tuple) >>>del(a) Delete the tuple.
  • 34. Tuple Convert tuple into list Convert list into tuple Methods Example Description list(tuple) >>>a=(1,2,3,4,5) >>>a=list(a) >>>print(a) [1, 2, 3, 4, 5] Convert the given tuple into list. Methods Example Description tuple(list) >>> a=[1,2,3,4,5] >>> a=tuple(a) >>> print(a) (1, 2, 3, 4, 5) Convert the given list into tuple.
  • 35. Tuple Tuple Assignment  Tuple assignment allows, variables on the left of an assignment operator and values on the right of the assignment operator.  Multiple assignment works by creating a tuple of expressions from the right hand side, and a tuple of targets from the left, and then matching each expression to a target.  It is useful to swap the values of two variables. Example: Swapping using temporary variable Swapping using tuple assignment a=20 b=50 temp=a a=b b=temp print("value after swapping is",a,b) a=20 b=50 (a,b)=(b,a) print("value after swapping is",a,b)
  • 36. Tuple Multiple assignments  Multiple values can be assigned to multiple variables using tuple assignment. Example >>>(a,b,c)=(1,2,3) >>>print(a) 1 >>>print(b) 2 >>>print(c) 3
  • 37. Tuple Tuple as return value  A Tuple is a comma separated sequence of items.  It is created with or without ( ).  A function can return one value.  if you want to return more than one value from a function then use tuple as return value. Example: Program to find quotient and reminder output def div(a,b): r=a%b q=a//b return(r,q) a=eval(input("enter a value:")) b=eval(input("enter b value:")) r,q=div(a,b) print("reminder:",r) print("quotient:",q) enter a value:5 enter b value:4 reminder: 1 quotient: 1
  • 38. Tuple Tuple as argument  The parameter name that begins with * gathers argument into a tuple. Example def printall(*args): print(args) printall(2,3,'a') Output: (2, 3, 'a')
  • 39. Dictionaries  Dictionary is an unordered collection of elements.  An element in dictionary has a key:value pair.  All elements in dictionary are placed inside the curly braces i.e. { }  Elements in Dictionaries are accessed via keys.  The values of a dictionary can be any data type.  Keys must be immutable data type. Operations on dictionary 1. Accessing an element 2. Update 3. Add element 4. Membership
  • 40. Dictionaries  . Operations Example Description Creating a dictionary >>> a={1:"one",2:"two"} >>> print(a) {1: 'one', 2: 'two'} Creating the dictionary with different data types. Accessing an element >>> a[1] 'one' >>> a[0] KeyError: 0 Accessing the elements by using keys. Update >>> a[1]="ONE" >>> print(a) {1: 'ONE', 2: 'two'} Assigning a new value to key. Add element >>> a[3]="three" >>> print(a) {1: 'ONE', 2: 'two', 3: 'three'} Add new element in to the dictionary with key. Membership a={1: 'ONE', 2: 'two', 3: 'three'} >>> 1 in a True >>> 3 not in a False If the key is present in dictionary returns TRUE else FALSE
  • 41. Dictionaries Methods in dictionary Method Example Description Dictionary.copy() a={1: 'ONE', 2: 'two', 3: 'three'} >>> b=a.copy() >>> print(b) {1: 'ONE', 2: 'two', 3: 'three'} copy dictionary ’a’ to dictionary ‘b’ Dictionary.items() >>> a.items() dict_items([(1, 'ONE'), (2, 'two'), (3, 'three')]) It displays a list of dictionary’s (key, value) tuple pairs. Dictionary.key() >>> a.keys() dict_keys([1, 2, 3]) Displays list of keys in a dictionary. Dictionary.values() >>> a.values() dict_values(['ONE', 'two', 'three']) Displays list of values in a dictionary. Dictionary.pop(key ) >>> a.pop(3) 'three' >>> print(a) {1: 'ONE', 2: 'two'} Remove the element with key.
  • 43. Comparison of List, Tuples and Dictionary . List Tuple Dictionary A list is mutable A tuple is immutable A dictionary is mutable Lists are dynamic Tuples are static Values can be of any data type and can repeat. Keys must be of immutable type Homogenous Heterogeneous Homogenous Slicing can be done Slicing can be done Slicing can't be done
  • 44. Assignment 1.Addition of matrix 2.Multiplication of matrix 3.Transpose of matrix 4.Selection sort 5.Insertion sort 6.Merge sort 7.Histogram email:[email protected]
  • 45. .