User Tools

Site Tools


python:dierbach:chapter_2_data_and_expressions

This is an old revision of the document!


View page as slide show

Data and Expressions

Mithat Konar
based on Dierbach's Introduction to Computer Science using Python.

Contents

  • Literals
  • Variables and identifiers
  • Operators
  • Expressions
  • Data types

Literals

What is a literal?

  • literal: a sequence of one or more characters that stands for itself.
  • numeric literal: contains only the digits 0–9, a sign character (1 or 2) and a optional decimal point.
    • integer versus floating point value
    • e for scientific notation
    • 3, -42, +98.6, 6.033e23

Number ranges

  • Floating point values have limited range and precision.
  • IEEE 754: ±10-308 to ±10308 with 16 to 17 digits of precision.
  • arithmetic overflow: results when operation causes number to be “too big”.
>>> 1.5e200 * 2.0e210
inf
  • arithmetic underflow: results when operation causes number to be “too small”.
>>> 1.0e-300 / 1.0e100
0.0

Floating point numbers are an approximation

  • Limited precision means actual values are approximations.
>>> 6 * 1/10
0.6
>>> 6 * (1/10)
0.6000000000000001

Formatting output

  • format() produces a string version of a value with a specific number of decimal places.
  • format specifier says how many places and format.
>>> 12/5
2.4
>>> format(12/5, '.2f')      # 2 places, floating point
'2.40'
>>> format(2 ** 100, '.6e')  # 6 places, scientific notation
'1.267651e 1 30'
>>> format(13402.25, ',.2f') # optional comma
'13,402.25'

String literals

  • Use either single-quote or double-quote.
greeting = 'Hi there'
"Vernacular nepotism is fractious."
'A'
"A"
  • Clever use:
msg = 'She said, "Yellow."'
msg = "She's making a radio."

Character codes

  • Characters need to be encoded as (binary) numbers.
  • Python uses UTF-8 by default.
  • ord() translates a single character into its UTF-8 code.
  • chr() converts a UTF-8 code into a character.
>>> ord('1')
49
>>> ord('2')
50
>>> ord('a')
97
>>> ord('A')
65

Control characters

  • control characters: non-printing characters used to control display of output.
  • Represented with escape sequences (backslash in Python).
  • Most popular escape sequence is the newline control: '\n'.
>>> print('Eat\nMore\nElderberries')
Eat
More
Elderberries

String formatting

  • Format strings with format( value, format_specifier )
format('Hello', '<16')  # left aligned field 16 characters wide
'Hello           '
 
format('Hello', '>16')  # right aligned field 16 characters wide
'           Hello'
 
format('Hello', '.>16') # fill with '.'
'...........Hello'

Implicit Line Joining

  • What to do with long lines in source code?
  • implicit joining: you can break the line at some points without messing up logic or syntax.
print('Name:', student_name, 'Address:', student_address,
      'Number of Credits:', total_credits, 'GPA:', current_gpa)
  • Doesn’t work to break up a string.

Explicit Line Joining

  • explicit joining (backslash) can be used in some situations where implicit joining won’t.
num_seconds = num_hours * 60 * 60 + \
              num_minutes * 60 
  • Also doesn’t work to break up strings.

Silly encoding example

# This program displays the Unicode encoding for 'Hello World!
 
# program greeting
print('The Unicode encoding for "Hello World!" is:')
 
# output results
print(ord('H'), ord('e'), ord('l'), ord('l'), ord('o'), ord(' '),
      ord('W'), ord('o'), ord('r'), ord('l'), ord('d'), ord('!'))

Variables and Identifiers

What is a variable?

  • variable: a name associated with a value.
       +--------+
num -->|   10   |
       +--------+

Assignment

  • assignment: take the value resulting from the expression on the right and copy it into the variable on the left.
  • assignment operator: = in Python.
    • = is not “equals”!
foo = 7
num = 1 + foo
foo = foo + 1

Variable reassignment

num = 10    #        +--------+
k = num     # num -->|   10   |
            #   k -->|        | 
            #        +--------+
k = 20      #        +--------+
            # num -->|   10   |
            #        +--------+
            #        +--------+
            #   k -->|   20   |
            #        +--------+

id()

  • Use id() to see if two variables are pointing to the same thing.
>>> num = 10
k = num
>>> id(num)
??? # some number
>>> id(k)
??? # same number as above
k = 20
>>> id(num)
??? # same as before
>>> id(k)
??? # different

What is an identifier?

  • identifier: a sequence of one or more characters used to provide a name for a given program element.
  • identifier: names of things.
  • Rules of the name:
    • letters, digits, and the underscore character only (no spaces)
    • can’t start with a digit
    • don’t use underscore for the first character for now
    • can be as long as you want

Keywords and help

  • keyword an identifier that has predefined meaning in a programming language.
  • You can’t use a keyword as your own identifier in Python.
  • Get a list of keywords:
>>> help()
help> keywords
...
help> quit
>>> 
  • Things you think should be keywords are not!
  • Check “special” words using 'testword' in dir(__builtins__)

Example: Restaurant Tab Calculation

RestaurantTab.py

# Restaurant Tab Calculation Program
# This program will calculate a restaurant tab with a gift certificate
 
# initialization
tax = 0.08
 
# program greeting
print('This program will calculate a restaurant tab for a couple with')
print('a gift certificate, with a restaurant tax of', tax * 100, '%\n')
 
# get amount of gift certificate
amt_certificate = float(input('Enter amount of the gift certificate: '))
 
# cost of ordered items
print('Enter ordered items for person 1')
 
appetizer_per1 = float(input('Appetizier: '))
entree_per1 = float(input('Entree: '))
drinks_per1 = float(input('Drinks: '))
dessert_per1 = float(input('Dessert: '))
 
print('\nEnter ordered items for person 2')
 
appetizer_per2 = float(input('Appetizier: '))
entree_per2 = float(input('Entree: '))
drinks_per2 = float(input('Drinks: '))
dessert_per2 = float(input('Dessert: '))
 
# total items
amt_person1 = appetizer_per1 + entree_per1 + drinks_per1 + dessert_per1
amt_person2 = appetizer_per2 + entree_per2 + drinks_per2 + dessert_per2
 
# compute tab with tax
items_cost = amt_person1 + amt_person2
tab = items_cost + items_cost * tax
 
# display amount owe
print('\nOrdered items: $', format(items_cost, '.2f'))
print('Restaurant tax: $', format(items_cost * tax, '.2f'))
print('Tab: $', format(tab - amt_certificate, '.2f'))
print('(negative amount indicates unused amount of gift certificate)')

Operators

What Is an Operator?

operator: a symbol that represents an operation that may be performed on one or more operands. binary operator: takes two operands unary operator: takes one operand

Arithmetic operators

Demonstration of simple table syntax.

RightLeft Center Default
1212 12 12
123123 123 123
11 1 1
python/dierbach/chapter_2_data_and_expressions.1469756187.txt.gz · Last modified: 2016/07/29 01:36 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki