Python - 遍历用户输入的数字,计算并输出输入的值
Python - Loop through User input number, calculate and output the entered values
我已经学习 Python 将近 6 周了,下面是我的第一个程序。
我想得到的是用户输入的患者编号、碳水化合物、蛋白质和脂肪需求。
使用下面的代码,我得到了我想要的输出。但是,我觉得它根本不是DRY。我在重复很多事情。
我想修改这段代码,使用户能够输入任意数量的患者。目前,我指定 patient_no1 和 patient_no2。我将修改 for 循环并用 for 循环编码这个问题。如果您能给我一些关于如何重构当前代码的指导,将不胜感激。
谢谢!
def diet_log():
################################ Patient 1 ##########################################
# Request User input for patient numbers, Handle non-positive integers and other invalid user input error for patient numbers
while True:
try:
patient_no1 = int(input("Enter a patient number to determine the dietary requirements : "))
assert(patient_no1 > 0), "The patient number entered must be a positive integer."
break
except:
print("The patient number you enter must be a positive integer. Please try again.")
# Request User input for protein, Handle non-positive integers and other invalid user input error
while True:
try:
diet_protein1 = float(input("Amount of protein required: "))
assert(diet_protein1 > 0)
break
except:
print("The protein amount must be a non-negative integer.")
# Request User input for carbohydrates, Handle non-positive integers and other invalid user input error
while True:
try:
diet_carb1 = float(input("Amount of carbohydrates required: "))
assert(diet_carb1 > 0)
break
except:
print("The amount of carbohydrates required must be a non-negative integer.")
# Request User input for fat, Handle non-positive integers and other invalid user input error
while True:
try:
diet_fat1 = float(input("Amount of fat required: "))
assert(diet_fat1 > 0)
break
except:
print("The fat amount must be a non-negative integer.")
print("-----------------------------------------------------")
########################## end of Patient 1 ##############################################################
################################ Patient 2 ##########################################
# Request User input for patient numbers, Handle non-positive integers and other invalid user input error for patient numbers
while True:
try:
patient_no2 = int(input("Enter a patient number to determine the dietary requirements : "))
assert(patient_no2 > 0), "The patient number entered must be a positive integer."
break
except:
print("The patient number you enter must be a positive integer. Please try again.")
# Request User input for protein, Handle non-positive integers and other invalid user input error
while True:
try:
diet_protein2 = float(input("Amount of protein required: "))
assert(diet_protein2 > 0)
break
except:
print("The protein amount must be a non-negative integer.")
# Request User input for carbohydrates, Handle non-positive integers and other invalid user input error
while True:
try:
diet_carb2 = float(input("Amount of carbohydrates required: "))
assert(diet_carb2 > 0)
break
except:
print("The amount of carbohydrates required must be a non-negative integer.")
# Request User input for fat, Handle non-positive integers and other invalid user input error
while True:
try:
diet_fat2 = float(input("Amount of fat required: "))
assert(diet_fat2 > 0)
break
except:
print("The fat amount must be a non-negative integer.")
########################## end of Patient 2 ##############################################################
# Create list of protein, carb and fat for patients
total_patient_num = [patient_no1, patient_no2]
diet_protein = [diet_protein1, diet_protein2]
diet_carb = [diet_carb1, diet_carb2]
diet_fat = [diet_fat1, diet_fat2]
# Calculate average for the lists created above by using statistics
import statistics
average_protein = statistics.mean(diet_protein)
average_carb = statistics.mean(diet_carb)
average_fat = statistics.mean(diet_fat)
# Calculate average kilojoules
kilojoules = 4.18 * ( (4 * average_protein) + (4* average_carb) + (9.30 * average_fat))
# Display the output to the users
print("===================================================")
print("Total number of patients entered: ", len(total_patient_num))
print("Patient %d" % patient_no1)
print("\n"," Amount of protein (g) required: ", diet_protein1, "\n"," Amount of carbohydrates (g) required: ",diet_carb1 ,"\n"," Amount of fat required: ", diet_fat1)
print("Patient %d" % patient_no2)
print("\n"," Amount of protein (g) required: ", diet_protein2, "\n"," Amount of carbohydrates (g) required: ",diet_carb2 ,"\n"," Amount of fat required: ", diet_fat2)
print("-----------------------------------------------------")
print("Averages: ", "\n",
"Protein (g): ", format(average_protein, ",.2f"), "\n",
"Carbohydrates (g): ", format(average_carb, ",.2f"), "\n",
"Fat (g): ", format(average_fat, ".2f"), "\n",
"Kilojoules (kJ): ", format(kilojoules, ",.2f"), "\n")
if __name__ == "__main__": diet_log()
# print(diet_log("patient no"))
首先寻找看起来非常相似的代码。例如,您围绕输入语句执行的 while 循环看起来很相似。尝试将它们转换为带有使它们不同的部分的参数的函数。
您可以先以通用方式定义您的列表:
total_patient_num = []
diet_protein = []
diet_carb = []
diet_fat = []
目前,如果您要添加 n 个用户,则必须重复相同的代码 n 次。
当您看到这样的模式时,它会提示您应该对代码进行抽象。
要解决此问题,您只需将代码放入函数中即可:
def get_user_input():
while True:
try:
patient_no_value = int(input("Enter a patient number to determine the dietary requirements : "))
assert(patient_no_value > 0), "The patient number entered must be a positive integer."
total_patient_num.append(patient_no_value)
break
except:
print("The patient number you enter must be a positive integer. Please try again.")
# Request User input for protein, Handle non-positive integers and other invalid user input error
while True:
try:
diet_protein_value = float(input("Amount of protein required: "))
assert(diet_protein_value > 0)
diet_protein.append(diet_protein_value)
break
except:
print("The protein amount must be a non-negative integer.")
# Request User input for carbohydrates, Handle non-positive integers and other invalid user input error
while True:
try:
diet_carb_value = float(input("Amount of carbohydrates required: "))
assert(diet_carb_value > 0)
diet_carb.apend(diet_carb_value )
break
except:
print("The amount of carbohydrates required must be a non-negative integer.")
# Request User input for fat, Handle non-positive integers and other invalid user input error
while True:
try:
diet_fat_value = float(input("Amount of fat required: "))
assert(diet_fat_value > 0)
diet_fat.append(diet_fat_value)
break
except:
print("The fat amount must be a non-negative integer.")
print("-----------------------------------------------------")
每次调用该方法时,它都会在每个列表中创建一个新条目。
您也可以考虑使用 class 来代表您的用户。
我已经学习 Python 将近 6 周了,下面是我的第一个程序。
我想得到的是用户输入的患者编号、碳水化合物、蛋白质和脂肪需求。
使用下面的代码,我得到了我想要的输出。但是,我觉得它根本不是DRY。我在重复很多事情。
我想修改这段代码,使用户能够输入任意数量的患者。目前,我指定 patient_no1 和 patient_no2。我将修改 for 循环并用 for 循环编码这个问题。如果您能给我一些关于如何重构当前代码的指导,将不胜感激。 谢谢!
def diet_log():
################################ Patient 1 ##########################################
# Request User input for patient numbers, Handle non-positive integers and other invalid user input error for patient numbers
while True:
try:
patient_no1 = int(input("Enter a patient number to determine the dietary requirements : "))
assert(patient_no1 > 0), "The patient number entered must be a positive integer."
break
except:
print("The patient number you enter must be a positive integer. Please try again.")
# Request User input for protein, Handle non-positive integers and other invalid user input error
while True:
try:
diet_protein1 = float(input("Amount of protein required: "))
assert(diet_protein1 > 0)
break
except:
print("The protein amount must be a non-negative integer.")
# Request User input for carbohydrates, Handle non-positive integers and other invalid user input error
while True:
try:
diet_carb1 = float(input("Amount of carbohydrates required: "))
assert(diet_carb1 > 0)
break
except:
print("The amount of carbohydrates required must be a non-negative integer.")
# Request User input for fat, Handle non-positive integers and other invalid user input error
while True:
try:
diet_fat1 = float(input("Amount of fat required: "))
assert(diet_fat1 > 0)
break
except:
print("The fat amount must be a non-negative integer.")
print("-----------------------------------------------------")
########################## end of Patient 1 ##############################################################
################################ Patient 2 ##########################################
# Request User input for patient numbers, Handle non-positive integers and other invalid user input error for patient numbers
while True:
try:
patient_no2 = int(input("Enter a patient number to determine the dietary requirements : "))
assert(patient_no2 > 0), "The patient number entered must be a positive integer."
break
except:
print("The patient number you enter must be a positive integer. Please try again.")
# Request User input for protein, Handle non-positive integers and other invalid user input error
while True:
try:
diet_protein2 = float(input("Amount of protein required: "))
assert(diet_protein2 > 0)
break
except:
print("The protein amount must be a non-negative integer.")
# Request User input for carbohydrates, Handle non-positive integers and other invalid user input error
while True:
try:
diet_carb2 = float(input("Amount of carbohydrates required: "))
assert(diet_carb2 > 0)
break
except:
print("The amount of carbohydrates required must be a non-negative integer.")
# Request User input for fat, Handle non-positive integers and other invalid user input error
while True:
try:
diet_fat2 = float(input("Amount of fat required: "))
assert(diet_fat2 > 0)
break
except:
print("The fat amount must be a non-negative integer.")
########################## end of Patient 2 ##############################################################
# Create list of protein, carb and fat for patients
total_patient_num = [patient_no1, patient_no2]
diet_protein = [diet_protein1, diet_protein2]
diet_carb = [diet_carb1, diet_carb2]
diet_fat = [diet_fat1, diet_fat2]
# Calculate average for the lists created above by using statistics
import statistics
average_protein = statistics.mean(diet_protein)
average_carb = statistics.mean(diet_carb)
average_fat = statistics.mean(diet_fat)
# Calculate average kilojoules
kilojoules = 4.18 * ( (4 * average_protein) + (4* average_carb) + (9.30 * average_fat))
# Display the output to the users
print("===================================================")
print("Total number of patients entered: ", len(total_patient_num))
print("Patient %d" % patient_no1)
print("\n"," Amount of protein (g) required: ", diet_protein1, "\n"," Amount of carbohydrates (g) required: ",diet_carb1 ,"\n"," Amount of fat required: ", diet_fat1)
print("Patient %d" % patient_no2)
print("\n"," Amount of protein (g) required: ", diet_protein2, "\n"," Amount of carbohydrates (g) required: ",diet_carb2 ,"\n"," Amount of fat required: ", diet_fat2)
print("-----------------------------------------------------")
print("Averages: ", "\n",
"Protein (g): ", format(average_protein, ",.2f"), "\n",
"Carbohydrates (g): ", format(average_carb, ",.2f"), "\n",
"Fat (g): ", format(average_fat, ".2f"), "\n",
"Kilojoules (kJ): ", format(kilojoules, ",.2f"), "\n")
if __name__ == "__main__": diet_log()
# print(diet_log("patient no"))
首先寻找看起来非常相似的代码。例如,您围绕输入语句执行的 while 循环看起来很相似。尝试将它们转换为带有使它们不同的部分的参数的函数。
您可以先以通用方式定义您的列表:
total_patient_num = []
diet_protein = []
diet_carb = []
diet_fat = []
目前,如果您要添加 n 个用户,则必须重复相同的代码 n 次。 当您看到这样的模式时,它会提示您应该对代码进行抽象。 要解决此问题,您只需将代码放入函数中即可:
def get_user_input():
while True:
try:
patient_no_value = int(input("Enter a patient number to determine the dietary requirements : "))
assert(patient_no_value > 0), "The patient number entered must be a positive integer."
total_patient_num.append(patient_no_value)
break
except:
print("The patient number you enter must be a positive integer. Please try again.")
# Request User input for protein, Handle non-positive integers and other invalid user input error
while True:
try:
diet_protein_value = float(input("Amount of protein required: "))
assert(diet_protein_value > 0)
diet_protein.append(diet_protein_value)
break
except:
print("The protein amount must be a non-negative integer.")
# Request User input for carbohydrates, Handle non-positive integers and other invalid user input error
while True:
try:
diet_carb_value = float(input("Amount of carbohydrates required: "))
assert(diet_carb_value > 0)
diet_carb.apend(diet_carb_value )
break
except:
print("The amount of carbohydrates required must be a non-negative integer.")
# Request User input for fat, Handle non-positive integers and other invalid user input error
while True:
try:
diet_fat_value = float(input("Amount of fat required: "))
assert(diet_fat_value > 0)
diet_fat.append(diet_fat_value)
break
except:
print("The fat amount must be a non-negative integer.")
print("-----------------------------------------------------")
每次调用该方法时,它都会在每个列表中创建一个新条目。
您也可以考虑使用 class 来代表您的用户。