Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Announcements Python Let’s learn programming with a general purpose language (Python). Try to get help from me and tutors After we study Python, we will study JavaScript to continue with client-side web programming that we started with HTML/CSS. What to do today Start Python After that we will continue with server-side web programming with Python/Flask. Reading assignment for this slide set: Chapters 1 and 2 of Downey Break around 10:15am Python is much cleaner language to use to learn the concepts of programming than JavaScript. Also JavaScript is a special purpose language for web development. We will take a systematic approach in learning a programming language and the fundamental concepts involved in programming with Python. 1 2 Why Python? What to do today Simple, simpler than Java (which is simpler than C++) "In 2003 I started teaching at Olin College and I got to teach Python for the first time. The contrast with Java was striking. Students struggled less, learned more, worked on more interesting projects, and generally had a lot more fun." -- Allen Downey The first Python program! Highly relevant to non-CS majors Python programming environment Python is a general-purpose programming language Python packages such as NumPy, SciPy are heavily used by scientists Variables Other packages are available for various domains Is a modern language with good support Expressions and statements Popular for web applications (e.g., Facebook apps) Fun to program in Strings Widely used: becoming one of the most popular languages http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html 3 4 1 Getting started with Python First cup of Python Install Canopy, an IDE (Integrated Development Environment) using the instructions on the Course Schedule page See simple.py Interactive mode Script mode See ch2.py Can also run from the “command line” Mac: Terminal Windows: Command prompt Start with the python or ipython command Both interactive session and script mode are possible with either We will try all these different ways in class together Python files has the .py extension, e.g., simple.py We will use Python 2.7 - Textbook uses 2.7 5 The basics 6 Representing values Values 23 12.321 “Hello world!” Types integer float (real number) string (of characters) boolean (True and False) Everything on a computer reduces to numbers Letters represented by numbers (ASCII codes, see next slide) Pixel colors are three numbers (red, green, blue) So, how can Python tell all these numbers apart? By type! Type A set of values and the operations on them Examples of operators: +, -, /, *, **, %, etc. The meaning of these operators depends on the type of their operands Expressions (try these on Python interpreter) 23 * (12 + 56) 3.4/2.3 ‘Hello,’ + ‘ world!’ 7 8 2 Expression vs. Statement Represents something Python evaluates it End result is a value Does something Python executes it Need not result in a value Examples 23 2.54 (4 + 12 * 4) * 2.1 Examples print “Hello” x = 3 + 4 9 10 Type: int Type: float Type int (integer) Values: . . ., -3, -2, -1, 0, 1, 2, 3, . . . Operations: +, -, *, / ,**, %, unary – Type float (floating point number): Values: (approximations of) real numbers Operations: +, -, *, **, unary – Principle: operations on int values must yield an int Example: In Python a number with a “.” is a float literal, e.g., 3.0 Without a decimal a number is an int literal, e.g., 3 1/2 rounds result down to 0 (it computes the quotient part of division) Companion operation: % (it computes the remainder part of division) 8 % 5 evaluates to 3, remainder when dividing 8 by 5 The meaning for floats differs from that of ints Example: 1.0/2.0 evaluates to 0.5 (cf. 1/2 evaluates to 0) Exponent notation is useful for large (or small) values -22.51e6 is -22.51 * 106 or -2251000 22.51e-6 is 22.51 * 10-6 or 0.00002251 Operator / is not an int operation in Python 3 (use // instead) 11 12 3 Floats have finite precision Type: str Python stores floats as binary fractions Integer mantissa times a power of 2 Example: 1.25 is 5 * 2-2 (5 is mantissa and -2 is power here) Type str for strings Values: any sequence of characters Operation(s): + (concatenation) Impossible to write most real numbers this way exactly Similar to problem of writing 1.0/3.0 with decimals Python chooses the closest binary fraction it can String literal: sequence of characters in quotes Double quotes: “ abc3$#@(9”, “Hello world!” Single quotes: ‘Hello world!’ This approximation results in representation error When combined in expressions, the error can get worse Example: try 0.1 + 0.2 to the Python prompt Concatenation can only apply to strings “ab” + “cd” evaluates to “abcd” “ab” + 2 produces an error “ab” + str(2) evaluates to “ab2” 13 Type: bool Converting values between types Type boolean or bool Values: True, False Operations: not, and, or 14 Basic form: type(value) float(2) converts value 2 to type float (value now 2.0) int(3.9) converts value 3.9 to type int (value now 3) Explicit conversion is also called “casting” not b: True if b is false and False if b is true a and b: True if both a and b are true; False otherwise a or b: True if a is true or b is true; False otherwise Narrow to wide: bool è int è float Widening: Python does automatically if needed Often come from comparing int or float values Order comparison: i < j, i <= j, i >= j, i > j Equality, inequality: i == j, i != j (note: = means something different!) Example: 1 / 2.0 evaluates to 0.5 (by casting 1 to float) True + 3 evaluates to 4 False + 3 evaluates to 3 Narrowing: Python never does this automatically, we can force it though 15 Example: float(int(3.9)) evaluates to 3.0 16 4 Operator precedence Type: set of values and the operations on them Type int: Values: integers Ops: +, -, *, /, %, **, … What is the difference between the following? 2 * (1 + 3) 2 + 1 * 3 Type float: Values: real numbers Ops: +, -, *, /, **, … Operations are performed in a set order Parentheses make the order explicit What happens when there are no parentheses? There should be no ambiguity in terms of ordering of evaluation Type bool: Values;: True, False Ops: not, and, or Type: str: Values: string literals with double quotes or single quotes Ops: + (concatenation) (Will see more types in the coming weeks) Operator precedence: the fixed order Python processes operators in absence of parentheses 17 Precedence of Python operators Exponentiation: ** Unary operators: +, Binary arithmetic: *, /, % 18 Variables and assignments A variable Is a named memory location Contains a value Can be used in expressions highest at the top n same line, same precedence n left-to-right among the same n Binary arithmetic: +, - Variables are created by assignment statements ‘=‘ is the assignment operator Examples: b = 5 // assign 5 to b h = 4.5 area = b * h Comparisons: <, >, <=, >= Equality relations: ==, != Logical not Logical and Logical or 19 b = 3 area = b * h // repeated assignment into // the same variable is acceptable 20 5 Dynamic typing Dynamic typing (cont.) Python is a dynamically typed language A variable can hold values of any type A variable can hold different types of values at different times Use type(x) to find out the type of the value x at a given time Use names of types for conversion, comparison Often want to track the type in a variable What is the result of evaluating x/y? Depends on whether x, y are int or float values Use the expression type(<expression>) to get type type(2) evaluates to <type ‘int’> type(x) evaluates to type of contents of x The following is acceptable in Python x=1 # x contains an int value 1 x = x / 2.0 # x now contains a float value 0.5 x = ‘apple’ # x now contains a str value ‘apple’ Can use in a boolean expression to test type type(‘abc’) == str evaluates to True a == b tests if a is equal to b Alternative is a statically typed language (e.g., Java) Each variable is restricted to values of just one type for its entire life time 21 String: text as a value Comments string: a quoted sequence of characters ‘abc d’ (Python prefers) “abc d” (most other languages) Comments are ignored by python interpreter Used to add a note to your code for readability Single line comments starts with a # # This line is a comment x = x + 1 # This is a partial line comment How to write quotes in quotes? Delineate with “other quote” Examples 22 “‘“ ‘“‘ “a’b’c” // third character is b ‘a”bb”c’ Multi-line comments with “”” … “”” “”” This is the first line of a multi-line comment. This is an example of a comment in three lines. “”” 23 24 6 Today’s extra Do these before next class If you are using a Mac, try “System Preferences” under the “Apple symbol” at the top left corner of your screen Finish reading Chapter 2 Start reading Chapter 3 of Downey Try “Mission Control” and “Hot Corners” in particular Do the Unix Lab if you are using a Mac Do the DOS Lab if you are using a Windows machine Next time Functions (Chapter 3) 25 26 7