首页 > 解决方案 > 测试 python 代码时出错:TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“NoneType”

问题描述

Python 新手,我试图回答一个家庭作业问题,其中:医院记录他们正在处理的患者数量,为每位患者提供所需的营养,然后在对总数求和后平均每位患者所需的营养。

现在,当我测试/验证数据输入时,我看到我的代码由于我试图解决问题的笨拙方式而导致错误。测试时,我得到这个:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

我已经尝试过并弄乱返回函数,但如果它不存在,我认为问题可能出在我的read_input()函数上。我一直在玩 PythonTutor,所以我可以想象错误在哪里......我只是不知道如何摆脱这个循环并修复它。

到目前为止我的代码

def validate_positive_patients(n):

    try:
        n = float(n)
        if n <= 0:
            print("Please enter a nonnegative number")
            return n, False

    except ValueError:
        print("Please enter a positive integer")
        return None, False
    return n, True

def read_input(float):
    value, positive = validate_positive_patients(input(float))
    if not positive:
        read_input(float=float)
    else:
        return value

# rest of code seems to work fine

我的代码很笨拙,但我真正想做的是只接受“患者人数”的 int 值、蛋白质、碳水化合物等的浮点数,如果最初出现输入错误,不只是吐出 None价值。

如果只有计算机知道您希望它们做什么而不是我告诉它做什么:P 在此先感谢您的帮助!

标签: pythonpython-3.x

解决方案


默认情况下,Python 函数返回None.

在您的原始代码中read_input,如果输入的值不是正数,那么您永远不会点击return语句,并相应地返回None

我已经清理了你的代码,同时试图保持它的精神:

def get_positive_int(message):
    while True:
        input_value = input(message)
        if input_value.isdigit() and int(input_value) > 0:
            return int(input_value)

        else:
            print('Please enter a positive number.')

def get_positive_float(message):
    while True:
        input_value = input(message)
        try:
            float_value = float(input_value)
            if float_value > 0:
                return float_value

        except ValueError:
            pass

        print('Please enter a positive real number.')

def calculate_average(nutrition, total_quantity, total_patients):
    average = total_quantity / total_patients
    print(f'{nutrition} {average}')

number_of_patients = get_positive_int("Enter number of patients: ")

protein, carbohydrates, fat, kilojoules = 0, 0, 0, 0

for i in range(int(number_of_patients)):
    print(f'Patient {i + 1}')
    protein += get_float("Amount of protein (g) required: ")
    carbohydrates += get_float("Amount of carbohydrates (g) required: ")
    fat += get_float("Amount of fat (g) required: ")
    kilojoules += 4.18*(4*protein + 4*carbohydrates + 9.30*fat)

print("Averages:")
calculate_average(nutrition = "Protein (g): ", total_quantity = protein,
                  total_patients = number_of_patients)
calculate_average(nutrition = "Carbohydrates (g): ", total_quantity = 
                  carbohydrates, total_patients = number_of_patients)
calculate_average(nutrition = "Fat (g): ", total_quantity = fat,
                  total_patients = number_of_patients)
calculate_average(nutrition = "Kilojoules (kJ): ", total_quantity =
                  kilojoules, total_patients = number_of_patients)

特别是,隐藏内置函数(float用作参数名称)是不明智的,而 f-strings 可以使您的代码更易于阅读。


推荐阅读