CHAPTER 1 Introduction to Computers and Programmin g

  • Slides: 27
Download presentation
CHAPTER 1 Introduction to Computers and Programmin g Copyright © 2012 Pearson Education, Inc.

CHAPTER 1 Introduction to Computers and Programmin g Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Compilers and Interpreters • Programs written in high-level languages must be translated into machine

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 Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Compilers and Interpreters (cont’d. ) • Interpreter: translates and executes instructions in high-level language

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 Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

Compilers and Interpreters (cont’d. ) Executing a high-level program with an interpreter Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Compiling and interpreting n Many languages require you to compile (translate) your program into

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

Using Python • Python must be installed and configured prior to use – One

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 Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Interactive Mode • When you start Python in interactive mode, you will see a

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 Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Writing Python Programs and Running Them in Script Mode • Statements entered in interactive

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 Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Python Scripts • When you call a python program from the command line the

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 Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The IDLE Programming Environment • IDLE (Integrated Development Learning Environment): single program that provides

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 Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

IDLE Development Environment • IDLE is an Integrated Deve. Lopment Environment for Python, typically

IDLE Development Environment • IDLE is an Integrated Deve. Lopment Environment 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, persistent breakpoints, and call stack visibility Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Programming basics n n code or source code: The sequence of instructions in a

Programming basics n n 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. n output: The messages printed to the user by a program. n console: The text box onto which output is printed. n Some source code editors pop up the console as an external window, and others contain their own console window. 12

The Basics

The Basics

A Code Sample (in IDLE) x = 34 - 23 # A comment. y

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 n Indentation matters to code meaning n n Block

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

Basic Datatypes n Integers (default for numbers) z = 5 // 2 # Answer

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

Whitespace is meaningful in Python: especially indentation and placement of newlines n. Use a

Whitespace is meaningful in Python: especially indentation and placement of newlines n. 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 n • • 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 n

Comments Start comments with #, rest of line is ignored n Can include a

Comments Start comments with #, rest of line is ignored n Can include a “documentation string” as the first line of a new function or class you define n Development environments, debugger, and other tools use it: it’s good style to include one n 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 n Binding a variable in Python means setting a name to hold a

Assignment n Binding a variable in Python means setting a name to hold a reference to some object n n Names in Python do not have an intrinsic type, objects have types n n Assignment creates references, not copies 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 n You can assign to multiple names at the same time >>> x,

Assignment n 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 n Assignments can be chained >>> a = b = x = 2

Naming Rules n Names are case sensitive and cannot start with a number. They

Naming Rules n Names are case sensitive and cannot start with a number. They can contain letters, numbers, and underscores. bob n Bob _bob _2_bob_2 Bo. B 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 recommended naming conventions njoined_lower for functions, methods

Naming conventions The Python community has these recommended naming conventions njoined_lower for functions, methods and, attributes njoined_lower or ALL_CAPS for constants n. Studly. Caps for classes ncamel. Case only to conform to pre-existing conventions n. Attributes: interface, _internal, __private

Accessing Non-Existent Name Accessing a name before it’s been properly created (by placing it

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 -toplevely Name. Error: name ‘y' is not defined >>> y = 3 >>> y 3

Expressions n expression: A data value or set of operations to compute a value.

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

n Boolean Operations — and, or, not Operation x or y x and y

n Boolean Operations — and, or, not Operation x or y x and y n not x Comparisons 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 25

n Numeric Types — int, float Operation x+y x-y x*y x/y x // y

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

Math commands n n Python has useful commands for performing calculations. Command name Description

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