Compilers and Interpreters

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

Introduction to C Programming
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to Python
INTRODUCTION TO PYTHON PART 1 CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
CSC 9010: Natural Language Processing
1 Introduction to Programming with Python. 2 Some influential ones: FORTRAN science / engineering COBOL business data LISP logic and AI BASIC a simple.
INLS 560 – V ARIABLES, E XPRESSIONS, AND S TATEMENTS Instructor: Jason Carter.
Python Programming Fundamentals
Introduction to Python
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Fundamentals of Python: First Programs
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CPTR 124 Review for Test 1. Development Tools Editor Similar to a word processor Allows programmer to compose/save/edit source code Compiler/interpreter.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Input, Output, and Processing
Computer Science 101 Introduction to Programming.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Variables, Expressions and Statements
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
CSC 1010 Programming for All Lecture 2 Introduction to Python Some material based on material from Marty Stepp, Instructor, University of Washington.
Python Let’s get started!.
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 2 Writing Simple Programs
Fundamentals of Programming I Overview of Programming
C++ First Steps.
Topics Designing a Program Input, Processing, and Output
Topics Introduction to Functions Defining and Calling a Void Function
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Topics Introduction Hardware and Software How Computers Store Data
Python Let’s get started!.
Introduction to Python
Completing the Problem-Solving Process
Chapter 2 - Introduction to C Programming
Introduction Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
Topics Introduction to Repetition Structures
Revision Lecture
Presented By S.Yamuna AP/IT
Variables, Expressions, and IO
Chapter 2 - Introduction to C Programming
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Chapter 2 - Introduction to C Programming
Topics Introduction to File Input and Output
Introduction to C++ Programming
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Chapter 2 - Introduction to C Programming
Introduction to Python
Topics Introduction Hardware and Software How Computers Store Data
T. Jumana Abu Shmais – AOU - Riyadh
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Introduction to programming with Python
Chapter 2 - Introduction to C Programming
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Introduction to Programming with Python
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 2 - Introduction to C Programming
Chapter 1: Programming Basics, Python History and Program Components
Topics Introduction to File Input and Output
Introduction to Programming with Python
Introduction to C Programming
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Compilers and Interpreters Programs written in high-level languages must be translated into machine language to be executed Compiler: translates high-level language program into separate machine language program Machine language program can be executed at any time

Compilers and Interpreters (cont’d.) Interpreter: translates and executes instructions in high-level language program Used by Python language Interprets one instruction at a time No separate machine language program Source code: statements written by programmer Syntax error: prevents code from being translated

Compilers and Interpreters (cont’d.) Executing a high-level program with an interpreter

Compiling and interpreting Many languages require you to compile (translate) your program into a form that the machine understands. Python is instead directly interpreted into machine instructions. compile execute output source code Hello.java byte code Hello.class interpret output source code Hello.py

Using Python Python must be installed and configured prior to use One of the items installed is the Python interpreter Python interpreter can be used in two modes: Interactive mode: enter statements on keyboard Script mode: save statements in Python script

Interactive Mode When you start Python in interactive mode, you will see a prompt Indicates the interpreter is waiting for a Python statement to be typed Prompt reappears after previous statement is executed Error message displayed If you incorrectly type a statement Good way to learn new parts of Python

Writing Python Programs and Running Them in Script Mode Statements entered in interactive mode are not saved as a program To have a program use script mode Save a set of Python statements in a file The filename should have the .py extension To run the file, or script, type python filename at the operating system command line

Python Scripts When you call a python program from the command line the interpreter evaluates each expression in the file Familiar mechanisms are used to provide command line arguments and/or redirect input and output Python also has mechanisms to allow a python program to act both as a script and as a module to be imported and used by another python program

The IDLE Programming Environment IDLE (Integrated Development Learning Environment): single program that provides tools to write, execute and test a program Automatically installed when Python language is installed Runs in interactive mode Has built-in text editor with features designed to help write Python programs

IDLE Development Environment IDLE is an Integrated DeveLopment Environ-ment for Python, typically used on Windows Multi-window text editor with syntax highlighting, auto-completion, smart indent and other. Python shell with syntax highlighting. Integrated debugger with stepping, persis- tent breakpoints, and call stack visi- bility

Programming basics code or source code: The sequence of instructions in a program. syntax: The set of legal structures and commands that can be used in a particular programming language. output: The messages printed to the user by a program. console: The text box onto which output is printed. Some source code editors pop up the console as an external window, and others contain their own console window.

The Basics

A Code Sample (in IDLE) x = 34 - 23 # A comment. y = “Hello” # Another one. z = 3.45 if z == 3.45 or y == “Hello”: x = x + 1 y = y + “ World” # String concat. print (x) print (y)

Enough to Understand the Code Indentation matters to code meaning Block structure indicated by indentation First assignment to a variable creates it Variable types don’t need to be declared. Python figures out the variable types on its own. Assignment is = and comparison is == For numbers + - * / % are as expected Special use of + for string concatenation and % for string formatting (as in C’s printf) Logical operators are words (and, or, not) not symbols The basic printing command is print

Basic Datatypes Integers (default for numbers) Floats Strings z = 5 // 2 # Answer 2, integer division Floats x = 3.456 Strings Can use “” or ‘’ to specify with “abc” == ‘abc’ Unmatched can occur within the string: “matt’s” Use triple double-quotes for multi-line strings or strings than contain both ‘ and “ inside of them: “““a‘b“c”””

Whitespace Whitespace is meaningful in Python: especially indentation and placement of newlines Use a newline to end a line of code Use \ when must go to next line prematurely No braces {} to mark blocks of code, use consistent indentation instead First line with less indentation is outside of the block First line with more indentation starts a nested block Colons start of a new block in many constructs, e.g. function definitions, then clauses

Comments Start comments with #, rest of line is ignored Can include a “documentation string” as the first line of a new function or class you define Development environments, debugger, and other tools use it: it’s good style to include one def fact(n): “““fact(n) assumes n is a positive integer and returns facorial of n.””” assert(n>0) if n==1 return 1 else n*fact(n-1)

Assignment Binding a variable in Python means setting a name to hold a reference to some object Assignment creates references, not copies Names in Python do not have an intrinsic type, objects have types Python determines the type of the reference automatically based on what data is assigned to it You create a name the first time it appears on the left side of an assignment expression: x = 3 A reference is deleted via garbage collection after any names bound to it have passed out of scope Python uses reference semantics (more later)

Assignment You can assign to multiple names at the same time >>> x, y = 2, 3 >>> x 2 >>> y 3 This makes it easy to swap values >>> x, y = y, x Assignments can be chained >>> a = b = x = 2

Naming Rules Names are case sensitive and cannot start with a number. They can contain letters, numbers, and underscores. bob Bob _bob _2_bob_ bob_2 BoB There are some reserved words: and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while

Naming conventions The Python community has these recommend-ed naming conventions joined_lower for functions, methods and, attributes joined_lower or ALL_CAPS for constants StudlyCaps for classes camelCase only to conform to pre-existing conventions Attributes: interface, _internal, __private

Accessing Non-Existent Name Accessing a name before it’s been properly created (by placing it on the left side of an assignment), raises an error >>> y Traceback (most recent call last): File "<pyshell#16>", line 1, in -toplevel- y NameError: name ‘y' is not defined >>> y = 3 3

Expressions expression: A data value or set of operations to compute a value. Examples: 1 + 4 * 3 42 Arithmetic operators we will use: + - * / addition, subtraction/negation, multiplication, division % modulus, a.k.a. remainder ** exponentiation precedence: Order in which operations are computed. * / % ** have a higher precedence than + - 1 + 3 * 4 is 13 Parentheses can be used to force a certain order of evaluation. (1 + 3) * 4 is 16

Boolean Operations — and, or, not Comparisons Operation x or y x and y not x Operation Meaning < strictly less than <= less than or equal > strictly greater than >= greater than or equal == equal != not equal is object identity is not negated object identity

Numeric Types — int, float Operation Result x + y sum of x and y x - y difference of x and y x * y product of x and y x / y quotient of x and y x // y floored quotient of x and y x % y remainder of x / y -x x negated +x x unchanged abs(x) absolute value or magnitude of x int(x) x converted to integer float(x) x converted to floating point divmod(x, y) the pair (x // y, x % y) pow(x, y) x to the power y x ** y

Math commands Python has useful commands for performing calculations. To use many of these commands, you must write the following at the top of your Python program: from math import * Command name Description abs(value) absolute value ceil(value) rounds up cos(value) cosine, in radians floor(value) rounds down log(value) logarithm, base e log10(value) logarithm, base 10 max(value1, value2) larger of two values min(value1, value2) smaller of two values round(value) nearest whole number sin(value) sine, in radians sqrt(value) square root Constant Description e 2.7182818... pi 3.1415926...