1

This Python program should read a birth year until the number zero is entered.
The program should then print out the average age and how old the youngest and oldest is.

I need help with two things.

  1. Print "Unreasonable age, please try again" when input year is -N, like "-45"
  2. Print the result i.e. the arithmetic average, the youngest and oldest only when I exit the loop. That means when I enter 0.

Current output:

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.

Expected output that I want:

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.

Example code:

# 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! :-)

martineau
  • 119,623
  • 25
  • 170
  • 301
kabax
  • 143
  • 1
  • 12

2 Answers2

3

The code works by simply unindenting the two last print statements and uncommenting the 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.")

I also removed unnecessary comments. But, your code can be simplified very much by simply using a list:

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")
TheEagle
  • 5,808
  • 3
  • 11
  • 39
  • 1
    I know this is mainly a snippet, but I would test for an empty list before doing the prints at the end, just to avoid `ZeroDivisionError` or `ValueError` for `min()` and `max()`. – Ben Y Jul 12 '21 at 21:48
  • @Ben-Y, how do you do that? Was getting ZeroDivisionError when age is for example 0. – kabax Jul 12 '21 at 22:06
  • Check if a list is empty first -- if you enter 0 by itself, you'll end up with an empty list. To check if a list is empty, it's usually `if not ages:` or if you want to be explicit: `if not len(ages):` or `if len(ages) == 0:` – Ben Y Jul 12 '21 at 22:15
  • Try and Except helped, like this: https://stackoverflow.com/questions/29836964/error-python-zerodivisionerror-division-by-zero – kabax Jul 12 '21 at 22:56
  • @kabax you don't need `try: … except` - see my edit. – TheEagle Jul 13 '21 at 11:34
-1

You could store all the ages in a list and then do the math you need with that.

# 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)
Carlos Melus
  • 1,472
  • 2
  • 7
  • 12
  • Sorry if you understood the last sentence of my answer like a personal attack - it wasn't meant like that. Can you maybe explain to me why people (not just you !) prefix builtin functions with `np.` ? – TheEagle Jul 13 '21 at 11:31