[PP Problem 2.1] Indicate whether the result is a float or int by including or 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 give?
a. 6
b. 20.0
c. 4.5
d. -4.5
e. 4
f. 1
g. 1.0
h. 1.0
k. -5.0
l. 19
m. 35
[PP Problem 4.5] Given variables x
and y
, which are assigned the values
3 and 12.5, respectively, use the print
function to print the following
messages. When numbers appear in the messages, variables x
and y
should be
used.
a. print("The rabbit is " + str(x) + ".")
b. print("The rabbit is " + str(x) + " years old.")
c. print(str(y) + " is average.")
d. print(str(y) + " * " + str(x))
e. print(str(y) + " * " + str(x) + " is " + str(x*y) + ".")
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 hypotenuse_length
//
floor division in my_sqrt
. This code
effectively performs x ** 0
. We want to use float division, i.e.
1/2
.float
returned by
hypotenuse_length
to string in the print statement. We need to wrap
hypotenuse_length
with str()
.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
y=0).
def x_intercept(slope, intercept):
return -intercept / slope