3.7. Walking through Assignment more Generally¶
Let’s explore assignment in general. Try tracing this example.
- 1
- The variable a is not used in defining the variable b.
- 12.3
- The variable d is set to a copy of the value in variable b. The variable b still holds the value 12.3 as well.
- "b"
- The variable d gets assigned the same value as the one stored in b.
- "d"
- The variable d gets its value from the variable b.
What is the value of variable d
when this program is finished running?
The sequence of statements in a program is very important. Assignment doesn’t create some kind of relationship between the names, like in mathematics. The variable a
might equal 12
at one point, and 15
at another. An assignment statement is an action that occurs once, and then is over with.
- var1 is 45, var2 is 45
- The variable var1 was set to 45, but that gets changed in line 2, before var2 gets set to any value at all.
- var1 is 45, var2 is var1
- Both variables contain numeric values, because those are the only values in this program.
- var1 is 17.3, var2 is 45
- The variable var2 never gets set to 45 in this program.
- var1 is 17.3, var2 is 17.3
- The variable var1 is first set to 45 and then changed to 17.3, and then, var2 gets the value from var1.
What are the values in var1
and var2
after this program runs?
We can see values (including the values for named variables) by printing them. It’s a useful way to see what’s going on inside a program. Try running this example where we’re having the computer calculate the number of days in three weeks:
- 7, 7*3, daysInWeek*3
- The values will actually be computed and numbers will be printed.
- daysInWeek, numDays, numDays2
- The variable names will not be printed.
- 7, 21, 21
- The first print will print the value of daysInWeek (7), the second the value of numDays (21), and the third the value of numDays2 (21).
- 7, 21, 3
- The value for daysInWeek will be computed and assigned.
What three values are printed when this program runs?
The following program should figure out the cost per person for a dinner including the tip. But the blocks have been mixed up. Drag the blocks from the left and put them in the correct order on the right. Click the <i>Check Me</i> button to check your solution.</p>
10 people went to a restaurant for dinner. Each guest ate 1 appetizer and 1 entree. The whole party shared 1 dessert. Write the code to calculate and print the total bill if each appetizer costs $2.00, each entree costs $9.89, and dessert costs $7.99. It should print 126.89.
Create variables to hold each value. Calculate bill
as (appetizer + entree) * numPeople + dessert
. Be sure to print the result.