我刚刚开始学习编码,但是在尝试将英镑转换为盎司时遇到了一个问题。我们假设允许用户输入他们的数据,例如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()


为了使平均重量正确打印,这仍然需要花时间进行一些讨论-我们的程序需要“知道”重量的表示方式。下一步是将其推回“重量”类别-理想情况下,该类别与重量单位无关(即可以接受任意单位,例如公斤,磅或石头)。

09-25 19:59