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

More Related Content

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

What's hot

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

Similar to Programming in Python

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

Recently uploaded

PDF
1. Doing Academic Research: Problems and Issues, 2. Academic Research Writing...
PDF
AI and ICT for Teaching and Learning, Induction-cum-Training Programme, 5th 8...
PDF
Cattolica University - Lab Generative and Agentic AI - Mario Bencivinni
PDF
DEFINITION OF COMMUNITY Sociology. .pdf
PDF
Multimodal and Multimedia AI - by Ms. Oceana Wong
PDF
Agentic AI and AI Agents 20251121.pdf - by Ms. Oceana Wong
PPTX
DEPED MEMORANDUM 089, 2025 PMES guidelines pptx
PPTX
What are New Features in Purchase _Odoo 18
PPTX
SEMESTER 5 UNIT- 1 Difference of Children and adults.pptx
PPTX
Masterclass on Cybercrime, Scams & Safety Hacks.pptx
PPTX
Physical education notes class ncert 12th
PPTX
kklklklklklklklk;lkpoipor[3rjdkjoe99759893058085
PPTX
Time Series Analysis - Least Square Method Fitting a Linear Trend Equation
PPTX
General Wellness & Restorative Tonic: Draksharishta
PPTX
Chapter 3. Pharmaceutical Aids (pharmaceutics)
PDF
LH_Lecture Note on Spices , AI And Importance in Human Life.pdf
PPTX
Anatomy of the eyeball An overviews.pptx
PDF
45 ĐỀ LUYỆN THI IOE LỚP 8 THEO CHƯƠNG TRÌNH MỚI - NĂM HỌC 2024-2025 (CÓ LINK ...
PDF
The invasion of Alexander of Macedonia in India
PDF
Deep Research and Analysis - by Ms. Oceana Wong
1. Doing Academic Research: Problems and Issues, 2. Academic Research Writing...
AI and ICT for Teaching and Learning, Induction-cum-Training Programme, 5th 8...
Cattolica University - Lab Generative and Agentic AI - Mario Bencivinni
DEFINITION OF COMMUNITY Sociology. .pdf
Multimodal and Multimedia AI - by Ms. Oceana Wong
Agentic AI and AI Agents 20251121.pdf - by Ms. Oceana Wong
DEPED MEMORANDUM 089, 2025 PMES guidelines pptx
What are New Features in Purchase _Odoo 18
SEMESTER 5 UNIT- 1 Difference of Children and adults.pptx
Masterclass on Cybercrime, Scams & Safety Hacks.pptx
Physical education notes class ncert 12th
kklklklklklklklk;lkpoipor[3rjdkjoe99759893058085
Time Series Analysis - Least Square Method Fitting a Linear Trend Equation
General Wellness & Restorative Tonic: Draksharishta
Chapter 3. Pharmaceutical Aids (pharmaceutics)
LH_Lecture Note on Spices , AI And Importance in Human Life.pdf
Anatomy of the eyeball An overviews.pptx
45 ĐỀ LUYỆN THI IOE LỚP 8 THEO CHƯƠNG TRÌNH MỚI - NĂM HỌC 2024-2025 (CÓ LINK ...
The invasion of Alexander of Macedonia in India
Deep Research and Analysis - by Ms. Oceana Wong

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