вызов функции из функции python - PullRequest
0 голосов
/ 13 июня 2019

Я делаю простой расчет для сжигания калорий. Я получаю данные и переменные от пользователей, и у меня есть две формулы.

Функция BMR работает. Тройник продолжает выдавать ошибки (в основном, он не может вызвать float), а когда нет, я получаю что-то вроде <function a0…>.

def bmr(gender, age, height, weight):
    if gender == "f":
        bmr = 655 + weight*9.6 + height*1.6 + age*4.7
    else:
        bmr = 66 + weight*13.8 + height*5 + age*6.8
    return bmr

def tee (bmr, amount_of_exersice):
    #x = 0
    y = bmr(gender, age, height, weight)
    if amount_of_exersice == 0:
        x = 1.2
    elif 1<= amount_of_exersice <= 2:
        x = 1.375
    elif 3 <= amount_of_exersice <= 5:
        x = 1.55
    else:
        x = 1.725
    z = x * y
    return z

Ответы [ 3 ]

1 голос
/ 13 июня 2019

Пара проблем, вы переопределяете "bmr" и не передаете правильные аргументы во второй вызов bmr. Попробуйте в качестве примера:

def tee (gender, age, height, weight, amount_of_exersice):
    y = bmr(gender, age, height, weight)
    if amount_of_exersice == 0:
        x = 1.2
    elif 1<= amount_of_exersice <= 2:
        x = 1.375
    elif 3 <= amount_of_exersice <= 5:
        x = 1.55
    else:
        x = 1.725
    z = x * y
    return z

или если вы хотите определить bmr раньше:

def tee (y, amount_of_exersice):
    if amount_of_exersice == 0:
        x = 1.2
    elif 1<= amount_of_exersice <= 2:
        x = 1.375
    elif 3 <= amount_of_exersice <= 5:
        x = 1.55
    else:
        x = 1.725
    z = x * y
    return z

y_bmr = bmr(gender, age, height, weight)
tee(y_bmr, amount_of_exersice)
0 голосов
/ 14 июня 2019
def validate_user_input(prompt, type_=None, min_=None, max_=None, range_=None):
    if min_ is not None and max_ is not None and max_ < min_:
        raise ValueError("min_ must be less than or equal to max_.")
    while True:
        ui = input(prompt)
        if type_ is not None:
            try:
                ui = type_(ui)
            except ValueError:
                print("Input type must be {0}.".format(type_.__name__))
                continue
        if max_ is not None and ui > max_:
            print("Input must be less than or equal to {0}.".format(max_))
        elif min_ is not None and ui < min_:
            print("Input must be greater than or equal to {0}.".format(min_))
        elif range_ is not None and ui not in range_:
            if isinstance(range_, range):
                template = "Input must be between {0.start} and {0.stop}."
                print(template.format(range_))
            else:
                template = "Input must be {0}."
                if len(range_) == 1:
                    print(template.format(*range_))
                else:
                    print(template.format(" or ".join((", ".join(map(str,
                                                                     range_[:-1])),
                                                       str(range_[-1])))))
        else:
            return ui


def bmr(gender, age, height, weight):
    if gender == "f":
        bmr = 655 + weight*9.6 + height*1.6 + age*4.7
    else:
        bmr = 66 + weight*13.8 + height*5 + age*6.8
    return bmr

def tee (gender, age, height, weight, amount_of_exersice):
    y = bmr(gender, age, height, weight)
    if amount_of_exersice == 0:
        x = 1.2
    elif 1<= amount_of_exersice <= 2:
        x = 1.375
    elif 3 <= amount_of_exersice <= 5:
        x = 1.55
    else:
        x = 1.725
    z = x * y
    return z

## user info ##
gender = validate_user_input("Please enter your gender (F -Female / M- Male): ", str.lower, range_=("f","m"))
age = validate_user_input("Please enter your age: ", int, 1, 110)
height = validate_user_input("Please enter your height in cm: ", int, 130, 230)
weight = validate_user_input("Please enter your weight in kg: ", float, 20, 400)
amount_of_exersice = validate_user_input("Please enter the amount of days you engage in physical activity per week: ", int, 0, 7)

calc_bmr = bmr(gender, age, height, weight)
calc_tee = tee(gender, age, height, weight, amount_of_exersice)
print("Your Basal Metabolic Rate is ", calc_bmr)
print("Your daily calories burn is ", calc_tee)
0 голосов
/ 13 июня 2019

Когда вы делаете

def tee(bmr, amount_of_exersize):

Вы переопределяете имя bmr, чтобы указать на любую переменную, которую вы передаете - тогда как, если бы вы этого не сделали, она бы ссылалась нафункция выше.Эта замена применяется, пока вы находитесь внутри метода, и единственное реальное решение - переименовать параметр, чтобы он не конфликтовал:

def tee(something_else, amount_of_exersize):
    y = bmr(gender, age, height, weight)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...