gpt4 book ai didi

python - python练习难点

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:35 25 4
gpt4 key购买 nike

所以,我正在做 Python 实用编程书中的练习,但我卡在第 2 章的第 9 个练习上,它与第 7 个练习相关:

7.: In the United States, a car’s fuel efficiency is measured in miles per gallon. In the metric system, it is usually measured in liters per 100 kilometers. Write a function called convert_mileage that converts from miles per gallon to liters per 100 kilometers.

我是这样写程序的:

def convert_mileage(miles_per_gallon):
liters_per_gallon = 3.785411784
kilometers_per_mile = 1.609344
liters_per_100 = (100*liters_per_gallon)/(kilometers_per_mile*miles_per_gallon)
print miles_per_gallon,'miles per gallon are',liters_per_100,'liters per 100 kilometers.'

convert_mileage(40)
convert_mileage(20)

现在,第 9 个练习如下:

9.: Define a function called liters_needed that takes a value representing a distance in kilometers and a value representing gas mileage for a vehicle and returns the amount of gas needed in liters to travel that distance. Your definition should call the function convert_mileage that you defined as part of a previous exercise.

我不知道如何将第一个功能链接到第二个功能......而且与旅行的公升相比,我很难理解整个里程数。如果有人可以帮助我,那就太好了!谢谢:)

最佳答案

本练习要求您重用您的convert_mileage 函数。因此,您必须返回,而不是仅仅打印计算出的值。将您的功能更改为如下所示:

LITERS_PER_GALLON = 3.785411784
KILOMETERS_PER_MILES = 1.609344

def convert_mileage(miles_per_gallon):
"""convert miles-per-gallon to liters per 100 kilometers"""
return (100*LITERS_PER_GALLON)/(KILOMETERS_PER_MILES*miles_per_gallon)

现在您可以调用此函数并在另一个计算中重用其结果:

def liters_needed(distance_km, miles_per_gallon):
"""determine liters needed for distance with given miles per gallon"""
liters_per_100km = convert_mileage(miles_per_gallon)
return liters_per_100km * distance_km / 100

现在您必须在调用函数时打印结果:

print "Liters needed for 200km with 15mpg:", liters_needed(200, 15)

关于python - python练习难点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com