python - 测试 python 代码 : TypeError: int() argument must be a string, 类似字节的对象或数字时出错,而不是 'NoneType'

标签 python python-3.x

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 预先感谢您的帮助!

最佳答案

默认情况下,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 字符串可以使代码更易于阅读。

关于python - 测试 python 代码 : TypeError: int() argument must be a string, 类似字节的对象或数字时出错,而不是 'NoneType',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55788480/

相关文章:

Python Pandas Dataframe 将 NaN 替换为列表中的值

python - 当我们在Django中使用opencv时如何处理请求

python - 当先前的值很重要时如何使用 `apply()` 或其他矢量化方法

python celery : Retrieve tasks arguments if there's an exception

python - 使用 RSA 在 Python 中逐行加密文件并将其与另一个文件进行比较

python - 尝试复制 TFIDF 示例,乘法返回错误的数字

python-3.x - 在 Airflow 中是否有每日 DAG 依赖于每周(周末)DAG 的方法?

python - 使 __call__ 成为基类中可用于所有派生类的特定接口(interface)

python - 输入数组相等时索引矩阵元素

python - 如何使用正则表达式搜索字母对匹配?