[PP Problem 2.1] Indicate whether the result is an int or float by (not) including a decimal point, e.g. 5 for an int, 5.0 for a float.
For each of the following expressions, what value will the expression evaluate to? The new operator we didn’t see in class is
%, called modulus, which evaluates to the remainder of its left operand divided by its right operand.
[PP Problem 4.5] Given variables
y, which are assigned the values
3 and 12.5, respectively, use the
y should be
print("The rabbit is " + str(x) + ".")
print("The rabbit is " + str(x) + " years old.")
print(str(y) + " is average.")
print(str(y) + " * " + str(x))
print(str(y) + " * " + str(x) + " is " + str(x*y) + ".")
If we execute the following code, what will the final value be for the variable
# indicates a comment, everything on the line including and after the
# is ignored by Python (is not executed).
The final value for
z is 49. While the expression
z+a are evaluated (and may print to the screen when executing in the shell), those expressions don’t change the values of
z respectively (because there is no assignment operator). Because it is after the
#, the statement
z=2 is not executed at all. The only relevant statements are:
i = 7 a = i z = i * a
The program below is supposed to calculate the length of the hypotenuse of a right triangle with sides 3 and 4 and print out the answer. However, the program has three errors in it: one syntax error, one logic error and one runtime error relating to type. What are the three errors? Try to figure it out without running the program. Think Python describes these three different types of errors (note they call “logic errors” “semantic errors”)
# Take the sqrt of a number def my_sqrt(x): return x ** (1//2) # Calculate the length of the hypotenuse of a right triangle def hypotenuse_length(a, b) sum = a**2 + b**2 return my_sqrt(sum) print("If a is 3 and b is 4 then hypotenuse is " + hypotenuse_length(3,4))
:after definition of
//floor division in
my_sqrt. This code effectively performs
x ** 0. We want to use float division, i.e.
hypotenuse_lengthto string in the print statement. We need to wrap
Write a function named
x_intercept that has two parameters, the slope and
intercept of a line, and returns the x intercept (i.e. the value of x where
def x_intercept(slope, intercept): return -intercept / slope