Expressions

CS 65: Introduction to Computer Science I

Expressions

expression: something evaluated by the Python interpreter

In [1]:
num_students = 42
num_adults = 10 
total_field_trip_lunches = num_students + num_adults
print("Total field trip lunches:",total_field_trip_lunches)
Total field trip lunches: 52

num_students + num_adults is evaluated - results in an answer, so it is an expression

expressions include operators, like +, and operands like num_students and num_adults

Arithmetic Operators

Python supports all of the arithmetic operators you know and love:

  • ( ) parentheses
  • ** exponents
  • * multiplication
  • / division
  • + addition
  • - subtraction

PEMDAS order of operations

In [2]:
6 / 2*(1+2)
Out[2]:
9.0
In [3]:
2**4 
Out[3]:
16

Keeping it simple

Just because you can write really complex expressions in Python doesn't mean you should.

In [13]:
vacation_budget = (2.70 * 1224/32) + ((8-1) * 96) + (8 * ((40*4)+100)) + (4 * 190)
print("Vacation budget:",vacation_budget)
Vacation budget: 3615.275
In [14]:
avg_gas_estimate = 2.70
round_trip_miles_to_memphis = 1224
vehicle_mpg = 32
gas_cost = avg_gas_estimate * (round_trip_miles_to_memphis/vehicle_mpg)

vacation_days = 8

hotel_nights = vacation_days-1
hotel_per_night_cost = 96
lodging_cost = hotel_nights * hotel_per_night_cost

food_per_person_per_day = 40
num_people = 4
total_food_per_day = food_per_person_per_day*num_people
souvenirs_and_incidentals_per_day = 100
food_and_incidental_cost = vacation_days*(total_food_per_day+souvenirs_and_incidentals_per_day)

graceland_ticket_cost = 190
graceland_cost = num_people * graceland_ticket_cost

vacation_budget = gas_cost + lodging_cost + food_and_incidental_cost + graceland_cost
print("Vacation budget:",vacation_budget)
Vacation budget: 3615.275