Python beginner - Truncate function help

weight = 4.8
cost_ground_premium = 125.00
import math
def truncate(number, decimals=0):
#Ground shipping table

if weight <= 2:
cost_ground = weight * 1.50 + 20
elif weight <= 6:
cost_ground = weight * 3.00 + 20
elif weight <= 10:
cost_ground = weight * 4.00 + 20
else:
weight > 10
cost_ground = weight * 4.75 + 20
#Drone shipping
if weight <=2:
cost_drone = weight * 4.50
elif weight <= 6:
cost_drone = weight * 9.00
elif weight <= 10:
cost_drone = weight * 12.00
else:
weight > 10
cost_drone = weight * 14.25
print(“Ground shipping $” , cost_ground)
print(“Ground Shipping Premium $”, cost_ground_premium)

cost_drone = truncate(cost_drone, 3)
print(“Drone Shipping $”, cost_drone)

Hi ,

my code is returning none when I am trying to truncate the cost_drone value.

can anyone help

Hi,

Your truncate function does not have a return value (hence why it returns None).
Elementary functions fall under three categories: return an object, change the value of an object, or display a value.

But… does it need a return value? If you can ascertain what your function is really trying to do it’ll help you fix the problem. (And why it may be invoke improperly, as is).

1 Like

I am still struggling to find a solution here.

All i am trying to do is return the value of cost_drone to 2 decimal places so i know I need to use the Truncate method.

One solution is ```
return math.trunc(number * factor) / factor

however I do not want to do this only to one variable as I want to do it. to the other variable cost_ground as well

weight = 10
cost_ground_premium = 125.00
import math
def truncate(number, decimals=0):
#Ground shipping table

if weight <= 2:
cost_ground = weight * 1.50 + 20
elif weight <= 6:
cost_ground = weight * 3.00 + 20
elif weight <= 10:
cost_ground = weight * 4.00 + 20
else:
weight > 10
cost_ground = weight * 4.75 + 20
#Drone shipping
if weight <=2:
cost_drone = weight * 4.50
elif weight <= 6:
cost_drone = weight * 9.00
elif weight <= 10:
cost_drone = weight * 12.00
else:
weight > 10
cost_drone = weight * 14.25

cost_ground = f"{cost_ground:.3f}"
formatted_ground = cost_ground

print(“Ground shipping $” , cost_ground)
print(“Ground Shipping Premium $”, cost_ground_premium)

cost_drone = f"{cost_drone:.2f}"
formatted_drone = cost_drone

print(“Drone Shipping $:”, formatted_drone)

off topic here:

Python’s round function:
round(3.14159, 2) would round 3.14159 to 2 decimal places.

If you want a function to return anything you have to include the return keyword at the point when the value is ready to be returned in the function (this will exit from the function, or rather “return” back to the code). You can also return a data structure that houses more than one value or order (such as an array, a hash-map, etc.).

Example:

def return_five(): #returns 5
   return 5

my_num = return_five()
print(my_num) #prints 5