Skip to main content

Exercises 4.13 Write Code Questions

1.

Fix the errors in the code, and change it to use only one if statement. The code should print “The number is 5” when the number is 5, and should print “The number is NOT 5” when it is not.
Solution.
# Initialize x and set condition for when x = 5
# Use "else" to take care of condition when x is not 5.
x = 5
if x == 5:
    print("The number is 5") # indent the body of if
else:
    print("The number is NOT 5") # indent the body of else

2.

Complete the conditional below so the words “Not three” are printed if x does not equal 3 and “It is three” is printed otherwise.

3.

Complete the pay computation as follows: When the employee works less than or equal to 40 hours a week, pay them $10 per hour. Otherwise, pay them $10 and hour for the first 40 hours and 1.5 times the hourly rate for hours worked above 40 hours. Then set grossPay equal to the amount an employee would be paid for working 45 hours.
Solution.
# Initializing variables
hours = 45
rate = 10
# overtimeRate is 1.5 the rate amount
overtimeRate = rate * 1.5
grossPay = 0
# Begin conditional to see if hours are within regular pay
if hours <= 40:  # for 40 hours or fewer...
    grossPay = hours * rate
else:
    overTime = hours - 40 # calculate hours over 40
    # Pay will equal the regular rate for 40 hours,
    # plus the overtime rate for the extra hours
    grossPay = (rate * 40) + (overTime * overtimeRate)
# Print the final pay
print(grossPay)

4.

Write the code to calculate and print the cost of a 14 mile cab ride. If the distance traveled is less than or equal to 5 miles the cost is $2.00 a mile. If the distance is greater than 5 but less than or equal to 12 miles, the cost is $1.50, and if the distance traveled is more than 12 miles the cost is $1.25 a mile. Assign the final cost to the variable total. (Your code should work for any mileage, not just for 14 miles.)
Solution.
distance = 14 # must initialize variable

if distance <= 5:
    rate = 2.00
elif distance <= 12:
    rate = 1.50
else:
    rate = 1.25

total = distance * rate

print("Total cost of trip:", total)