2009_Puython_Variables,Expressions,Statements

download 2009_Puython_Variables,Expressions,Statements

of 20

Transcript of 2009_Puython_Variables,Expressions,Statements

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    1/20

    . .

    Variables, Operators,

    Expression

    UniversityofSeoulDe artmentoMaterialsScience&En ineerin

    [email protected]

    Contents & Homework

    Contents:

    - Think Python - How to Think Like a Computer Scientist

    (http://www.greenteapress.com/thinkpython/thinkpython.html)

    Think Python Ch. 2

    -

    - Read: 1

    - Install Python

    Lab:

    - Think Python Ch. 2 Exercises

    Lecture 1 2

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    2/20

    HW#1 (contd): Python Installation

    http://www.python.org download

    Lecture 1 3

    What is a Program?

    A sequence of instructions that specifies how to perform a

    .

    npu Output

    a

    Conditional execution

    epet t on

    Lecture 1 4

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    3/20

    What is Programming Language?

    Programming

    LanguagesPeople Computers

    Natural languages

    e.g. Korean, English, Spanish, German, Chinese, etc.

    Formal languages

    e.g. mathematical expressions, chemical formulae, programming languages

    y o no use na ura anguages as programm ng anguages

    Ambiguity

    Literalness

    Lecture 1 5

    Classification of Programming Languages

    High-level languages

    e.g. y on, or ran, , , ava, e c.

    Low-level languages

    High-level Low-level translation

    Interpreters

    Compilers

    Python uses both processes, but because of the way programmers interact with

    Lecture 1

    it, it is usually considered an interpreted language.

    6

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    4/20

    History of Programming Languages

    Fortran 95

    Lecture 1 7Fortran 2003

    Programming Language Ranking

    TIOBE Index (http://www.tiobe.com)

    Lecture 1 8

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    5/20

    Programming Language Ranking

    TIOBE Index (http://www.tiobe.com)

    Lecture 1 9

    Brief History of Python

    Guido van Rossum wrote Python in late 1998 ~

    early 1990s as ascriptlanguage for the

    Amoeba OS Python design was inspired by C, Modula-3,

    and particularly the educational language ABC

    Public release in 1991

    Name from the Monty Pythons Flying Circus

    Lecture 1 10

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    6/20

    Advantages of Python

    Easy to learn

    Easy to program

    Ideal for scripting steering

    Graphics

    Free

    Platform-independent

    Interactive language runs much more slowly than compiled one

    (loss in computational time), but one can get results immediately,can find/rectify errors quickly (gain in human time)

    etc. etc. (more later)

    Lecture 1 11

    Values

    va ue s one o t e un amenta t ngs--- e a etter or a num er---t at a

    program manipulates. e.g. 2 and "Hello, World!".

    These values belong to different types: 2 is an integer, and "Hello, World!" isa string, so-called because it contains a string of letters. You (and the

    .

    The print statement also works for integers.

    >>> print 4

    4

    Lecture 1 12

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    7/20

    No , for large integers

    ,

    groups of three digits, as in 1,000,000. This is not a legal integer in Python, but

    it is legal:

    >>> print 1,000,000

    1 0 0

    Python interprets 1,000,000 as a list of three items to be printed. So remember

    not to put commas in your integers.

    Lecture 1 13

    Types

    If you are not sure what type a value has, the interpreter can tell you.

    >>> type("Hello, World!")

    >>> type(17)

    Not surprisingly, strings belong to the type str and integers belong to the type

    . ,

    float, because these numbers are represented in a format called floating-point.

    .

    Lecture 1 14

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    8/20

    Types (cntd)

    " " " ". ,

    quotation marks like strings.

    >>> type("17")

    >>> t e("3.2")

    They're strings.

    Lecture 1 15

    Core built-in object types preview

    Lecture 1 16

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    9/20

    Variables & Assignments

    One of the most powerful features of a programming language is the ability to

    . .

    generally, identifier variables, functions, classes, modules, and other objects)

    The assignment statement creates new variables and gives them values:

    >>> message = "What's up, Doc?"

    >>> n = 17

    =

    >>> pi = 3.14159

    , ,

    though it uses the same character). Assignment operators link a name, on the

    left hand side of the operator, with a value, on the right hand side. This is why

    >>> 17 = n

    you will get an error if you enter:

    Lecture 1 17

    State diagram

    common way o represen var a es on paper s o wr e e name w an

    arrow pointing to the variable's value. This kind of figure is called a state

    diagrambecause it shows what state each of the variables is in (think of it as

    the variable's state of mind). This diagram shows the result of the assignment

    statements:

    Lecture 1 18

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    10/20

    Printing Variables

    >>> print message'

    .

    ,

    >>> print n

    17

    >>> print pi

    3.14159

    Lecture 1 19

    Types of Variables

    .

    again, we can ask the interpreter what they are

    >>> type(n)

    >>> type(pi)

    The type of a variable is the type of the value it refers to.

    Lecture 1 20

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    11/20

    Variable Names

    they document what the variable is used for.

    Variable names can be arbitrarily long. They can contain both letters and

    numbers, but they have to begin with a letter.

    It is legal to use uppercase letters. If you use them, remember that case matters:

    Bruce and bruce are different variables.

    The underscore character (_) can appear in a name. It is often used in names

    , _ _ _ _ _ .

    Lecture 1 21

    Variable Names (contd)

    >>> 76trombones = "big parade"

    SyntaxError: invalid syntax>>> more$ = 1000000

    S ntaxError: invalid s ntax

    >>> class = "Computer Science 101"

    SyntaxError: invalid syntax

    Lecture 1 22

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    12/20

    Keywords (Reserved Words)

    .

    language's rules and structure, and they cannot be used as variable names.

    Python has 29 keywords:

    and elif global or yield

    assert else if pass

    break except import print

    class exec in raise

    continue finally is return

    def for lambda try

    -

    e rom no w e

    Lecture 1

    . . .

    your variable names and you don't know why, see if it is on this list.

    23

    Statements

    A statement is an instruction that the Python interpreter can execute. We have

    .

    on the command line, Python executes it and displays the result, if there is one.

    - The result of a print statement is a value.

    - Assignment statements don't produce a result.

    Lecture 1 24

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    13/20

    Script

    A script usually contains a sequence of statements. If there is more than one

    , .

    For example, using an editor of your choice, you can write the following script:

    rint 1

    x = 2

    print x

    After saving this as a file, e.g. "try.py, you can run the script:

    $ python try.py

    and will get the following result:

    1

    2Again, the assignment statement produces no output.

    Lecture 1 25

    Evaluating Expressions

    An expression is a combination of values, variables, and operators. If you type

    ,

    result:

    >>> 1 + 1

    2 The expression result isimmediately echoed back.

    ,

    appear on the right hand side of assignment statements. A value all by itself is a

    simple expression, and so is a variable.

    >>> 17

    17

    x

    2

    Lecture 1 26

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    14/20

    Evaluating Expressions vs. Printing

    Confusingly, evaluating an expression is not quite the same thing as printing a

    .

    >>> message = "What's up, Doc?"

    >>> print message

    What's up, Doc?

    >>> message

    "What's up, Doc?"

    the expression, which in this case is the

    contents of the string.

    When the Python shell displays the value

    of an expression, it uses the same formatyou wou use to enter a va ue. In t e case

    of strings, that means that it includes the

    quotation marks. Equivalent to

    Lecture 1

    >>> pr n repr message

    27

    Evaluating Expressions in a Script

    ', ,

    anything. The script

    173.2

    "Hello World!"

    1 + 1

    produces no output at all.

    : ow wou you c ange e scr p o sp ay e va ues o ese our express ons

    Lecture 1 28

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    15/20

    Operators and Operands

    Operators are special symbols that represent computations like addition and

    . .

    The following are all legal Python expressions whose meaning is more or less

    clear:

    20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)

    The symbols +, , and /, and the use of parenthesis for grouping, mean inPython what they mean in mathematics. The asterisk (*) is the symbol for

    **, .

    When a variable name appears in the place of an operand, it is replaced with itsvalue before the operation is performed.

    Lecture 1 29

    Operators and Operands (contd)

    Addition, subtraction, multiplication, and exponentiation all do what you expect,

    .

    unexpected result:

    >>> minute = 59

    >>> m nute0

    , . , .

    for the discrepancy is that Python is performing integer division.

    When both of the operands are integers, the result must also be an integer, and

    by convention, integer division always rounds down, even in cases like this

    where the next inte er is ver close.

    floating-point division

    Lecture 1 30

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    16/20

    Order of Operations

    When more than one operator appears in an expression, the order of evaluation

    .

    for its mathematical operators that mathematics does.

    1. Parentheses have the highest precedence and can be used to force an expression

    to evaluate in the order you want. Since expressions in parentheses are

    eva ua e rs , 2*(3-1) s 4, an (1+1)**(5-2) s . ou can a so use

    parentheses to make an expression easier to read, as in (minute*100)/60,

    even though it doesn't change the result.

    2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and3*1**3 is 3 and not 27.

    Lecture 1 31

    Order of Operations (contd)

    . u p ca on an v s on ave e same prece ence, w c s g er an

    Addition and Subtraction, which also have the same precedence. So 2*3-1

    yields 5 rather than 4, and 2/3-1 is -1, not 1 (remember that in integer division,

    2/3=0).

    4. Operators with the same precedence are evaluated from left to right. So in the

    expression minute*100/60, the multiplication happens first, yielding

    5900 60 which in turn ields 98. If the o erations had been evaluated from

    right to left, the result would have been 59*1, which is 59, which is wrong.

    The acronym PEMDAS is a useful way to remember the order of operations.

    Lecture 1 32

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    17/20

    Operations on Strings

    In general, you cannot perform mathematical operations on strings, even if the

    .

    type string):

    message-1 "Hello"/123 message*"Hello" "15"+2

    Interestingly, the + operator does work with strings, although it does not do

    exactl what ou mi ht ex ect. For strin s the + o erator re resents

    concatenation, which means joining the two operands by linking them end-to-

    end. For example:

    fruit = "banana"

    baked_good = " nut bread"

    print fruit + baked_good

    The output of this program is banana nut bread. The space before the word

    nut is part of the string, and is necessary to produce the space between the

    Lecture 1

    conca ena e s r ngs.

    33

    Operations on Strings: *

    The * operator also works on strings; it performs repetition. For example,

    'Fun'*3 is 'FunFunFun'. One of the o erands has to be a strin the other has

    to be an integer.

    On one hand, this interpretation of+ and * makes sense by analogy withaddition and multiplication. Just as 4*3 is equivalent to 4+4+4, we expect

    "Fun"*3 to be the same as "Fun"+"Fun"+"Fun", and it is.

    On the other hand, there is a significant way in which string concatenation and

    repe on are eren rom n eger a on an mu p ca on. an you n

    of a property that addition and multiplication have that string concatenation and

    repetition do not?

    Lecture 1 34

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    18/20

    Other Operations & Precedence

    In addition to the numeric operators, there exist:

    Comparison operations

    Bitwise operations

    We will study comparison and logical operators in more detail at

    P thon lecture #3.

    Lecture 1 35

    Summary: operators & precedence

    High

    Lecture 1 36

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    19/20

    Composition

    So far, we have looked at the elements of a program---variables, expressions,

    --- , .

    One of the most useful features of programming languages is their ability to

    take small building blocks and compose them. For example, we know how to

    add numbers and we know how to print; it turns out we can do both at the same

    time:

    >>> print 17 + 3

    Composition makes it possible to express complex computations neatly and

    concisely.

    Lecture 1 37

    Composition (contd)

    ', ,

    actually happening at the same time. The point is that any expression involving

    numbers, strings, and variables can be used inside a print statement. e.g:

    -

    print "Number of minutes since midnight: ", hour*60+minute

    statement:

    = *

    Warning: There are limits on where you can use certain expressions. For

    , -

    name, not an expression. So, the following is illegal: minute+1 = hour.

    Lecture 1 38

  • 7/28/2019 2009_Puython_Variables,Expressions,Statements

    20/20

    Comments

    As programs get bigger and more complicated, they get more difficult to read.Formal languages are dense, and it is often difficult to look at a piece of codeand figure out what it is doing, or why. For the programmer or for futureprogrammers who might use this code, add notes to your programs to explain innatural language what the program is doing.

    These notes are called comments, and they are marked with the # symbol:

    # compute the percentage of the hour that has elapsed

    percentage = (minute * 100) / 60

    You can also put comments at the end of a line:

    percentage = (minute * 100) / 60 # caution: integer division

    Everything from the # to the end of the line is ignored---it has no effect on theprogram.

    Lecture 1 39

    Summary

    1. Introduction

    .

    3. Variables

    4. Variable names & keywords

    .

    6. Evaluating expressions

    6. Operators and operands

    7. O erator recedence

    8. Composition

    9. Comments