2.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:
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.
Notice that in the code below that we are using camel case variable names like
costTrip. When using this style, you have to be careful about
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.
What we’re doing above is tracing a program. Normally, we run a program – tell the computer to execute each step of the program as fast as possible. When we do that, we don’t see individual variable values, as we can above. However, we can check values (including the values for variables) by printing them.
"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
Try editing the program above and running it to answer this question: