在Python中创建用户定义函数

vyu0f0g1  于 2023-05-02  发布在  Python
关注(0)|答案(2)|浏览(110)
miles_per_hour = float(input())
minutes_traveled = float(input())

print(f'Miles: {mph_and_minutes_to_miles(miles_per_hour, 
minutes_traveled):f}')

我需要为这个输入程序创建用户定义函数,但我不知道如何定义mph_and_minutes_to_miles。我无法更改程序的这一部分。
我试过:

def calculate_hours_traveled(minutes_traveled):
hours_traveled = minutes_traveled / 60.0
return hours_traveled

def calculate_miles_traveled(miles_per_hour, hours_traveled):
miles_traveled = hours_traveled \* miles_per_hour
return miles_traveled

mph_and_minutes_to_miles = miles_traveled
return mph_and_minutes_to_miles

但还是不行。我有一些输入和输出示例:
70.0每小时100英里0表示行驶分钟数
输出应为:
116.666667

7cjasjjr

7cjasjjr1#

你很接近了您只需定义mph_and_minutes_to_miles函数,该函数首先调用calculate_hours_traveled将分钟数转换为小时数,然后调用calculate_miles_traveled从速度和小时数中获取行驶的距离。

def calculate_hours_traveled(minutes_traveled):
    return minutes_traveled / 60.0

def calculate_miles_traveled(miles_per_hour, hours_traveled):
    return hours_traveled * miles_per_hour

def mph_and_minutes_to_miles(mph, mins):
    return calculate_miles_traveled(mph, calculate_hours_traveled(mins))
zaq34kh6

zaq34kh62#

我相信你应该试试下面的代码(你需要先定义“mph_and_minutes_to_miles”,然后返回正确的主题):

def calculate_hours_traveled(minutes_traveled):
hours_traveled = minutes_traveled / 60.0
return hours_traveled

def calculate_miles_traveled(miles_per_hour, hours_traveled):
miles_traveled = hours_traveled \* miles_per_hour
return miles_traveled

def mph_n_mins_to_miles(miles_per_hour, mins_traveled):
hours_traveled = calculate_hours_traveled(minutes_traveled)
miles_traveled = calculate_miles_traveled(miles_per_hour, 
hours_traveled)
return mph_n_mins_to_miles

之后,您可以在顶部添加上面提供的代码并调用函数:

miles_per_hour = float(input())
minutes_traveled = float(input())

print(f'Miles: {mph_n_mins_to_miles(miles_per_hour, 
minutes_traveled):f}')

谢谢

相关问题