Skip to main content

Section 14.6 Driving from Chicago to Dallas

As an example, imagine that you were planning to drive from Chicago to Dallas. If you know how many miles per gallon your car gets, and how many miles it is, you can estimate the number of gallons it will take.
Use the CodeLens below to trace through what it would look like for a computer to execute this program:
  • Press Next to run the next instruction.
  • Press Prev to go back one instruction.
Now, if we know the average cost of a gallon of gas, we can figure out the cost of the trip from Chicago to Dallas in your car.
The Codelens allows us to see the value of each variable in a program as it runs. But normally if we run a program we do not get to watch what is happening on each line. However, we can check what values are in variables by printing them out.
The function print can take an input (a variable name inside of parentheses) whose value will be displayed. The print function can also print a string (like "Cost to get from Chicago to Dallas") which is a sequence of characters inside a pair of double quotes as seen in line 8. It will print the exact contents of the string. This is useful for explaining the values that you are printing.
You can also print multiple things on one line by putting them all inside the parentheses after print, separated by commas. You can see this on line 12 in the program below.

Warning 14.6.1.

Notice that in the code above we are using camel case variable names like costPerGallon and costTrip. When using this style, you have to be careful about capitalization - costperGallon is a different name than costPerGallon. Try changing just the first copy of costPerGallon below to costpergallon and then run the code to see what happens.
Try editing the program above and running it to answer the questions below:

Checkpoint 14.6.2.

    If the cost per gallon drops to $3.45, can we drive from Chicago to Dallas for less than $90 in gas?
  • Yes
  • Yes, the cost would be $89.86 (which you knew by editing the program above and running it)
  • No
  • Try it -- it’s just under $90.
  • We should fly instead.
  • You might be right, but figure out the cost by editing the above program

Checkpoint 14.6.3.

    What would be printed by print("costPerGallon") if this line was added to the end of the program?
  • 3.45
  • This would be true if it was printing the value of the original variable.
  • 3.65
  • This would be true if it was printing the value of the variable after you changed it to figure out the previous question.
  • costPerGallon
  • Since costPerGallon is in double quotes it is a string, and it will print out those exact characters.
You have attempted of activities on this page.