Movatterモバイル変換


[0]ホーム

URL:


Tiji Thomas, profile picture
Uploaded byTiji Thomas
PPTX, PDF1,447 views

Programming in Python

The document provides an introduction to programming in Python. It discusses how Python can be used for web development, desktop applications, data science, machine learning, and more. It also covers executing Python programs, reading keyboard input, decision making and loops in Python, standard data types like numbers, strings, lists, tuples and dictionaries. Additionally, it describes functions, opening and reading/writing files, regular expressions, and provides examples of SQLite database connections in Python projects.

Embed presentation

Downloaded 50 times
Programming in PythonTiji ThomasHODDepartment of Computer ApplicationsMACFAST
Jointly organized byDept. of Computer Applications, MACFASTKSCSTE&UNAI , Computer Society of India (CSI)MAR ATHANASIOS COLLEGE FOR ADVANCED STUDIES TIRUVALLA(MACFAST)UNAI-MACFAST-ASPIRETaliparamba Arts & Science CollegeAccredited 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 , MachineLearning , 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 Programa) Command Prompt• print “Hello World”• b)IDLE1. Run IDLE. ...2. Click File, New Window. ...3. Enter your script and save file with . Python files have afile 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 yourscript.
Reading Keyboard Input• Python provides two built-in functions to read a line of text fromstandard input, which by default comes from the keyboard. Thesefunctions are −• raw_input• input• The raw_input Function• The raw_input([prompt]) function reads one linefrom 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 toraw_input, except that it assumes the input is avalid Python expression and returns the evaluatedresult to you.str = input("Enter your input: ");print "Received input is : ", str
Python Decision MakingStatement Descriptionif statementsAn if statement consists of a boolean expressionfollowed by one or more statements.if...else statementsAn if statement can be followed by an optionalelse statement, which executes when the booleanexpression is FALSE.If .. elifYou can use one if or else if statement insideanother if or else if statement(s).
Indentation• Python provides no braces to indicate blocks ofcode for class and function definitions or flowcontrol. Blocks of code are denoted by lineindentationif True:print "True"else:print "False"
Python Loops• while - loops through a block of code if and as longas a specified condition is true• for - loops through a block of code a specifiednumber of times
Example - while#Display first n numbersn=input("Enter value for n ")i=1while i<=n:print ii= i + 1
Example for#for loop examplestr= “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 withinsquare brackets ([]). To some extent, lists are similar to arrays in C.One difference between them is that all the items belonging to alist 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 list1. 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 usefulto generate sequences of numbers in the form of alist.• The given end point is never part of the generatedlist;
Basic list operationsLength - lenConcatenation : +Repetition - ['Hi!'] * 4Membership - 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 fruitsfruits.sort()for i in fruits:print iprint "nnnReverse ordernnn"fruits.sort(reverse=True)for i in fruits:print i
Python Tuples• A tuple consists of a number of values separated bycommas. Tuples are enclosed within parentheses.• The main differences between lists and tuples are:Lists are enclosed in brackets ( [ ] ) and theirelements and size can be changed, while tuples areenclosed in parentheses ( ( ) ) and cannot beupdated.• 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 inPerl and consist of key-value pairs• Dictionaries are enclosed by curly braces ({ }) andvalues can be assigned and accessed using squarebraces ([]).
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 followedby the function name and parentheses ( ( ) ).• Any input parameters or arguments should be placedwithin these parentheses.• The first statement of a function can be an optionalstatement - the documentation string of the function ordocstring..• The statement return [expression] exits a function,optionally passing back an expression to the caller. Areturn statement with no arguments is the same asreturn None.
Example -1Function for find maximum of two numbersExample -2Function for Read and Display listExample -3Function for search in a listExample -4Function for prime numbers
Opening a File• The open() function is used to open files in Python.• The first parameter of this function contains thename of the file to be opened and the secondparameter specifies in which mode the file shouldbe openedExample• File=open(“macfast.txt” , “w”)
Modes Descriptionr Read only. Starts at the beginning of the filer+ Read/Write. Starts at the beginning of the filew Write only. Opens and clears the contents of file; orcreates a new file if it doesn't existw+ Read/Write. Opens and clears the contents of file; orcreates a new file if it doesn't exista Append. Opens and writes to the end of the file or createsa new file if it doesn't exista+ Read/Append. Preserves file content by writing to the endof the file
• Opening and Closing Files• The open Functionfile object = open(file_name [, access_mode][, buffering])• file_name: The file_name argument is a string value thatcontains the name of the file that you want to access.• access_mode: The access_mode determines the mode inwhich the file has to be opened, i.e., read, write, append,etc.• The close() MethodThe close() method of a file object flushes any unwritteninformation and closes the file object, after which no morewriting can be done.
• The write() Method• The write() method writes any string to an open file• The write() method does not add a newlinecharacter ('n') to the end of the string −# Open a filefile = open(“test.txt", "wb")file.write( “ Two day workshop on Python ");# Close opend fileFile.close()
• The read() Method• The read() method reads a string from an open file.f= open(“test.txt", "r")str = f.read();print strfo.close()
Regular Expression• Regular expressions are essentially a tiny, highlyspecialized programming language embeddedinside Python and made available through the remodule.
• Regular expressions are useful in a wide variety oftext processing tasks, and more generally stringprocessing• Data validation• Data scraping (especially web scraping),• Data wrangling,• Parsing,• Syntax highlighting systems
Various methods of Regular ExpressionsThe ‘re’ package provides multiple methods toperform queries on an input string. Here are themost commonly used methods1.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 thestringstr='MCA , MBA , BCA , BBA're.match('MCA' , str)re.match("MBA" , str)
re.search()search() method is able to find a pattern from anyposition of the string but it only returns the firstoccurrence of the search pattern.
Re.findall• findall helps to get a list of all matching patternsimport restr='MCA , MBA , BCA , BBA , MSC'result =re.findall (r"Mww" , str)if result:for i in result:print ielse:print "Not Found"
Finding all Adverbsimport refile= 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 occurrencesof given pattern.import restr = '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 newsub string. If the pattern is not found, string isreturned unchanged.import restr = 'BCA BSc BCA'print strresult=re.sub(r"B", "M" , str)print "After replacement"print result
Change gmail.com to macfast.orgusing re.sub()import restr = "tiji@gmail.com ,anju@gmail.com ,anu@gmail.com"print strnewstr= re.sub(r"@w+.com" , "@macfast.org" , str)print "Change gmail.com to macfast.org "print newstr
Project -1•Extract information from anExcel file using Python
What is SQLite?SQLite is an embedded SQL database engine•SQLite is ideal for both small and largeapplications•SQLite supports standard SQL•Open source software
Connection to a SQLite Databaseimport sqlite3conn = sqlite3.connect('example.db')Once you have a Connection, you can create aCursor object and call its execute() method toperform SQL commands:c = conn.cursor()
ProjectStudent Information System(SIS)Insert Data -> insertdata.pyUpdate Data -> updatedata.pyDelete Data ->deletedata.pyDisplay Students List ->list.py
Thank You

Recommended

PPTX
Python for Beginners(v1)
PPTX
Values and Data types in python
PDF
Learn 90% of Python in 90 Minutes
PPTX
Programming
PDF
Python Workshop
PDF
Control Structures in Python
PDF
Python Programming Part 1.pdf
PPTX
Python and its applications
PDF
Python basic
PPSX
Programming with Python
PDF
Python final ppt
PPTX
Python basics
PPTX
Fundamentals of Python Programming
PPTX
Introduction to the basics of Python programming (part 1)
PPT
Introduction to Python
PPTX
Intro to Python Programming Language
PPTX
Basic Python Programming: Part 01 and Part 02
PPTX
Python
PPT
Python ppt
PDF
Variables & Data Types In Python | Edureka
PDF
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
PDF
Python Basics | Python Tutorial | Edureka
PPT
Python Programming ppt
PPT
Intro to Python
PPTX
Beginning Python Programming
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
PPTX
Introduction python
PPTX
Chapter 8 getting started with python
PDF
Introduction to python
PPTX
Python

More Related Content

PPTX
Python for Beginners(v1)
PPTX
Values and Data types in python
PDF
Learn 90% of Python in 90 Minutes
PPTX
Programming
PDF
Python Workshop
PDF
Control Structures in Python
PDF
Python Programming Part 1.pdf
PPTX
Python and its applications
Python for Beginners(v1)
Values and Data types in python
Learn 90% of Python in 90 Minutes
Programming
Python Workshop
Control Structures in Python
Python Programming Part 1.pdf
Python and its applications

What's hot

PDF
Python basic
PPSX
Programming with Python
PDF
Python final ppt
PPTX
Python basics
PPTX
Fundamentals of Python Programming
PPTX
Introduction to the basics of Python programming (part 1)
PPT
Introduction to Python
PPTX
Intro to Python Programming Language
PPTX
Basic Python Programming: Part 01 and Part 02
PPTX
Python
PPT
Python ppt
PDF
Variables & Data Types In Python | Edureka
PDF
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
PDF
Python Basics | Python Tutorial | Edureka
PPT
Python Programming ppt
PPT
Intro to Python
PPTX
Beginning Python Programming
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
PPTX
Introduction python
PPTX
Chapter 8 getting started with python
Python basic
Programming with Python
Python final ppt
Python basics
Fundamentals of Python Programming
Introduction to the basics of Python programming (part 1)
Introduction to Python
Intro to Python Programming Language
Basic Python Programming: Part 01 and Part 02
Python
Python ppt
Variables & Data Types In Python | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Basics | Python Tutorial | Edureka
Python Programming ppt
Intro to Python
Beginning Python Programming
Python 101: Python for Absolute Beginners (PyTexas 2014)
Introduction python
Chapter 8 getting started with python

Similar to Programming in Python

PDF
Introduction to python
PPTX
Python
PDF
Introduction To Programming with Python
PPTX
Basic of Python- Hands on Session
PPTX
Python For Data Science.pptx
PPTX
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
PPTX
FUNDAMENTALS OF PYTHON LANGUAGE
PPTX
Pythonppt28 11-18
PPTX
introduction to python programming concepts
PPTX
Introduction to learn and Python Interpreter
PPTX
Python Demo.pptx
PPTX
Chapter1 python introduction syntax general
PPTX
python_computer engineering_semester_computer_language.pptx
PPTX
Introduction to python programming 1
PPT
Python tutorialfeb152012
PPTX
Python Demo.pptx
PDF
First Steps in Python Programming
PPTX
Python-The programming Language
PPTX
Python chapter presentation details.pptx
PPT
Python
Introduction to python
Python
Introduction To Programming with Python
Basic of Python- Hands on Session
Python For Data Science.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
FUNDAMENTALS OF PYTHON LANGUAGE
Pythonppt28 11-18
introduction to python programming concepts
Introduction to learn and Python Interpreter
Python Demo.pptx
Chapter1 python introduction syntax general
python_computer engineering_semester_computer_language.pptx
Introduction to python programming 1
Python tutorialfeb152012
Python Demo.pptx
First Steps in Python Programming
Python-The programming Language
Python chapter presentation details.pptx
Python

Recently uploaded

PDF
বাংলাদেশ অর্থনৈতিক সমীক্ষা - ২০২৫ with Bookmark.pdf
PPTX
LYMPHATIC SYSTEM.pptx it includes lymph, lymph nodes, bone marrow, spleen
PDF
Digital Journalism Ethics 2025 materi for Regulation & Ethic Media
PDF
Agentic AI and AI Agents 20251121.pdf - by Ms. Oceana Wong
PDF
Digital Electronics – Registers and Their Applications
PDF
1. Doing Academic Research: Problems and Issues, 2. Academic Research Writing...
PPTX
Screening and Selecting Studies for Systematic Review Dr Reginald Quansah
PDF
DEFINITION OF COMMUNITY Sociology. .pdf
PDF
The invasion of Alexander of Macedonia in India
PPTX
Time Series Analysis - Method of Simple Moving Average 3 Year and 4 Year Movi...
PDF
LH_Lecture Note on Spices , AI And Importance in Human Life.pdf
PDF
Conferencia de Abertura_Virgilio Almeida.pdf
PDF
“Step-by-Step Fabrication of Bipolar Junction Transistors (BJTs)”
PDF
UGC NET Paper 1 Syllabus | 10 Units Complete Guide for NTA JRF
PPTX
Physical education notes class ncert 12th
PPTX
What are New Features in Purchase _Odoo 18
PPTX
Anatomy of the eyeball An overviews.pptx
PPTX
A Presentation of PMES 2025-2028 with Salient features.pptx
PPTX
G-Protein-Coupled Receptors (GPCRs): Structure, Mechanism, and Functions
PPTX
Chapter 3. Pharmaceutical Aids (pharmaceutics)
বাংলাদেশ অর্থনৈতিক সমীক্ষা - ২০২৫ with Bookmark.pdf
LYMPHATIC SYSTEM.pptx it includes lymph, lymph nodes, bone marrow, spleen
Digital Journalism Ethics 2025 materi for Regulation & Ethic Media
Agentic AI and AI Agents 20251121.pdf - by Ms. Oceana Wong
Digital Electronics – Registers and Their Applications
1. Doing Academic Research: Problems and Issues, 2. Academic Research Writing...
Screening and Selecting Studies for Systematic Review Dr Reginald Quansah
DEFINITION OF COMMUNITY Sociology. .pdf
The invasion of Alexander of Macedonia in India
Time Series Analysis - Method of Simple Moving Average 3 Year and 4 Year Movi...
LH_Lecture Note on Spices , AI And Importance in Human Life.pdf
Conferencia de Abertura_Virgilio Almeida.pdf
“Step-by-Step Fabrication of Bipolar Junction Transistors (BJTs)”
UGC NET Paper 1 Syllabus | 10 Units Complete Guide for NTA JRF
Physical education notes class ncert 12th
What are New Features in Purchase _Odoo 18
Anatomy of the eyeball An overviews.pptx
A Presentation of PMES 2025-2028 with Salient features.pptx
G-Protein-Coupled Receptors (GPCRs): Structure, Mechanism, and Functions
Chapter 3. Pharmaceutical Aids (pharmaceutics)

Programming in Python

  • 1.
    Programming in PythonTijiThomasHODDepartment of Computer ApplicationsMACFAST
  • 2.
    Jointly organized byDept.of Computer Applications, MACFASTKSCSTE&UNAI , Computer Society of India (CSI)MAR ATHANASIOS COLLEGE FOR ADVANCED STUDIES TIRUVALLA(MACFAST)UNAI-MACFAST-ASPIRETaliparamba Arts & Science CollegeAccredited by NAAC with A grade
  • 3.
    Introduction Python isa general-purpose interpreted, object-oriented, and high-level programming language. What can we do with Python –Web Development , ,Desktop Applications, Data Science , MachineLearning , 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 PythonPrograma) Command Prompt• print “Hello World”• b)IDLE1. Run IDLE. ...2. Click File, New Window. ...3. Enter your script and save file with . Python files have afile 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 yourscript.
  • 5.
    Reading Keyboard Input•Python provides two built-in functions to read a line of text fromstandard input, which by default comes from the keyboard. Thesefunctions are −• raw_input• input• The raw_input Function• The raw_input([prompt]) function reads one linefrom 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 inputFunction• The input([prompt]) function is equivalent toraw_input, except that it assumes the input is avalid Python expression and returns the evaluatedresult to you.str = input("Enter your input: ");print "Received input is : ", str
  • 7.
    Python Decision MakingStatementDescriptionif statementsAn if statement consists of a boolean expressionfollowed by one or more statements.if...else statementsAn if statement can be followed by an optionalelse statement, which executes when the booleanexpression is FALSE.If .. elifYou can use one if or else if statement insideanother if or else if statement(s).
  • 8.
    Indentation• Python providesno braces to indicate blocks ofcode for class and function definitions or flowcontrol. Blocks of code are denoted by lineindentationif True:print "True"else:print "False"
  • 9.
    Python Loops• while- loops through a block of code if and as longas a specified condition is true• for - loops through a block of code a specifiednumber of times
  • 10.
    Example - while#Displayfirst n numbersn=input("Enter value for n ")i=1while i<=n:print ii= i + 1
  • 11.
    Example for#for loopexamplestr= “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 ofcharacters 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• Alist contains items separated by commas and enclosed withinsquare brackets ([]). To some extent, lists are similar to arrays in C.One difference between them is that all the items belonging to alist 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• Addelements to a list1. 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• Thebuilt-in range function in Python is very usefulto generate sequences of numbers in the form of alist.• The given end point is never part of the generatedlist;
  • 17.
    Basic list operationsLength- lenConcatenation : +Repetition - ['Hi!'] * 4Membership - 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 fruitsfruits.sort()for i in fruits:print iprint "nnnReverse ordernnn"fruits.sort(reverse=True)for i in fruits:print i
  • 19.
    Python Tuples• Atuple consists of a number of values separated bycommas. Tuples are enclosed within parentheses.• The main differences between lists and tuples are:Lists are enclosed in brackets ( [ ] ) and theirelements and size can be changed, while tuples areenclosed in parentheses ( ( ) ) and cannot beupdated.• 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'sdictionaries are kind of hash table type.They work like associative arrays or hashes found inPerl and consist of key-value pairs• Dictionaries are enclosed by curly braces ({ }) andvalues can be assigned and accessed using squarebraces ([]).
  • 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• Functionblocks begin with the keyword def followedby the function name and parentheses ( ( ) ).• Any input parameters or arguments should be placedwithin these parentheses.• The first statement of a function can be an optionalstatement - the documentation string of the function ordocstring..• The statement return [expression] exits a function,optionally passing back an expression to the caller. Areturn statement with no arguments is the same asreturn None.
  • 25.
    Example -1Function forfind maximum of two numbersExample -2Function for Read and Display listExample -3Function for search in a listExample -4Function for prime numbers
  • 26.
    Opening a File•The open() function is used to open files in Python.• The first parameter of this function contains thename of the file to be opened and the secondparameter specifies in which mode the file shouldbe openedExample• File=open(“macfast.txt” , “w”)
  • 27.
    Modes Descriptionr Readonly. Starts at the beginning of the filer+ Read/Write. Starts at the beginning of the filew Write only. Opens and clears the contents of file; orcreates a new file if it doesn't existw+ Read/Write. Opens and clears the contents of file; orcreates a new file if it doesn't exista Append. Opens and writes to the end of the file or createsa new file if it doesn't exista+ Read/Append. Preserves file content by writing to the endof the file
  • 28.
    • Opening andClosing Files• The open Functionfile object = open(file_name [, access_mode][, buffering])• file_name: The file_name argument is a string value thatcontains the name of the file that you want to access.• access_mode: The access_mode determines the mode inwhich the file has to be opened, i.e., read, write, append,etc.• The close() MethodThe close() method of a file object flushes any unwritteninformation and closes the file object, after which no morewriting can be done.
  • 29.
    • The write()Method• The write() method writes any string to an open file• The write() method does not add a newlinecharacter ('n') to the end of the string −# Open a filefile = open(“test.txt", "wb")file.write( “ Two day workshop on Python ");# Close opend fileFile.close()
  • 30.
    • The read()Method• The read() method reads a string from an open file.f= open(“test.txt", "r")str = f.read();print strfo.close()
  • 31.
    Regular Expression• Regularexpressions are essentially a tiny, highlyspecialized programming language embeddedinside Python and made available through the remodule.
  • 32.
    • Regular expressionsare useful in a wide variety oftext processing tasks, and more generally stringprocessing• Data validation• Data scraping (especially web scraping),• Data wrangling,• Parsing,• Syntax highlighting systems
  • 33.
    Various methods ofRegular ExpressionsThe ‘re’ package provides multiple methods toperform queries on an input string. Here are themost commonly used methods1.re.match()2.re.search()3.re.findall()4.re.split()5.re.sub()
  • 34.
    re.match()This method findsmatch if it occurs at start of thestringstr='MCA , MBA , BCA , BBA're.match('MCA' , str)re.match("MBA" , str)
  • 35.
    re.search()search() method isable to find a pattern from anyposition of the string but it only returns the firstoccurrence of the search pattern.
  • 36.
    Re.findall• findall helpsto get a list of all matching patternsimport restr='MCA , MBA , BCA , BBA , MSC'result =re.findall (r"Mww" , str)if result:for i in result:print ielse:print "Not Found"
  • 37.
    Finding all Adverbsimportrefile= 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 helpsto split string by the occurrencesof given pattern.import restr = '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 newsub string. If the pattern is not found, string isreturned unchanged.import restr = 'BCA BSc BCA'print strresult=re.sub(r"B", "M" , str)print "After replacement"print result
  • 40.
    Change gmail.com tomacfast.orgusing re.sub()import restr = "tiji@gmail.com ,anju@gmail.com ,anu@gmail.com"print strnewstr= re.sub(r"@w+.com" , "@macfast.org" , str)print "Change gmail.com to macfast.org "print newstr
  • 41.
    Project -1•Extract informationfrom anExcel file using Python
  • 42.
    What is SQLite?SQLiteis an embedded SQL database engine•SQLite is ideal for both small and largeapplications•SQLite supports standard SQL•Open source software
  • 43.
    Connection to aSQLite Databaseimport sqlite3conn = sqlite3.connect('example.db')Once you have a Connection, you can create aCursor object and call its execute() method toperform SQL commands:c = conn.cursor()
  • 44.
    ProjectStudent Information System(SIS)InsertData -> insertdata.pyUpdate Data -> updatedata.pyDelete Data ->deletedata.pyDisplay Students List ->list.py
  • 45.

Editor's Notes

  • #19 TimSort is a sorting algorithm based on Insertion Sort and Merge Sort. A stable sorting algorithm works in O(n Log n) timeUsed 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
  • #32 Why we use regular expression?
  • #33 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.

[8]ページ先頭

©2009-2025 Movatter.jp