Constants
• Fixed values such as numbers, letters, and strings, are called
  “constants” because their value does not change
• Numeric constants are as you expect
                                           >>> print(123)
• String constants use single quotes (')   123
  or double quotes (")                     >>> print(98.6)
                                           98.6
                                           >>> print('Hello world')
                                           Hello world
              Reserved Words
You cannot use reserved words as variable names / identifiers
False        await        else         import       pass
None         break        except       in           raise
True         class        finally      is           return
and          continue     for          lambda       try
as           def          from         nonlocal     while
assert       del          global       not          with
async        elif         if           or           yield
                           Variables
• A variable is a named place in the memory where a programmer can store
  data and later retrieve the data using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later statement
       x = 12.2                               x 12.2
       y = 14
                                              y 14
                           Variables
• A variable is a named place in the memory where a programmer can store
  data and later retrieve the data using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later statement
       x = 12.2                               x 12.2 100
       y = 14
       x = 100                                y 14
  Python Variable Name Rules
• Must start with a letter or underscore _
• Must consist of letters, numbers, and underscores
• Case Sensitive
    Good:    spam    eggs    spam23   _speed
    Bad:     23spam     #sign var.12
    Different:    spam    Spam   SPAM
  Mnemonic Variable Names
• Since we programmers are given a choice in how we choose our
  variable names, there is a bit of “best practice”
• We name variables to help us remember what we intend to store
  in them (“mnemonic” = “memory aid”)
• This can confuse beginning students because well-named
  variables often “sound” so good that they must be keywords
                http://en.wikipedia.org/wiki/Mnemonic
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
 What is this bit of
  code doing?
                                    a = 35.0
x1q3z9ocd = 35.0                    b =
x1q3z9afd = 12.50                   12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd   c = a *
print(x1q3p9afd)                    b
                                    print(c)
   What are these
 bits of code doing?
                                              a = 35.0
x1q3z9ocd = 35.0                              b =
x1q3z9afd = 12.50                             12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd             c = a *
print(x1q3p9afd)                              b
                                              print(c)
                         hours = 35.0
   What are these        rate = 12.50
 bits of code doing?     pay = hours * rate
                         print(pay)
           Sentences or Lines
x = 2                  Assignment statement
x = x + 2              Assignment with expression
print(x)               Print statement
Variable    Operator      Constant   Function
          Assignment Statements
• We assign a value to a variable using the assignment statement (=)
• An assignment statement consists of an expression on the
  right-hand side and a variable to store the result
                x = 3.9 * x * ( 1 - x )
A variable is a memory location             x 0.6
used to store a value (0.6)
                                           0.6                  0.6
                              x = 3.9 *    x      * ( 1     -    x )
                                                          0.4
The right side is an expression.
                                                 0.936
Once the expression is evaluated,
the result is placed in (assigned to) x.
A variable is a memory location used to
store a value. The value stored in a         x 0.6         0.936
variable can be updated by replacing the
old value (0.6) with a new value (0.936).
                                            0.6                  0.6
                                x = 3.9 *   x      * ( 1     -    x )
                                                           0.4
The right side is an expression. Once the
expression is evaluated, the result is
                                                  0.936
placed in (assigned to) the variable on
the left side (i.e., x).
Expressions…
            Numeric Expressions
                                            Operator    Operation
• Because of the lack of mathematical
  symbols on computer keyboards - we           +         Addition
  use “computer-speak” to express the          -       Subtraction
  classic math operations
                                               *       Multiplication
• Asterisk is multiplication                   /         Division
• Exponentiation (raise to a power) looks      **         Power
  different than in math                       %        Remainder
        Numeric Expressions
>>> xx = 2           >>>   jj = 23
>>> xx = xx + 2      >>>   kk = jj % 5     Operator    Operation
>>> print(xx)        >>>   print(kk)
                                              +         Addition
4                    3
>>> yy = 440 * 12    >>>   print(4 ** 3)      -       Subtraction
>>> print(yy)        64                       *       Multiplication
5280
>>> zz = yy / 1000              4R3           /         Division
>>> print(zz)              5   23             **         Power
5.28                           20             %        Remainder
                               3
             Order of Evaluation
• When we string operators together - Python must know which one
  to do first
• This is called “operator precedence”
• Which operator “takes precedence” over the others?
            x = 1 + 2 * 3 - 4 / 5 ** 6
      Operator Precedence Rules
Highest precedence rule to lowest precedence rule:
   • Parentheses are always respected                Parenthesis
                                                        Power
   • Exponentiation (raise to a power)               Multiplication
                                                       Addition
   • Multiplication, Division, and Remainder
                                                     Left to Right
   • Addition and Subtraction
   • Left to right
                             1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11.0                           1 + 8 / 4 * 5
>>>
                                 1 + 2 * 5
       Parenthesis
          Power
       Multiplication             1 + 10
         Addition
       Left to Right
                                    11
 Operator Precedence                               Parenthesis
                                                      Power
• Remember the rules top to bottom                 Multiplication
                                                     Addition
• When writing code - use parentheses              Left to Right
• When writing code - keep mathematical expressions simple enough
  that they are easy to understand
• Break long series of mathematical operations up to make them
  more clear
       What Does “Type” Mean?
• In Python variables, literals, and
  constants have a “type”
                                           >>> ddd = 1 + 4
• Python knows the difference              >>> print(ddd)
                                           5
  between an integer number and a          >>> eee = 'hello ' + 'there'
  string                                   >>> print(eee)
                                           hello there
• For example “+” means “addition” if
  something is a number and
  “concatenate” if something is a string
                                           concatenate = put together
                  Type Matters
                                   >>> eee = 'hello ' + 'there'
• Python knows what “type”         >>> eee = eee + 1
  everything is                    Traceback (most recent call last):
                                   File "<stdin>", line 1, in
• Some operations are              <module>
  prohibited                       TypeError: can only concatenate
                                   str (not "int") to str
                                   >>> type(eee)
• You cannot “add 1” to a string   <class'str'>
                                   >>> type('hello')
• We can ask Python what type      <class'str'>
  something is by using the        >>> type(1)
                                   <class'int'>
  type() function                  >>>
     Several Types of Numbers
                                         >>> xx = 1
• Numbers have two main types
                                         >>> type (xx)
                                         <class 'int'>
 - Integers are whole numbers:
                                         >>> temp = 98.6
   -14, -2, 0, 1, 100, 401233
                                         >>> type(temp)
                                         <class'float'>
 - Floating Point Numbers have
                                         >>> type(1)
 decimal parts: -2.5 , 0.0, 98.6, 14.0
                                         <class 'int'>
                                         >>> type(1.0)
• There are other number types - they
                                         <class'float'>
  are variations on float and integer
                                         >>>
Type Conversions
                                    >>> print(float(99) + 100)
• When you put an integer and       199.0
                                    >>> i = 42
  floating point in an              >>> type(i)
  expression, the integer is        <class'int'>
  implicitly converted to a float   >>> f = float(i)
                                    >>> print(f)
• You can control this with the
                                    42.0
                                    >>> type(f)
  built-in functions int() and      <class'float'>
  float()                           >>>
                Integer Division
                                       >>> print(10 / 2)
                                       5.0
                                       >>> print(9 / 2)
Integer division produces a floating   4.5
point result                           >>> print(99 / 100)
                                       0.99
                                       >>> print(10.0 / 2.0)
                                       5.0
                                       >>> print(99.0 / 100.0)
                                       0.99
This was different in Python 2.x
     String
                                 >>> sval = '123'
                                 >>> type(sval)
                                 <class 'str'>
   Conversions
                                 >>> print(sval + 1)
                                 Traceback (most recent call last):
                                   File "<stdin>", line 1, in <module>
                                 TypeError: can only concatenate str
• You can also use int() and     (not "int") to str
                                 >>> ival = int(sval)
  float() to convert between     >>> type(ival)
                                 <class 'int'>
  strings and integers           >>> print(ival + 1)
                                 124
• You will get an error if the   >>> nsv = 'hello bob'
                                 >>> niv = int(nsv)
  string does not contain        Traceback (most recent call last):
                                 File "<stdin>", line 1, in <module>
  numeric characters             ValueError: invalid literal for int()
                                 with base 10: 'x'
                  User Input
• We can instruct Python to
  pause and read data         nam = input('Who are you? ')
                              print('Welcome', nam)
  from the user using the
  input() function
• The input()  function
                                Who are you? Chuck
  returns a string
                                Welcome Chuck
Converting User Input
• If we want to read a
  number from the user, we
                                inp = input('Europe floor?')
  must convert it from a        usf = int(inp) + 1
  string to a number using a    print('US floor', usf)
  type conversion function
• Later we will deal with bad         Europe floor? 0
  input data                          US floor 1
            Comments in Python
• Anything after a # is ignored by Python
• Why comment?
  - Describe what is going to happen in a sequence of code
  - Document who wrote the code or other ancillary information
  - Turn off a line of code - perhaps temporarily
# Get the name of the file and open it
name = input('Enter file:')
handle = open(name, 'r')
# Count word frequency
counts = dict()
for line in handle:
    words = line.split()
    for word in words:
        counts[word] = counts.get(word,0) + 1
# Find the most common word
bigcount = None
bigword = None
for word,count in counts.items():
    if bigcount is None or count > bigcount:
        bigword = word
        bigcount = count
# All done
print(bigword, bigcount)
                   Summary
• Type                   • Integer Division
• Reserved words         • Conversion between types
• Variables (mnemonic)   • User input
• Operators              • Comments (#)
• Operator precedence
Exercise
           Write a program to prompt the user for hours
           and rate per hour to compute gross pay.
           Enter Hours: 35
           Enter Rate: 2.75
           Pay: 96.25