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字符串可以使您的代码更易于阅读。