简体   繁体   English

错误测试python代码:TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是“ NoneType”

[英]Error testing python code: TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

New to Python and am trying to answer a homework problem where: a hospital records how many patients they are dealing with, the required nutrition to be provided to each patient, and then averaging required nutrition per patient after summing the totals. Python的新手,正在尝试回答以下作业问题:医院记录正在处理的患者人数,要向每位患者提供的所需营养,然后将总数求和后平均每位患者所需的营养。

Now when I'm testing/validating data entry, I see my code is causing errors because of the clumsy way I've tried to solve the problem. 现在,当我测试/验证数据输入时,由于尝试解决问题的笨拙方式,我看到我的代码正在引起错误。 When testing, I get this: 测试时,我得到以下信息:

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

I've tried going through and messing with the return functions, but if it's not there, I think the issue might be with my read_input() functions. 我尝试过遍历返回函数,但是如果不存在,我认为问题可能出在我的read_input()函数上。 I've been messing around with PythonTutor, so I can visualize where the error is...I just have no idea how to get out of this loop and fix it. 我一直在搞弄PythonTutor,所以我可以看到错误在哪里...我只是不知道如何摆脱这个循环并进行修复。

my code so far 到目前为止我的代码

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

My code is clumsy, but what I'd really like it to do is only accept int values for 'number of patients', floats for protein, carbs etc., and if there is an entry error initially to not just spit out a None value. 我的代码很笨拙,但是我真正想做的只是接受“患者数量”的int值,蛋白质,碳水化合物等的浮点数,并且如果最初出现输入错误,不仅要吐出None值。

If only computers knew what you wanted them to do instead of what I'm telling it to do :P Thanks in advance for any help! 如果只有计算机知道您想要他们做什么,而不是我要它做什么:P在此先感谢您的帮助!

By default, Python functions return None . 默认情况下,Python函数返回None

In your original code, in read_input , if the value entered is not positive, then you never hit a return statement, and accordingly return None . 在原始代码的read_input ,如果输入的值不是正数,则您永远不会命中return语句,因此返回None

I've cleaned up your code a little, while attempting to preserve its spirit: 在尝试保留其精神的同时,我对您的代码进行了一些整理:

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)

In particular, it is unwise to shadow builtins (using float as a parameter name), and f-strings can make your code easier to read. 特别是,阴影内置函数(使用float作为参数名称)是不明智的,f字符串可以使您的代码更易于阅读。

You'd be getting None because you're ignoring a value when you call read_input again in the if statement. 您将获得None,因为在if语句中再次调用read_input时将忽略一个值。

The alternative would be to just loop, not call the same function 另一种选择是只是循环,而不是调用相同的函数

def read_input(prompt):
    positive = False
    while not positive:
        value, positive = validate_positive_patients(input(prompt))
    return value 

And I suggest you use while loops so that it continously checks the results 我建议您使用while循环,以便它连续检查结果

Note that you're also doing return None, False in the first function, so you still should check that value is not None before actually returning a numeric value 请注意,您也正在第一个函数中return None, False ,因此您仍应在实际返回数字值之前检查该value is not None

Also Check if input is positive integer 同时检查输入是否为正整数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是 python3 中的“NoneType”错误 - TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' error in python3 TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“NoneType”(HTML 将输入发送到 Python) - TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' (HTML send input to Python) TypeError: int() 参数必须是一个字符串,一个类似字节的 object 或一个数字,而不是使用 Python 3.7 时的“NoneType” - TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' while using Python 3.7 Python:TypeError:int() 参数必须是字符串、类似字节的对象或数字,而不是“NoneType” - Python: TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是&#39;NoneType&#39;错误 - TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' error int() 参数必须是字符串、类似字节的对象或数字,而不是“NoneType” - int() argument must be a string, a bytes-like object or a number, not 'NoneType' TypeError: int() 参数必须是一个字符串,一个类似字节的 object 或一个数字,而不是“NoneType”。 但我写了 int() - TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'. But I wrote the int() TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是“ NoneType” - TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' 使用 openpyxl 时,会发生此执行“TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'” - While using openpyxl this execption occurs “ TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' ” TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' Deep Learning - TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' Deep Learning
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM