View page as slide show

Contents

Literals

What is a literal?

Number ranges

>>> 1.5e200 * 2.0e210
inf
>>> 1.0e-300 / 1.0e100
0.0

Floating point numbers are an approximation

>>> 6 * 1/10
0.6
>>> 6 * (1/10)
0.6000000000000001

Formatting output

>>> 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

greeting = 'Hi there'
"Vernacular nepotism is fractious."
'A'
"A"
msg = 'She said, "Yellow."'
msg = "She's making a radio."

Character codes

>>> ord('1')
49
>>> ord('2')
50
>>> ord('a')
97
>>> ord('A')
65

Control characters

>>> print('Eat\nMore\nElderberries')
Eat
More
Elderberries

String formatting

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

print('Name:', student_name, 'Address:', student_address,
      'Number of Credits:', total_credits, 'GPA:', current_gpa)

Explicit Line Joining

num_seconds = num_hours * 60 * 60 + \
              num_minutes * 60 

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?

       +--------+
num -->|   10   |
       +--------+

Assignment

foo = 7
num = 1 + foo
foo = foo + 1

Variable reassignment

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

id()

>>> 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?

Keywords and help

>>> help()
help> keywords
# table of keywords appears
help> quit
>>> 

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

symbol operator example result
-x negation -10 -10
x + y addition 10 + 25 35
x - y subtraction 10 - 25 -15
x * y multiplication 10 * 5 50
x / y division 25 / 10 2.5
x // y truncating div. 25 // 10 2
25 // 10.0 2.0
x % y modulus 25 % 10 2.0
x ** y exponentiation 10 ** 2 100

Example: Your Place in the Universe

PlaceInUniverse.py

# Your Place in the Universe Program
 
# This program will determine the approximate number of atoms that a person is
# person consists of and the percent of the universe that they comprise
 
# Initialization
num_atoms_universe = 10e80
weight_avg_person = 70  # 70 kg (154 lbs)
num_atoms_avg_person = 7e27
 
# Program greeting
print('This program will determine your place in the universe.')
 
# Prompt for user's weight
weight_lbs = int(input('Enter your weight in pounds: '))
 
# Convert weight to kilograms
weight_kg = 2.2 * weight_lbs
 
# Determine number atoms and percentage of universe
num_atoms = (weight_kg / weight_avg_person) * num_atoms_avg_person
percent_of_universe = (num_atoms / num_atoms_universe) * 100
 
# Display results
print('You contain approximately', format(num_atoms, '.2e'), 'atoms')
print('Therefore, you comprise', format(percent_of_universe, '.2e'),
      '% of the universe')

Expressions and Data Types

What is an expression?

Operator precedence and associativity

Python’s rules

operator associativity
** right to left
- (negation) left to right
*, /, //, %left to right
+, - left to right

Examples

>>> 6 - 3 + 2
5
>>> 2 * 3 / 4
1.5
>>> 2 ** 3
8
>>> 2 ** 3 ** 2  # exponentiation is r-to-l
512

What is a data type?

Python’s basic types

>>> type(66)
<class 'int'>
>>> type(3.1)
<class 'float'>
>>> type(True)
<class 'bool'>
>>> type(3.1)
<class 'float'>

Static versus dynamic typing

x = 41 + 1
print(x)
x = 'I ate a donut.'
print(x)
x = False
print(x)

Mixed-type expressions

Type coercion

3 + 1.23.0 + 1.2 → 4.2

Type conversion

>>> str(42)    # convert into to string
'42'
>>> int('42')  # convert string to int
42
>>> int(3.9)   # convert float to int
3
>>> float('99') # convert int to float
99.0
>>> int('99.9') # nope
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '99.9'

Example: Temperature Conversion Program

TempConversion.py

# Temperature Conversion Program (Fahrenheit to Celsius)
 
# This program will convert a temperature entered in Fahrenheit
# to the equivalent degrees in Celsius
 
# program greeting
print('This program will convert degrees Fahrenheit to degrees Celsius')
 
# get temperature in Fahrenheit
fahrenheit = float(input('Enter degrees Fahrenheit: '))
 
# calc degrees Celsius
celsius = (fahrenheit - 32) * 5 / 9
 
# output degrees Celsius
print(fahrenheit, 'degrees Fahrenheit equals',
       format(celsius, '.1f'), 'degrees Celsius')