Skip to main content
 首页 » 编程设计

python之Python 中的磅和盎司

2024年10月01日7mate10pro

我刚开始学习编码,但在尝试将磅换算为盎司时遇到了问题。我们假设允许用户输入他们的数据,例如 6 磅 2 盎司。我现在被困住了,我什至不确定我是否正在做这件事。任何帮助,将不胜感激。

您的程序将接受一组喂食一种食物的兔子的重量(以磅和盎司为单位)作为输入。让用户提供食物的名称。接受输入,直到用户键入零权重。将重量转换为盎司,让生活更轻松。计算每组兔子的算术平均值(平均值)。确定哪一组兔子最重,并报告它们的平均体重。

这是我在使用磅和盎司之前的原始代码,使用像 13 这样的简单数字时效果很好。

f1 = input("Name of Food:") 
 
print (f1) 
 
counter = 0 
sum = 0 
 
question = input('''Enter a weight? Type "Yes" or "No" \n\n''') 
 
while question == "Yes" : 
    ent_num = int(input("Weight of Rabbit:")) 
    sum = sum + ent_num 
    counter = counter + 1 
    question = input('''Enter another weight? Type "Yes" or "No". \n ''') 
 
print ("Average weight " + str(sum/counter)) 

在我尝试在输入中实现磅和盎司后,我当前的代码如下所示。

f1 = input("Name of Food: ") 
print (f1) 
 
counter = 0 
sum = 0 
 
print ("Please enter inforamtion in pounds and ounces. End") 
question = input('''Enter a weight? Type "Yes" or "No" \n\n''') 
 
while question == "Yes" : 
    ent_num = int(input("Weight of Rabbit:")) 
    sum = sum + ent_num 
    counter = counter + 1 
if pounds * ounces == 0: 
    allOunces = pounds * 16 + ounces 
    sum = sum + allOunces 
 
print ("Average weight " + str(sum/counter)) 

请您参考如下方法:

编程的很大一部分是学习如何将大问题干净利落地分解成小块。

让我们从获取单个权重开始:

POUND_WORDS = {"pound", "pounds", "lb", "lbs"} 
OUNCE_WORDS = {"ounce", "ounces", "oz", "ozs"} 
OUNCES_PER_POUND = 16 
 
def is_float(s): 
    """ 
    Return True if the string can be parsed as a floating value, else False 
    """ 
    try: 
        float(s) 
        return True 
    except ValueError: 
        return False 
 
def get_weight(prompt): 
    """ 
    Prompt for a weight in pounds and ounces 
    Return the weight in ounces 
    """ 
    # We will recognize the following formats: 
    # 12 lb       # assume 0 ounces 
    # 42 oz       # assume 0 pounds 
    # 12 6        # pounds and ounces are implied 
    # 3 lbs 5 oz  # fully specified 
 
    # repeat until we get input we recognize 
    good_input = False 
    while not good_input: 
        # get input, chunked into words 
        inp = input(prompt).lower().split() 
 
        if len(inp) not in {2, 4}: 
            # we only recognize 2-word or 4-word formats 
            continue    # start the while loop over again 
 
        if not is_float(inp[0]): 
            # we only recognize formats that begin with a number 
            continue 
 
        # get the first number 
        v1 = float(inp[0]) 
 
        if len(inp) == 2: 
            if inp[1] in POUND_WORDS: 
                # first input format 
                lbs = v1 
                ozs = 0 
                good_input = True 
            elif inp[1] in OUNCE_WORDS: 
                # second input format 
                lbs = 0 
                ozs = v1 
                good_input = True 
            elif is_float(inp[1]): 
                # third input format 
                lbs = v1 
                ozs = float(inp[1]) 
                good_input = True 
        else: 
            # 4 words 
            if inp[1] in POUND_WORDS and is_float(inp[2]) and inp[3] in OUNCE_WORDS: 
                lbs = v1 
                ozs = float(inp[2]) 
                good_input = True 
 
    return lbs * OUNCES_PER_POUND + ozs 

现在我们可以用它来获得一堆权重的平均值:

def get_average_weight(prompt): 
    """ 
    Prompt for a series of weights, 
    Return the average 
    """ 
    weights = [] 
    while True: 
        wt = get_weight(prompt) 
        if wt: 
            weights.append(wt) 
        else: 
            break 
    return sum(weights) / len(weights) 

现在我们想要获得每种食物类型的平均值:

def main(): 
    # get average weight for each feed type 
    food_avg = {} 
    while True: 
        food = input("\nFood name (just hit Enter to quit): ").strip() 
        if food: 
            avg = get_average_weight("Rabbit weight in lbs and ozs (enter 0 0 to quit): ") 
            food_avg[food] = avg 
        else: 
            break 
 
    # now we want to print the results, sorted from highest average weight 
    # Note: the result is a list of tuples, not a dict 
    food_avg = sorted(food_avg.items(), key = lambda fw: fw[1], reverse=True) 
 
    # and print the result 
    for food, avg in food_avg: 
        lbs = int(avg // 16) 
        ozs = avg % 16 
        print("{:<20s} {} lb {:0.1f} oz".format(food, lbs, ozs)) 

然后运行它:

main() 

这仍然需要一些麻烦才能正确打印平均重量——我们的程序需要“知道”重量是如何表示的。下一步是将其推回重量类 - 理想情况下是一个与重量单位无关的类(即可以接受任意单位,如千克、磅或英石)。