Practice with Expressions and Variables
You should have already watched several introductory videos before class. If you have just added the class, then go ahead and first watch the videos. (See OWL-Space “Lessons / Before Wed. 1/9 class”.)
During class, use CodeSkulptor to do the following exercises. We encourage you to collaborate with your peers and to ask the course staff any questions. You do not need to turn in any of the following work.
Arithmetic
As pointed out in one of the videos, division is the trickiest of the basic arithmetic operations. For each of the following, first try to predict the result, then try it in CodeSkulptor. Don't just limit yourself to the examples here, try your own, too!
Division with Integers
-
print 4 / 2 print 4 / 3 print 4 / 4 print 4 / 5 print 4 // 2 print 4 // 3 print 4 // 4 print 4 // 5
Division with Floating-point
-
print 4.0 / 2.0 print 4.0 / 3.0 print 4.0 / 4.0 print 4.0 / 5.0 print 4.0 // 2.0 print 4.0 // 3.0 print 4.0 // 4.0 print 4.0 // 5.0
Division mixing integers and floating-point
-
print 4.2 / 5 print 4 / 5.2 print 4.2 // 5 print 4 // 5.2
Division by zero
What do you think will happen with these special cases?
-
print 4.2 / 0 print 4 / 0 print 4.2 // 0 print 4 // 0
Do you understand the results?
Bigger formulas
The videos illustrated using Python to convert degrees Fahrenheit to degrees Celsius. In the following examples you'll write similar code.
Finish the following code. We don't expect that you necessarily know the relevant formulas by heart, so feel free to search online. Test your code on other inputs, as well.
-
# Converts a temperature in degrees Celsius to degrees Fahrenheit. temp_celsius = 100 temp_fahrenheit = ??? print temp_fahrenheit
-
# Computes the area of a triangle. height = 4 based = 5 triangle_area = ??? print triangle_area
-
# Computes the surface area of a rectangular solid, i.e., a box. width = 5 height = 4 depth = 6 box_surface_area = ??? print surface_area
How do you know your formulas are correct? Having known examples is very useful for testing correctness. They also help ensure that we all agree on what the code is supposed to do.
Assignment
In the previous formulas you had some simple uses of assignment, i.e., the equals sign. The next examples are some examples to stretch your mind a little and get you thinking about assignment. Again, for each, first try to predict the result by stepping through the line one at a time. Then test your answer by trying it out.
-
x = 5 y = 7 x = y y = 3 print x, y
-
x = 5 y = 7 x = y y = x print x, y
-
x = 5 y = 7 y = x y = 3 print x, y
-
x = 5 x += 7 print x
-
y = 5 y += y print y
-
x = 3 y = 5 z = 2 x *= y + z print x
Here's one last example for those that have been doing well. It's a tricky one, because it's using a feature not mentioned in the videos. But see if you can guess what it'll do before you run it. After you run it, can you explain what's going on?
-
x = 5 y = 7 x, y = y, x print x, y