Python中的磅和盎司

时间:2017-09-12 01:52:29

标签: python

我刚开始学习编码,而且我试图将磅数换算成盎司。我们假设允许用户输入他们的数据,如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))

3 个答案:

答案 0 :(得分:2)

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

让我们从一个体重开始:

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()

这仍然需要花费一些时间才能正常打印平均重量 - 我们的程序需要“了解”权重的表示方式。下一步是将它推回到Weight类 - 理想情况下是一个与重量单位不相关的类(即可以接受任意单位,如公斤或磅或石头)。

答案 1 :(得分:0)

你需要将磅和盎司保存在单独的变量中,所以需要这样的东西。

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" :
    pounds, ounces = map(int, input().split())
    weight = pounds * 16 + ounces
    sum = sum + weight
    counter = counter + 1
if pounds * ounces == 0:

print ("Average weight " + str(sum/counter))

答案 2 :(得分:0)

第二段代码存在一些问题。

1

question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
while question == "Yes" :
...

你需要在循环中提出你的问题。你会无休止地循环,因为他们永远不会被要求在循环内再次改变问题。我要做的是在循环之前设置question =“Yes”,然后在循环中设置第一行

question = input('''Enter a weight? Type "Yes" or "No" \n\n''')

2

您需要决定用户输入输入的方式。你目前有

ent_num = int(input("Weight of Rabbit:"))

但是ent_num可以是从“6lbs 12oz”到“7pounds11ounces”到“potato”的任何东西。除非你明确告诉他们如何输出重量,否则没有一致的解析方法。一个不那么模糊的问题就是这样说:

raw_input = input("Please enter the weight of the rabbit in pounds 
and ounces with a space separating the two numbers (e.g. 7lbs 12oz):")

然后你可以做一些事情来恢复两个单独的数字。这样的事情应该有效。

#split the string by the space.
chunked_input = raw_input.split()
#get the digits in the two chunks
lbs, ounces = map(lambda x: int(filter(str.isdigit, x)), chunked_input)

现在这个位可能需要一些解释。 map这里是一个函数(lambda x位)并将该函数应用于chunked_input的所有成员。 map(lambda x:x + 2,[4,6,7])== [6,8,9]。

Lambdas只是一个无需命名即可快速创建功能的工具。通过编写自己的函数,你可以完成与lbs,盎司行相同的事情:

def get_digit(my_substring):
    return int(filter(str.isdigit, my_substring)

然后映射它:

lbs, ounces = map(get_digit, chunked_input)

无论如何,一旦你将lbs和盎司作为两个单独的变量,你就可以了。您可以使用您使用的相同公式对它们进行标准化:

weight = pounds * 16 + ounces

然后你最终会得到每重量的盎司总重量。

要打印出最后的平均体重,你可以按照以前的方式进行分割:

#the * 1.0 is because if you can have fractional results, one of 
#either the divisor or the dividend must be a float
avg_oz_weight = sum * 1.0/counter 

然后如果你想用lbs和盎司显示它,你需要两个有用的运算符,%和//。 %被称为模运算符,它在你进行除法时返回余数(7%3 == 1,6%2 == 0)。 //运算符是floor division,所以(7 // 3 == 2,6 // 2 == 3)。

所以你可以用:

打印出一个不错的结果
print("The average weight is: {}lbs {}oz".format(avg_oz_weight // 16,
                                                 avg_oz_weight % 16))