【问题标题】:Print the arithmetic average, the youngest and oldest age打印算术平均值,最小和最大年龄
【发布时间】:2021-07-12 21:02:15
【问题描述】:

这个 Python 程序应该读取出生年份,直到输入数字 0。
然后程序应该打印出平均年龄以及最小和最大的年龄。

我在两件事上需要帮助。

  1. 输入年份为-N时打印“年龄不合理,请重试”,如“-45”
  2. 当我退出循环时打印结果,即算术平均值,最年轻和最老。 这意味着当我输入 0 时。

当前输出:

Please type in birth year, to stop, enter 0: 1948
Average age is  72.0 years old.
The younges is 72 years old,  and the oldest is  72 years old.
Please type in birth year, to stop, enter 0: 1845
Unreasonable age, please try again
Average age is  72.0 years old.
The younges is 72 years old,  and the oldest is  72 years old.
Please type in birth year, to stop, enter 0: 1995
Average age is  48.5 years old.
The younges is 25 years old,  and the oldest is  72 years old.
Please type in birth year, to stop, enter 0: 2005
Average age is  37.333333333333336 years old.
The younges is 15 years old,  and the oldest is  72 years old.
Please type in birth year, to stop, enter 0: 0
Average age is  37.333333333333336 years old.
The youngest is 15 years old,  and the oldest is  72 years old.

我想要的预期输出:

Please type in birth year, to stop, enter 0.
Year: 1998
Year: 1932
Year: 1887
Fail: Unreasonable age, please try again.
Year: 1987
Year: -77
Fail: Unreasonable age, please try again.
Year: 1963
Year: 0
Average age is 49 years old. The youngest is 21 years old, and the oldest is 87 years old.

示例代码:

# set number_years to zero     ### Initial value (has not started counting yet)
number_year = 0
# set number_years to zero     ### Initial value (has not started counting yet)
sum_year = 0
# set sum_year to zero    ### No maximum age yet
max_year = 0
# set max_year to zero      ### Well increased minimum value (age) to start with
min_year = 110
# set input_year to minus 1 ### Only as start value for the sake of the loop start!
input_year = -1

# White input_year is not 0:
while input_year != 0:
    # print info and store input value to input_year, stop if 0 is entered
    input_year = int(input("Please type in birth year, to stop, enter 0: "))
    # let age be (2020 - input_year)
    age = (2020 - input_year)
    # To avoid beauty flaws with the printout "Unreasonable year ..."
    # when the final zero is entered, we must check that age is not 2020
    # which it is deceptive enough because 2020-0=2020

    # if age is less than zero or age is greater than 110 and age is not 2020:
    if age < 0 or age > 110 and age != 2020:
        # Print "Unreasonable age, please try again"
        print("Unreasonable age, please try again")
    # else
    else:
        # if input_year is greater than zero:
        if input_year > 0:
            # increase number_year with 1
            number_year += 1
            # let sum_year become sum_year + age
            sum_year = sum_year + age
            # if age is less than min_year:
            if age < min_year:
                # set min_year to age ### New minimum age found
                min_year = age
            # if age is bigger than max_year:
            if age > max_year:
                # set max_year to age ### New maximum age found
                max_year = age

    ## If the entered number was 0, exit the loop
    #if input_year == 0:
    #    break

    # Now just print the arithmetic average, the youngest and oldest
    # Print "Average age is ", sum_year / number_year, "year."
    print("Average age is ", sum_year / number_year, "years old.")
    # Print "The younges is ", min_year, " and the oldest is ", max_year
    print("The youngest is", min_year, "years old,", " and the oldest is ", max_year, "years old.")

# Done! :-)

【问题讨论】:

    标签: python statistics


    【解决方案1】:

    代码通过简单地取消缩进最后两个打印语句并取消注释if …: break来工作:

    # Initial value (has not started counting yet)
    number_year = 0
    # Initial value (has not started counting yet)
    sum_year = 0
    # No maximum age yet
    max_year = 0
    # Well increased minimum value (age) to start with
    min_year = 110
    # Only as start value for the sake of the loop start!
    input_year = -1
    
    while input_year != 0:
        # print info and store input value to input_year, stop if 0 is entered
        input_year = int(input("Please type in birth year, to stop, enter 0: "))
        age = 2020 - input_year
        # To avoid beauty flaws with the printout "Unreasonable year ..." 
        # when the final zero is entered, we must check that age is not 2020 
        # which it is deceptive enough because 2020-0=2020 
    
        if age < 0 or age > 110 and age != 2020:
            print("Unreasonable age, please try again")
        # else
        else:
            if input_year > 0:
                number_year += 1
                sum_year += age
                if age < min_year:
                    ### New minimum age found
                    min_year = age
                if age > max_year:
                    ### New maximum age found
                    max_year = age
    
        if input_year == 0:
            break
    
    # print the arithmetic average, the youngest and oldest
    print("Average age is ", sum_year / number_year, "years old.")
    print("The youngest is", min_year, "years old,", " and the oldest is ", max_year, "years old.")
    

    我还删除了不必要的 cmets。但是,您的代码可以通过简单地使用列表来大大简化:

    ages = []
    
    while True: # infinite loop - we will exit by break-ing when age is 0
        age = 2020 - int(input("Please enter birth year (0 to exit)"))
    
        if age == 2020: # user entered a 0 - exit loop
            break
    
        if age < 0 or age > 110:
            print("Unreasonable age, please try again")
            continue # directly go to next loop
        
        ages.append(age) # will only get appended if the condition above was false because of the continue
    
    if ages: # ages list is not empty
        print("Average age is", sum(ages) / len(ages), "years old")
        print("The youngest is", min(ages), "old, and the oldest is", max(ages), "old")
    else:
        print("No ages entered - cannot print mean, min and max age - exiting")
    

    【讨论】:

    • 我知道这主要是一个 sn-p,但我会在最后打印之前测试一个空列表,以避免ZeroDivisionErrorValueError 用于min() 和@ 987654328@.
    • @Ben-Y,你是怎么做到的?例如,年龄为 0 时会出现 ZeroDivisionError。
    • 先检查一个列表是否为空——如果你自己输入0,你最终会得到一个空列表。要检查列表是否为空,通常是 if not ages: 或者如果您想明确:if not len(ages):if len(ages) == 0:
    • 尝试并排除帮助,例如:stackoverflow.com/questions/29836964/…
    • @kabax 你不需要try: … except - 查看我的编辑。
    【解决方案2】:

    您可以将所有年龄存储在一个列表中,然后用它做您需要的数学运算。

    # initialize your list
    ages = []
    
    # run your code here, adding the age value with each valid input
    # this can be done right before finishing the loop, after the last if statement
    ...
    while input_year != 0:
        ...
        ages.append(age)
    
    # at the end, do the required calculations
    average_age = np.mean(ages)
    min_age = np.min(ages)
    max_age = np.max(ages)
    

    【讨论】:

    • 很抱歉,如果您将我回答的最后一句话理解为人身攻击 - 这不是那个意思。您能否向我解释一下为什么人们(不仅仅是您!)为内置函数加上 np. 前缀?
    猜你喜欢
    • 2020-03-01
    • 2017-02-12
    • 1970-01-01
    • 2017-01-26
    • 2018-10-29
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多