SlideShare a Scribd company logo
Programming in Python
Tiji Thomas
HOD
Department of Computer Applications
MACFAST
Jointly organized by
Dept. of Computer Applications, MACFAST
KSCSTE
&
UNAI , Computer Society of India (CSI)
MAR ATHANASIOS COLLEGE FOR ADVANCED STUDIES TIRUVALLA
(MACFAST)
UNAI-MACFAST-ASPIRE
Taliparamba Arts & Science College
Accredited by NAAC with A grade
Introduction
 Python is a general-purpose interpreted, object-
oriented, and high-level programming language.
 What can we do with Python –Web Development , ,
Desktop Applications, Data Science , Machine
Learning , Computer Games , NLP etc.
 Python supports many databases (SQLite, Sqlite,
Oracle, Sybase, PostgreSQL etc.)
 Python is an open source software
 Google, Instagram, YouTube , Quora etc
Executing a Python Program
a) Command Prompt
• print “Hello World”
• b)IDLE
1. Run IDLE. ...
2. Click File, New Window. ...
3. Enter your script and save file with . Python files have a
file extension of ".py"
4. Select Run, Run Module (or press F5) to run your script.
5. The "Python Shell" window will display the output of your
script.
Reading Keyboard Input
• Python provides two built-in functions to read a line of text from
standard input, which by default comes from the keyboard. These
functions are −
• raw_input
• input
• The raw_input Function
• The raw_input([prompt]) function reads one line
from standard input and returns it as a string
(removing the trailing newline).
str = raw_input("Enter your input: ");
print "Received input is : ", str
• The input Function
• The input([prompt]) function is equivalent to
raw_input, except that it assumes the input is a
valid Python expression and returns the evaluated
result to you.
str = input("Enter your input: ");
print "Received input is : ", str
Python Decision Making
Statement Description
if statements
An if statement consists of a boolean expression
followed by one or more statements.
if...else statements
An if statement can be followed by an optional
else statement, which executes when the boolean
expression is FALSE.
If .. elif
You can use one if or else if statement inside
another if or else if statement(s).
Indentation
• Python provides no braces to indicate blocks of
code for class and function definitions or flow
control. Blocks of code are denoted by line
indentation
if True:
print "True"
else:
print "False"
Python Loops
• while - loops through a block of code if and as long
as a specified condition is true
• for - loops through a block of code a specified
number of times
Example - while
#Display first n numbers
n=input("Enter value for n ")
i=1
while i<=n:
print i
i= i + 1
Example for
#for loop example
str= “Python”
for letter in str:
print 'Current Letter :', letter
Standard Data Types
• Python has five standard data types −
• Numbers
• String
• List
• Tuple
• Dictionary
Strings
• Set of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes
• str = 'Hello World!'
• print str # Prints complete string
• print str[0] # Prints first character of the string
• print str[2:5] # Prints characters starting from 3rd to 5th
• print str[2:] # Prints string starting from 3rd character
• print str * 2 # Prints string two times
• print str + "TEST" # Prints concatenated string
Python Lists
• A list contains items separated by commas and enclosed within
square brackets ([]). To some extent, lists are similar to arrays in C.
One difference between them is that all the items belonging to a
list can be of different data type.
• list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
ls = [123, 'john']
• print list # Prints complete list
• print list[0] # Prints first element of the list
• print list[1:3] # Prints elements starting from 2nd till 3rd
• print list[2:] # Prints elements starting from 3rd element
• print ls * 2 # Prints list two times
• print list + ls # Prints concatenated lists
Python Lists
• Add elements to a list
1. mylist.append(10)
2. mylist.extend(["Raju",20,30])
3. mylist.insert(1,"Ammu")
• Search within lists -mylist.index('Anu’)
• Delete elements from a list - mylist.remove(20)
range function
• The built-in range function in Python is very useful
to generate sequences of numbers in the form of a
list.
• The given end point is never part of the generated
list;
Basic list operations
Length - len
Concatenation : +
Repetition - ['Hi!'] * 4
Membership - 3 in [1, 2, 3]
Iteration- for x in [1, 2, 3]: print x,
Sorting an array - list.sort()
fruits = ["lemon", "orange", "banana", "apple"]
print fruits
fruits.sort()
for i in fruits:
print i
print "nnnReverse ordernnn"
fruits.sort(reverse=True)
for i in fruits:
print i
Python Tuples
• A tuple consists of a number of values separated by
commas. Tuples are enclosed within parentheses.
• The main differences between lists and tuples are:
Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be
updated.
• read-only lists
Tuple Example
• tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
• tinytuple = (123, 'john')
• print tuple # Prints complete list
• print tuple[0] # Prints first element of the list
• print tuple[1:3] # Prints elements starting from 2nd till 3rd
• print tuple[2:] # Prints elements starting from 3rd element
• print tinytuple * 2 # Prints list two times
• print tuple + tinytuple # Prints concatenated lists
Operations on Tuple
• 1 Accessing Values in Tuples
• 2 Updating Tuples - not possible
• 3 Delete Tuple Elements - not possible
• 4 Create new tuple from existing tuples is possible
• Functions - cmp ,len , max , min
Python Dictionary
• Python's dictionaries are kind of hash table type.
They work like associative arrays or hashes found in
Perl and consist of key-value pairs
• Dictionaries are enclosed by curly braces ({ }) and
values can be assigned and accessed using square
braces ([]).
Example
• dict = {}
• dict['one'] = "This is one"
• dict[2] = "This is two"
• tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
• print dict['one'] # Prints value for 'one' key
• print dict[2] # Prints value for 2 key
• print tinydict # Prints complete dictionary
• print tinydict.keys() # Prints all the keys
• print tinydict.values() # Prints all the values
Python Functions
• Function blocks begin with the keyword def followed
by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed
within these parentheses.
• The first statement of a function can be an optional
statement - the documentation string of the function or
docstring.
.
• The statement return [expression] exits a function,
optionally passing back an expression to the caller. A
return statement with no arguments is the same as
return None.
Example -1
Function for find maximum of two numbers
Example -2
Function for Read and Display list
Example -3
Function for search in a list
Example -4
Function for prime numbers
Opening a File
• The open() function is used to open files in Python.
• The first parameter of this function contains the
name of the file to be opened and the second
parameter specifies in which mode the file should
be opened
Example
• File=open(“macfast.txt” , “w”)
Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or
creates a new file if it doesn't exist
w+ Read/Write. Opens and clears the contents of file; or
creates a new file if it doesn't exist
a Append. Opens and writes to the end of the file or creates
a new file if it doesn't exist
a+ Read/Append. Preserves file content by writing to the end
of the file
• Opening and Closing Files
• The open Function
file object = open(file_name [, access_mode][, buffering])
• file_name: The file_name argument is a string value that
contains the name of the file that you want to access.
• access_mode: The access_mode determines the mode in
which the file has to be opened, i.e., read, write, append,
etc.
• The close() Method
The close() method of a file object flushes any unwritten
information and closes the file object, after which no more
writing can be done.
• The write() Method
• The write() method writes any string to an open file
• The write() method does not add a newline
character ('n') to the end of the string −
# Open a file
file = open(“test.txt", "wb")
file.write( “ Two day workshop on Python ");
# Close opend file
File.close()
• The read() Method
• The read() method reads a string from an open file.
f= open(“test.txt", "r")
str = f.read();
print str
fo.close()
Regular Expression
• Regular expressions are essentially a tiny, highly
specialized programming language embedded
inside Python and made available through the re
module.
• Regular expressions are useful in a wide variety of
text processing tasks, and more generally string
processing
• Data validation
• Data scraping (especially web scraping),
• Data wrangling,
• Parsing,
• Syntax highlighting systems
Various methods of Regular Expressions
The ‘re’ package provides multiple methods to
perform queries on an input string. Here are the
most commonly used methods
1.re.match()
2.re.search()
3.re.findall()
4.re.split()
5.re.sub()
re.match()
This method finds match if it occurs at start of the
string
str='MCA , MBA , BCA , BBA'
re.match('MCA' , str)
re.match("MBA" , str)
re.search()
search() method is able to find a pattern from any
position of the string but it only returns the first
occurrence of the search pattern.
Re.findall
• findall helps to get a list of all matching patterns
import re
str='MCA , MBA , BCA , BBA , MSC'
result =re.findall (r"Mww" , str)
if result:
for i in result:
print i
else:
print "Not Found"
Finding all Adverbs
import re
file= open(‘story.txt' , "r")
str=file.read();
result=re.findall(r"w+ly",str)
for i in result:
print i
re.split()
This methods helps to split string by the occurrences
of given pattern.
import re
str = 'MCA MBA BCA MSC BBA BSc'
result=re.split(" ",str)
for i in result:
print i
re.sub(pattern, repl, string)
• It helps to search a pattern and replace with a new
sub string. If the pattern is not found, string is
returned unchanged.
import re
str = 'BCA BSc BCA'
print str
result=re.sub(r"B", "M" , str)
print "After replacement"
print result
Change gmail.com to macfast.org
using re.sub()
import re
str = "tiji@gmail.com ,anju@gmail.com ,anu@gmail.com"
print str
newstr= re.sub(r"@w+.com" , "@macfast.org" , str)
print "Change gmail.com to macfast.org "
print newstr
Project -1
•Extract information from an
Excel file using Python
What is SQLite?
SQLite is an embedded SQL database engine
•SQLite is ideal for both small and large
applications
•SQLite supports standard SQL
•Open source software
Connection to a SQLite Database
import sqlite3
conn = sqlite3.connect('example.db')
Once you have a Connection, you can create a
Cursor object and call its execute() method to
perform SQL commands:
c = conn.cursor()
Project
Student Information System(SIS)
Insert Data -> insertdata.py
Update Data -> updatedata.py
Delete Data ->deletedata.py
Display Students List ->list.py
Thank You

More Related Content

What's hot

Why Python?
Why Python?Why Python?
Why Python?
Adam Pah
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
vikram mahendra
 
Python : Data Types
Python : Data TypesPython : Data Types
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Numpy tutorial
Numpy tutorialNumpy tutorial
Numpy tutorial
HarikaReddy115
 
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String MethodsPython Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
Praveen M Jigajinni
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
Edureka!
 
Python ppt
Python pptPython ppt
Python ppt
Anush verma
 
NumPy
NumPyNumPy
Python programming
Python programmingPython programming
Python programming
Keshav Gupta
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
Priyanka Pradhan
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1
Nicholas I
 

What's hot (20)

Why Python?
Why Python?Why Python?
Why Python?
 
Python basic
Python basicPython basic
Python basic
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python programming
Python  programmingPython  programming
Python programming
 
Numpy tutorial
Numpy tutorialNumpy tutorial
Numpy tutorial
 
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String MethodsPython Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Python ppt
Python pptPython ppt
Python ppt
 
NumPy
NumPyNumPy
NumPy
 
Python programming
Python programmingPython programming
Python programming
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1
 

Similar to Programming in Python

manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
ssuser92d141
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
ALOK52916
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
VishwasKumar58
 
Python Basics
Python BasicsPython Basics
Python Basics
MobeenAhmed25
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
RajPurohit33
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
RalAnteloJurado
 
Learn Python in Three Hours - Presentation
Learn Python in Three Hours - PresentationLearn Python in Three Hours - Presentation
Learn Python in Three Hours - Presentation
Naseer-ul-Hassan Rehman
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
kashifmajeedjanjua
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
GeorgePama1
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
SATHYANARAYANAKB
 
Introductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.pptIntroductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.ppt
HiralPatel798996
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
RedenOriola
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
AshokRachapalli1
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
JemuelPinongcos1
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
Aditya Shankar
 
Kavitha_python.ppt
Kavitha_python.pptKavitha_python.ppt
Kavitha_python.ppt
KavithaMuralidharan2
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
arivukarasi2
 
1. python programming
1. python programming1. python programming
1. python programming
sreeLekha51
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 

Similar to Programming in Python (20)

ENGLISH PYTHON.ppt
ENGLISH PYTHON.pptENGLISH PYTHON.ppt
ENGLISH PYTHON.ppt
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python Basics
Python BasicsPython Basics
Python Basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
 
Learn Python in Three Hours - Presentation
Learn Python in Three Hours - PresentationLearn Python in Three Hours - Presentation
Learn Python in Three Hours - Presentation
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Introductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.pptIntroductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
 
Kavitha_python.ppt
Kavitha_python.pptKavitha_python.ppt
Kavitha_python.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
1. python programming
1. python programming1. python programming
1. python programming
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
 

Recently uploaded

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
gb193092
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 

Recently uploaded (20)

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 

Programming in Python

  • 1. Programming in Python Tiji Thomas HOD Department of Computer Applications MACFAST
  • 2. Jointly organized by Dept. of Computer Applications, MACFAST KSCSTE & UNAI , Computer Society of India (CSI) MAR ATHANASIOS COLLEGE FOR ADVANCED STUDIES TIRUVALLA (MACFAST) UNAI-MACFAST-ASPIRE Taliparamba Arts & Science College Accredited by NAAC with A grade
  • 3. Introduction  Python is a general-purpose interpreted, object- oriented, and high-level programming language.  What can we do with Python –Web Development , , Desktop Applications, Data Science , Machine Learning , Computer Games , NLP etc.  Python supports many databases (SQLite, Sqlite, Oracle, Sybase, PostgreSQL etc.)  Python is an open source software  Google, Instagram, YouTube , Quora etc
  • 4. Executing a Python Program a) Command Prompt • print “Hello World” • b)IDLE 1. Run IDLE. ... 2. Click File, New Window. ... 3. Enter your script and save file with . Python files have a file extension of ".py" 4. Select Run, Run Module (or press F5) to run your script. 5. The "Python Shell" window will display the output of your script.
  • 5. Reading Keyboard Input • Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are − • raw_input • input • The raw_input Function • The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline). str = raw_input("Enter your input: "); print "Received input is : ", str
  • 6. • The input Function • The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you. str = input("Enter your input: "); print "Received input is : ", str
  • 7. Python Decision Making Statement Description if statements An if statement consists of a boolean expression followed by one or more statements. if...else statements An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE. If .. elif You can use one if or else if statement inside another if or else if statement(s).
  • 8. Indentation • Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation if True: print "True" else: print "False"
  • 9. Python Loops • while - loops through a block of code if and as long as a specified condition is true • for - loops through a block of code a specified number of times
  • 10. Example - while #Display first n numbers n=input("Enter value for n ") i=1 while i<=n: print i i= i + 1
  • 11. Example for #for loop example str= “Python” for letter in str: print 'Current Letter :', letter
  • 12. Standard Data Types • Python has five standard data types − • Numbers • String • List • Tuple • Dictionary
  • 13. Strings • Set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes • str = 'Hello World!' • print str # Prints complete string • print str[0] # Prints first character of the string • print str[2:5] # Prints characters starting from 3rd to 5th • print str[2:] # Prints string starting from 3rd character • print str * 2 # Prints string two times • print str + "TEST" # Prints concatenated string
  • 14. Python Lists • A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. • list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] ls = [123, 'john'] • print list # Prints complete list • print list[0] # Prints first element of the list • print list[1:3] # Prints elements starting from 2nd till 3rd • print list[2:] # Prints elements starting from 3rd element • print ls * 2 # Prints list two times • print list + ls # Prints concatenated lists
  • 15. Python Lists • Add elements to a list 1. mylist.append(10) 2. mylist.extend(["Raju",20,30]) 3. mylist.insert(1,"Ammu") • Search within lists -mylist.index('Anu’) • Delete elements from a list - mylist.remove(20)
  • 16. range function • The built-in range function in Python is very useful to generate sequences of numbers in the form of a list. • The given end point is never part of the generated list;
  • 17. Basic list operations Length - len Concatenation : + Repetition - ['Hi!'] * 4 Membership - 3 in [1, 2, 3] Iteration- for x in [1, 2, 3]: print x,
  • 18. Sorting an array - list.sort() fruits = ["lemon", "orange", "banana", "apple"] print fruits fruits.sort() for i in fruits: print i print "nnnReverse ordernnn" fruits.sort(reverse=True) for i in fruits: print i
  • 19. Python Tuples • A tuple consists of a number of values separated by commas. Tuples are enclosed within parentheses. • The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. • read-only lists
  • 20. Tuple Example • tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) • tinytuple = (123, 'john') • print tuple # Prints complete list • print tuple[0] # Prints first element of the list • print tuple[1:3] # Prints elements starting from 2nd till 3rd • print tuple[2:] # Prints elements starting from 3rd element • print tinytuple * 2 # Prints list two times • print tuple + tinytuple # Prints concatenated lists
  • 21. Operations on Tuple • 1 Accessing Values in Tuples • 2 Updating Tuples - not possible • 3 Delete Tuple Elements - not possible • 4 Create new tuple from existing tuples is possible • Functions - cmp ,len , max , min
  • 22. Python Dictionary • Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
  • 23. Example • dict = {} • dict['one'] = "This is one" • dict[2] = "This is two" • tinydict = {'name': 'john','code':6734, 'dept': 'sales'} • print dict['one'] # Prints value for 'one' key • print dict[2] # Prints value for 2 key • print tinydict # Prints complete dictionary • print tinydict.keys() # Prints all the keys • print tinydict.values() # Prints all the values
  • 24. Python Functions • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). • Any input parameters or arguments should be placed within these parentheses. • The first statement of a function can be an optional statement - the documentation string of the function or docstring. . • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
  • 25. Example -1 Function for find maximum of two numbers Example -2 Function for Read and Display list Example -3 Function for search in a list Example -4 Function for prime numbers
  • 26. Opening a File • The open() function is used to open files in Python. • The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened Example • File=open(“macfast.txt” , “w”)
  • 27. Modes Description r Read only. Starts at the beginning of the file r+ Read/Write. Starts at the beginning of the file w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist a+ Read/Append. Preserves file content by writing to the end of the file
  • 28. • Opening and Closing Files • The open Function file object = open(file_name [, access_mode][, buffering]) • file_name: The file_name argument is a string value that contains the name of the file that you want to access. • access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. • The close() Method The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.
  • 29. • The write() Method • The write() method writes any string to an open file • The write() method does not add a newline character ('n') to the end of the string − # Open a file file = open(“test.txt", "wb") file.write( “ Two day workshop on Python "); # Close opend file File.close()
  • 30. • The read() Method • The read() method reads a string from an open file. f= open(“test.txt", "r") str = f.read(); print str fo.close()
  • 31. Regular Expression • Regular expressions are essentially a tiny, highly specialized programming language embedded inside Python and made available through the re module.
  • 32. • Regular expressions are useful in a wide variety of text processing tasks, and more generally string processing • Data validation • Data scraping (especially web scraping), • Data wrangling, • Parsing, • Syntax highlighting systems
  • 33. Various methods of Regular Expressions The ‘re’ package provides multiple methods to perform queries on an input string. Here are the most commonly used methods 1.re.match() 2.re.search() 3.re.findall() 4.re.split() 5.re.sub()
  • 34. re.match() This method finds match if it occurs at start of the string str='MCA , MBA , BCA , BBA' re.match('MCA' , str) re.match("MBA" , str)
  • 35. re.search() search() method is able to find a pattern from any position of the string but it only returns the first occurrence of the search pattern.
  • 36. Re.findall • findall helps to get a list of all matching patterns import re str='MCA , MBA , BCA , BBA , MSC' result =re.findall (r"Mww" , str) if result: for i in result: print i else: print "Not Found"
  • 37. Finding all Adverbs import re file= open(‘story.txt' , "r") str=file.read(); result=re.findall(r"w+ly",str) for i in result: print i
  • 38. re.split() This methods helps to split string by the occurrences of given pattern. import re str = 'MCA MBA BCA MSC BBA BSc' result=re.split(" ",str) for i in result: print i
  • 39. re.sub(pattern, repl, string) • It helps to search a pattern and replace with a new sub string. If the pattern is not found, string is returned unchanged. import re str = 'BCA BSc BCA' print str result=re.sub(r"B", "M" , str) print "After replacement" print result
  • 40. Change gmail.com to macfast.org using re.sub() import re str = "tiji@gmail.com ,anju@gmail.com ,anu@gmail.com" print str newstr= re.sub(r"@w+.com" , "@macfast.org" , str) print "Change gmail.com to macfast.org " print newstr
  • 41. Project -1 •Extract information from an Excel file using Python
  • 42. What is SQLite? SQLite is an embedded SQL database engine •SQLite is ideal for both small and large applications •SQLite supports standard SQL •Open source software
  • 43. Connection to a SQLite Database import sqlite3 conn = sqlite3.connect('example.db') Once you have a Connection, you can create a Cursor object and call its execute() method to perform SQL commands: c = conn.cursor()
  • 44. Project Student Information System(SIS) Insert Data -> insertdata.py Update Data -> updatedata.py Delete Data ->deletedata.py Display Students List ->list.py

Editor's Notes

  1. TimSort is a sorting algorithm based on Insertion Sort and Merge Sort. A stable sorting algorithm works in O(n Log n) time Used in Java’s Arrays.sort() as well as Python’s sorted() and sort(). It was implemented by Tim Peters in 2002 for use in the Python programming language
  2. Why we use regular expression?
  3. Web Scraping (also termed Screen Scraping, Web Data Extraction, Web Harvesting etc.) is a technique employed to extract large amounts of data from websites whereby the data is extracted and saved to a local file in your computer or to a database in table (spreadsheet) format. Data wrangling (sometimes referred to as data munging) is the process of transforming and mapping data from one "raw" data form into another format with the intent of making it more appropriate and valuable for a variety of downstream purposes such as analytics.