SlideShare a Scribd company logo
1 of 7
11.1 Python
We could implement a Charme interpreter using Scheme or any other universal
programming language, but implement it using the programming language Python.
Python is a popular programming language initially designed by Guido van Rossum in
1991.1 Python is freely available from http://www.python.org.
We use Python instead of Scheme to implement our Charme interpreter for a few
reasons. The first reason is pedagogical: it is instructive to learn new languages.
As Dijkstra's quote at the beginning of this chapter observes, the languages we use have
a profound effect on how we think.
This is true for natural languages, but also true for programming languages. Different
languages make different styles of programming more convenient, and it is important
for every programmer to be familiar with several different styles of programming.
All of the major concepts we have covered so far apply to Python nearly identically to
how they apply to Scheme, but seeing them in the context of a different language should
make it clearer what the fundamental concepts are and what are artifacts of a particular
programming language.
Another reason for using Python is that it provides some features that enhance
expressiveness that are not available in Scheme.
These include built-in support for objects and imperative control structures.
Python is also well-supported by most web servers (including Apache), and is
widely used to develop dynamic web applications.
The grammar for Python is quite different from the Scheme grammar, so Python
programs look very different from Scheme programs.
The evaluation rules, however, are quite similar to the evaluation rules for Scheme. This
chapter does not describe the entire Python language, but introduces the grammar rules
and evaluation rules for the most important Python constructs as we use them to
implement the Charme interpreter.
Like Scheme, Python is a universal programming language. Both languages can
express all mechanical computations.
For any computation we can express in Scheme, there is a Python program that defines
the same computation. Conversely, every Python program has an equivalent
Scheme program.
One piece of evidence that every Scheme program has an equivalent Python program is
the interpreter we develop in this chapter.
Since we can implement an interpreter for a Scheme-like language in Python, we know
we can express every computation that can be expressed by a program in that language
with an equivalent Python program: the Charme interpreter with the Charme program
as its input.
Tokenizing. We introduce Python using one of the procedures in our interpreter
implementation.
We divide the job of parsing into two procedures that are combined to solve the problem
of transforming an input string into a list describing the input program's structure.
The first part is the tokenizer. It takes as input a string representing a Charme program,
and outputs a list of the tokens in that string.
A token is an indivisible syntactic unit. For example, the Charme expression,(define
square (lambda (x) (* x x))), contains 15 tokens: (, define, square, (, lambda, (, x, ), (, *, x, x, ),
), and ).
Tokens are separated by whitespace (spaces, tabs, and newlines). Punctuation
marks such as the left and right parentheses are tokens by themselves.
The tokenize procedure below takes as input a string s in the Charme target
language, and produces as output a list of the tokens in s. We describe the
Python language constructs it uses next.
def tokenize(s): # # starts a comment until
empty
the end
string (two
to the
in the
is a
token it
of the line
current = ' ' # initialize
#
for
current to the single quotes)
tokens = []
for c in s:
#
initialize
each
tokens
character,
if
empty
string
list
sc,
if c.isspace(): #
if len(current) > 0: #
c whitespace
non-emptyif the current is
totokens.append(current) # add the list}
stringcurrent = '' # reset current
if
end
#add
token to
is
the
empty
elif c in '()': # otherwise, c a
current
parenthesis
tokenif len(current) > 0: #
tokens.append(current) it to the tokens
to
to
an
list
string
list
current = ' ' # and reset current
add the parenthesis
(it is
add the
character loop
there
#
the empty
tokens.append(c) # the token
else: # otherwise alphanumeric)
current = current + c # to the current
the
token
s
token
list
# end of the for reached
is
it
end
current
of
if len(current) > 0: # if a
totokens.append(current)
return tokens # the
result is the list of
tokens
add the token
11.1.1 Python Programs
Python provides control statements for making decisions, looping, and for
returning from a procedure.
If statement. Python's if statement is similar to the conditional expression in Scheme:
Unlike in Scheme, there is no need to have an alternate clause since the Python
if statement does not need to produce a value.
Hence, the else is optional. The evaluation rule is similar to Scheme's conditional
expression:
Python Evaluation Rule: If. First, evaluate the ExpressionPredicatePredicate. If it
evaluates to a true value, the consequent Block is evaluated, and none of the rest
of theIfStatement is evaluated. Otherwise, each of the elif predicates is evaluated in
order.
If one evaluates to a true value, its Block is evaluated and none of the rest
of the IfStatement is evaluated. If none of the elif predicates evaluates to a true
value, the else Block is evaluated if there is one.
The main if statement in tokenize is:
if c.isspace(): ...
elif c in '()': ...
else: current = current + c
The first if predicate tests if the current character is a space. If so, the end of the current
token has been reached. The consequent Block is itself an IfStatement:
if len(current) > 0:
tokens.append(current)
current = ' '
If the current token has at least one character, it is appended to the list of tokens in the
input string and the current token is reset to the empty string.
ThisIfStatement has no elif or else clauses, so if the predicate is false, there is nothing to
do.
For statement. A for statement provides a way of iterating through a set of
values, carrying out a body block for each value.
Its evaluation rule is: Python Evaluation Rule:
the Expressionwhich must produce a value that is a collection.
For. First evaluate
Then, for each value in the collection assign the Target to that value and evaluate
the Block.
Other than the first two initializations, and the final two statements, the bulk of
the tokenize procedure is contained in a for statement.
The for statement intokenize header is for c in s: .... The string s is the input string,
a collection of characters.
So, the loop will repeat once for each character in s, and the value of c is each character
in the input string (represented as a singleton string), in turn.
Return statement. In Scheme, the body of a procedure is an expression and the value
of that expression is the result of evaluating an application of the procedure.
In Python, the body of a procedure is a block of one or more statements.
Statements have no value, so there is no obvious way to decide what the result of
a procedure application should be.
Python's solution is to use areturn statement. The grammar for the return statement is:
A return statement finishes execution of
theExpression to the caller as the result.
a procedure, returning the value of
The last statement of the tokenizeprocedure is: return tokens. It returns the value of
the tokens list to the caller.

More Related Content

What's hot

Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and commentsNilimesh Halder
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| FundamentalsMohd Sajjad
 
Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design MAHASREEM
 
Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Aman Sharma
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical AnalyzerArchana Gopinath
 
LVEE 2014: Text parsing with Python and PLY
LVEE 2014: Text parsing with Python and PLYLVEE 2014: Text parsing with Python and PLY
LVEE 2014: Text parsing with Python and PLYdmbaturin
 
Python-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutabilityPython-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutabilityMohd Sajjad
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts Pavan Babu .G
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Jaganadh Gopinadhan
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
 

What's hot (20)

Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and comments
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Lexical Analysis - Compiler design
Lexical Analysis - Compiler design
 
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
 
Python syntax
Python syntaxPython syntax
Python syntax
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical Analyzer
 
LVEE 2014: Text parsing with Python and PLY
LVEE 2014: Text parsing with Python and PLYLVEE 2014: Text parsing with Python and PLY
LVEE 2014: Text parsing with Python and PLY
 
Python-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutabilityPython-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutability
 
Parsing
ParsingParsing
Parsing
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Python Data Types
Python Data TypesPython Data Types
Python Data Types
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 

Viewers also liked

1.2 eye & vision
1.2 eye & vision1.2 eye & vision
1.2 eye & visionRajendran
 
Lighting for displays and signaling
Lighting for displays and signalingLighting for displays and signaling
Lighting for displays and signalingRajendran
 
evaluating recursive_applications
evaluating recursive_applicationsevaluating recursive_applications
evaluating recursive_applicationsRajendran
 
impact of_mutation
impact of_mutationimpact of_mutation
impact of_mutationRajendran
 
empirical masurements
empirical masurementsempirical masurements
empirical masurementsRajendran
 
Array- queues3
Array- queues3Array- queues3
Array- queues3Rajendran
 
Transport lighting
Transport lightingTransport lighting
Transport lightingRajendran
 
Flood & sports
Flood & sportsFlood & sports
Flood & sportsRajendran
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional arrayRajendran
 
Np completeness h4
Np completeness  h4Np completeness  h4
Np completeness h4Rajendran
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional arrayRajendran
 
Turing Machine
Turing MachineTuring Machine
Turing MachineRajendran
 

Viewers also liked (19)

1.2 eye & vision
1.2 eye & vision1.2 eye & vision
1.2 eye & vision
 
Lighting for displays and signaling
Lighting for displays and signalingLighting for displays and signaling
Lighting for displays and signaling
 
evaluating recursive_applications
evaluating recursive_applicationsevaluating recursive_applications
evaluating recursive_applications
 
lists
listslists
lists
 
impact of_mutation
impact of_mutationimpact of_mutation
impact of_mutation
 
Stacks queues
Stacks queuesStacks queues
Stacks queues
 
empirical masurements
empirical masurementsempirical masurements
empirical masurements
 
Array- queues3
Array- queues3Array- queues3
Array- queues3
 
pairs
pairspairs
pairs
 
assignment
assignmentassignment
assignment
 
Transport lighting
Transport lightingTransport lighting
Transport lighting
 
Flood & sports
Flood & sportsFlood & sports
Flood & sports
 
Quick sort
Quick sortQuick sort
Quick sort
 
Pda to cfg h2
Pda to cfg h2Pda to cfg h2
Pda to cfg h2
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
 
Shell sort
Shell sortShell sort
Shell sort
 
Np completeness h4
Np completeness  h4Np completeness  h4
Np completeness h4
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Turing Machine
Turing MachineTuring Machine
Turing Machine
 

Similar to python

Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1Devashish Kumar
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning ParrotAI
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experiencedzynofustechnology
 
Python Decision Making And Loops.pdf
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdfNehaSpillai1
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
It’s sometimes useful to make a little language for a simple problem.pdf
It’s sometimes useful to make a little language for a simple problem.pdfIt’s sometimes useful to make a little language for a simple problem.pdf
It’s sometimes useful to make a little language for a simple problem.pdfarri2009av
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python FundamentalsPraveen M Jigajinni
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMaheshPandit16
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginnersAbishek Purushothaman
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonRanjith kumar
 
Engineering CS 5th Sem Python Module-1.pptx
Engineering CS 5th Sem Python Module-1.pptxEngineering CS 5th Sem Python Module-1.pptx
Engineering CS 5th Sem Python Module-1.pptxhardii0991
 
python full notes data types string and tuple
python full notes data types string and tuplepython full notes data types string and tuple
python full notes data types string and tupleSukhpreetSingh519414
 

Similar to python (20)

Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
Python Decision Making And Loops.pdf
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdf
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
C-PROGRAM
C-PROGRAMC-PROGRAM
C-PROGRAM
 
It’s sometimes useful to make a little language for a simple problem.pdf
It’s sometimes useful to make a little language for a simple problem.pdfIt’s sometimes useful to make a little language for a simple problem.pdf
It’s sometimes useful to make a little language for a simple problem.pdf
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python Fundamentals
 
Stu_Unit1_CSE1.pdf
Stu_Unit1_CSE1.pdfStu_Unit1_CSE1.pdf
Stu_Unit1_CSE1.pdf
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
GE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdfGE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdf
 
Engineering CS 5th Sem Python Module-1.pptx
Engineering CS 5th Sem Python Module-1.pptxEngineering CS 5th Sem Python Module-1.pptx
Engineering CS 5th Sem Python Module-1.pptx
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
python full notes data types string and tuple
python full notes data types string and tuplepython full notes data types string and tuple
python full notes data types string and tuple
 

More from Rajendran

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower boundsRajendran
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsRajendran
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower boundsRajendran
 
Red black tree
Red black treeRed black tree
Red black treeRajendran
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statisticsRajendran
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theoremRajendran
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree methodRajendran
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theoremRajendran
 
Master method
Master method Master method
Master method Rajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithmsRajendran
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisRajendran
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisRajendran
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of QuicksortRajendran
 
Np completeness
Np completenessNp completeness
Np completenessRajendran
 
computer languages
computer languagescomputer languages
computer languagesRajendran
 

More from Rajendran (20)

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower bounds
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding Costs
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
 
Red black tree
Red black treeRed black tree
Red black tree
 
Hash table
Hash tableHash table
Hash table
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theorem
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
 
Master method
Master method Master method
Master method
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Hash tables
Hash tablesHash tables
Hash tables
 
Lower bound
Lower boundLower bound
Lower bound
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm Analysis
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of Quicksort
 
Np completeness
Np completenessNp completeness
Np completeness
 
computer languages
computer languagescomputer languages
computer languages
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

python

  • 1. 11.1 Python We could implement a Charme interpreter using Scheme or any other universal programming language, but implement it using the programming language Python. Python is a popular programming language initially designed by Guido van Rossum in 1991.1 Python is freely available from http://www.python.org. We use Python instead of Scheme to implement our Charme interpreter for a few reasons. The first reason is pedagogical: it is instructive to learn new languages. As Dijkstra's quote at the beginning of this chapter observes, the languages we use have a profound effect on how we think. This is true for natural languages, but also true for programming languages. Different languages make different styles of programming more convenient, and it is important for every programmer to be familiar with several different styles of programming. All of the major concepts we have covered so far apply to Python nearly identically to how they apply to Scheme, but seeing them in the context of a different language should make it clearer what the fundamental concepts are and what are artifacts of a particular programming language. Another reason for using Python is that it provides some features that enhance expressiveness that are not available in Scheme. These include built-in support for objects and imperative control structures.
  • 2. Python is also well-supported by most web servers (including Apache), and is widely used to develop dynamic web applications. The grammar for Python is quite different from the Scheme grammar, so Python programs look very different from Scheme programs. The evaluation rules, however, are quite similar to the evaluation rules for Scheme. This chapter does not describe the entire Python language, but introduces the grammar rules and evaluation rules for the most important Python constructs as we use them to implement the Charme interpreter. Like Scheme, Python is a universal programming language. Both languages can express all mechanical computations. For any computation we can express in Scheme, there is a Python program that defines the same computation. Conversely, every Python program has an equivalent Scheme program. One piece of evidence that every Scheme program has an equivalent Python program is the interpreter we develop in this chapter. Since we can implement an interpreter for a Scheme-like language in Python, we know we can express every computation that can be expressed by a program in that language with an equivalent Python program: the Charme interpreter with the Charme program as its input.
  • 3. Tokenizing. We introduce Python using one of the procedures in our interpreter implementation. We divide the job of parsing into two procedures that are combined to solve the problem of transforming an input string into a list describing the input program's structure. The first part is the tokenizer. It takes as input a string representing a Charme program, and outputs a list of the tokens in that string. A token is an indivisible syntactic unit. For example, the Charme expression,(define square (lambda (x) (* x x))), contains 15 tokens: (, define, square, (, lambda, (, x, ), (, *, x, x, ), ), and ). Tokens are separated by whitespace (spaces, tabs, and newlines). Punctuation marks such as the left and right parentheses are tokens by themselves. The tokenize procedure below takes as input a string s in the Charme target language, and produces as output a list of the tokens in s. We describe the Python language constructs it uses next.
  • 4. def tokenize(s): # # starts a comment until empty the end string (two to the in the is a token it of the line current = ' ' # initialize # for current to the single quotes) tokens = [] for c in s: # initialize each tokens character, if empty string list sc, if c.isspace(): # if len(current) > 0: # c whitespace non-emptyif the current is totokens.append(current) # add the list} stringcurrent = '' # reset current if end #add token to is the empty elif c in '()': # otherwise, c a current parenthesis tokenif len(current) > 0: # tokens.append(current) it to the tokens to to an list string list current = ' ' # and reset current add the parenthesis (it is add the character loop there # the empty tokens.append(c) # the token else: # otherwise alphanumeric) current = current + c # to the current the token s token list # end of the for reached is it end current of if len(current) > 0: # if a totokens.append(current) return tokens # the result is the list of tokens add the token
  • 5. 11.1.1 Python Programs Python provides control statements for making decisions, looping, and for returning from a procedure. If statement. Python's if statement is similar to the conditional expression in Scheme: Unlike in Scheme, there is no need to have an alternate clause since the Python if statement does not need to produce a value. Hence, the else is optional. The evaluation rule is similar to Scheme's conditional expression: Python Evaluation Rule: If. First, evaluate the ExpressionPredicatePredicate. If it evaluates to a true value, the consequent Block is evaluated, and none of the rest of theIfStatement is evaluated. Otherwise, each of the elif predicates is evaluated in order. If one evaluates to a true value, its Block is evaluated and none of the rest of the IfStatement is evaluated. If none of the elif predicates evaluates to a true value, the else Block is evaluated if there is one.
  • 6. The main if statement in tokenize is: if c.isspace(): ... elif c in '()': ... else: current = current + c The first if predicate tests if the current character is a space. If so, the end of the current token has been reached. The consequent Block is itself an IfStatement: if len(current) > 0: tokens.append(current) current = ' ' If the current token has at least one character, it is appended to the list of tokens in the input string and the current token is reset to the empty string. ThisIfStatement has no elif or else clauses, so if the predicate is false, there is nothing to do. For statement. A for statement provides a way of iterating through a set of values, carrying out a body block for each value. Its evaluation rule is: Python Evaluation Rule: the Expressionwhich must produce a value that is a collection. For. First evaluate Then, for each value in the collection assign the Target to that value and evaluate the Block.
  • 7. Other than the first two initializations, and the final two statements, the bulk of the tokenize procedure is contained in a for statement. The for statement intokenize header is for c in s: .... The string s is the input string, a collection of characters. So, the loop will repeat once for each character in s, and the value of c is each character in the input string (represented as a singleton string), in turn. Return statement. In Scheme, the body of a procedure is an expression and the value of that expression is the result of evaluating an application of the procedure. In Python, the body of a procedure is a block of one or more statements. Statements have no value, so there is no obvious way to decide what the result of a procedure application should be. Python's solution is to use areturn statement. The grammar for the return statement is: A return statement finishes execution of theExpression to the caller as the result. a procedure, returning the value of The last statement of the tokenizeprocedure is: return tokens. It returns the value of the tokens list to the caller.