Print the arithmetic average, the youngest and oldest age - python

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.
Print "Unreasonable age, please try again" when input year is -N, like "-45"
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! :-)

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

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)

Related

How do I stop the loop from going past 12 months?

I need the loop to stop at 12 months and not count all the way up to how many months it takes to reach the goal. I just need it to print how many months it takes to reach the goal but not count all the way to it. I only need it to go up to 12 months. For example if I input an original deposit for 1000, 4.5 interest rate, 12 months, and 1200 goal amount then I want it to only show it counting to 12 months not 49. I still need it to print out how many months it takes to reach the goal at the end but I do not need it to show it counting all the way up to 49. I am sorry if this sounds confusing.
#Keep asking until the user puts in a positive numeric value using loops
fDeposit = 0
while fDeposit <= 0:
try:
fDeposit = float(input('What is the original deposit (positive value): '))
if fDeposit <= 0:
print("Input must be a positive numerical value: ")
except ValueError:
print("Input must be a numeric value")
fInterest = 0
while fInterest <= 0:
try:
fInterest = float(input('What is the Interest Rate (positive value): '))
if fInterest <= 0:
print("Input must be a positive numerical value: ")
except ValueError:
print("Input must be a numeric value")
iMonths = 0
while iMonths <= 0:
try:
iMonths = int(input('What is the number of months (positive value): '))
if iMonths <= 0:
print("Input must be a positive numerical value: ")
except ValueError:
print("Input must be a numeric value")
fGoal = None
while fGoal == None:
try:
fGoal = float(input('What is the goal amount (Can enter 0 but not negative): '))
if fGoal < 0:
print("Input must be a positive numerical value: ")
fGoal = None
except ValueError:
print("Input must be a numeric value")
# Calculate Interest. First convert the variable to a decimal by dividing by 100 then divide
that by 12
fMonthlyInterest= (fInterest/100/12)
#Output the number of months the user has supplied and get account balance
i = 1
fAccountBalance = fDeposit
while i <= fAccountBalance:
if fAccountBalance >= fGoal:
break
fInterestForMonth = (fAccountBalance * fMonthlyInterest)
#Add the interest for the month to the deposit to get the new Account Balance
fAccountBalance += fInterestForMonth
print('Month: ',i, 'Account Balance is: $',format(fAccountBalance, ",.2f"))
i += 1
# Calculate how many months it will take of compounding to reach the goal amount
GoalFormatted = "{:.2f}".format(fGoal)
CompoundedSavingsAccountBalance = fMonthlyInterest + fAccountBalance
while CompoundedSavingsAccountBalance < fGoal:
iMonths += 1
print('It will take: ',i-1, 'months to reach the goal of $', GoalFormatted)
to solve your problem, add "if i < 12:" after line 52, and indent the next line where you printing the month & the account balance. The completed section is below.
i = 1
fAccountBalance = fDeposit
while i <= fAccountBalance:
if fAccountBalance >= fGoal:
break
fInterestForMonth = (fAccountBalance * fMonthlyInterest)
#Add the interest for the month to the deposit to get the new Account Balance
fAccountBalance += fInterestForMonth
if i <= 12:
print('Month: ',i, 'Account Balance is: $',format(fAccountBalance, ",.2f"))
i += 1

Implement a condition into a array

I'm trying to implement another condition into my program but can't seem to figure it out.
Here is the code:
print ("Welcome to the winning card program.")
year_one=[]
year_one.append(eval(input("Enter the salary individual 1 got in year 1: ")))
year_one.append(eval(input("Enter the salary individual 2 got in year 1: ")))
if year_one[0]==year_one[1]:
print("Error. The amount are the same, please reenter information.")
year_two=[]
year_two.append(eval(input("Enter the salary individual 1 got in year 2: ")))
year_two.append(eval(input("Enter the salary individual 2 got in year 2: ")))
if year_two[0]==year_two[1]:
print("Error. The amount are the same, please reenter information.")
year_three=[]
year_three.append(eval(input("Enter the salary individual 1 got in year 3: ")))
year_three.append(eval(input("Enter the salary individual 2 got in year 3: ")))
if year_three[0]==year_three[1]:
print("Error. The amount are the same, please reenter information.")
year_four=[]
year_four.append(eval(input("Enter the salary individual 1 got in year 4: ")))
year_four.append(eval(input("Enter the salary individual 2 got in year 4: ")))
if year_four[0]==year_four[1]:
print("Error. The amount are the same, please reenter information.")
year_five=[]
year_five.append(eval(input("Enter the salary individual 1 got in year 4: ")))
year_five.append(eval(input("Enter the salary individual 2 got in year 4: ")))
if year_five[0]==year_five[1]:
print("Error. The amount are the same, please reenter information.")
individual1_total=year_one[0]+year_two[0]+year_three[0]+year_four[0]+year_five[0]
individual2_total=year_one[1]+year_two[1]+year_three[1]+year_four[1]+year_five[1]
if (individual1_total>individual2_total):
print("Individual one has the highest salary.")
elif (individual2_total>individual1_total):
print("Individual two has the highest salary.")
If the salary for the two individuals for a particular year is exactly the same, you should print an error and make the user enter both the salaries again for that year. (The condition is the salaries should not be the exact same).
I look forward to everyone's feedback.
Thank you in advance.
Ok so building on surge10 here is a more complete replacement of your code. I broke all the pieces down into functions, and made a dictionary as my in in-memory database.
total_years = 5
years = {}
def dict_key(year, userId):
return '{}:{}'.format(year, userId)
def get_user_data(year, userId):
key = dict_key(year, userId)
years[key] = float(input("Enter the salary individual {} got in year {}:".format(userId, year)))
def get_year_salaray(year, userId):
key = dict_key(year, userId)
return years[key]
def any_salaries_match(year, userIds):
for userLeft in userIds:
salary_left = get_year_salaray(year, userLeft)
for userRight in userIds:
if userLeft != userRight:
salary_right = get_year_salaray(year, userRight)
if salary_left == salary_right:
return True
def get_user_totals(userId):
total = 0
for key, value in years.items():
if ':{}'.format(userId) in key:
total += value
return total
for x in range(total_years):
year = x + 1
data_invalid = True
while data_invalid:
userOne = 1
userTwo = 2
get_user_data(year, userOne)
get_user_data(year, userTwo)
if any_salaries_match(year, [userOne, userTwo]):
print("Error. The amount are the same, please reenter information.")
else:
data_invalid = False
userOneTotal = get_user_totals(1)
userTwoTotal = get_user_totals(2)
if (userOneTotal>userTwoTotal):
print("Individual one has the highest salary.")
elif (userTwoTotal>userOneTotal):
print("Individual two has the highest salary.")
Since we were checking for five different years I used a loop for those five years
Later we can get it back into individual years.
print ("Welcome to the winning card program.")
years=[]
for x in range(5):
# range starts at zero so add one all the time
# to start it at one
y = str(x + 1)
errors = True
while errors:
salary_one = input("Enter the salary individual 1 got in year " + y + ": ")
salary_two = input("Enter the salary individual 2 got in year " + y + ": ")
if salary_one == salary_two:
print("Error. The amount are the same, please reenter information.")
errors = True
else:
years.append([salary_one, salary_two])
errors = False
year_one = years[0]
year_two = years[1]
...
print(year_one)
print(year_two)
...

How do I make this code loop into dictionaries and not continue looping in python?

Write a program to calculate the cost of dinner
If the person is under 5, dinner is free
If the person is under 10, dinner is $5
If the person is under 18, dinner is $10
If the person is over 65, the dinner is $12
All other dinners pay $15
Calculate 8% tax
Display the total for each diner, the number of diners, the average cost per diner, and the cumulative total for all diners
Program should loop until exit is entered, with each loop a new diner is added and the total overall numbers updated
Is what I need to do. I'm not sure how to do it so the totals go into dictionaries and not loop.
I've done a similar question, but now this one needs to have the amounts added all together and I'm not sure how. This is the code I've done for a previous similar question. The problem I seem to be currently having i it wont go into the dictionary and there for wont print it at the end. I also need it to keep looping until I type quit.
dinner = {}
total ={}
name = input("What's your name? ")
age = input("What age is the person eating? ")
age = int(age)
amount = input("How many people that age? ")
amount = int(amount)
while True:
if name == 'quit':
print('Done')
break
elif age < 5:
price = 0 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
elif age < 10:
price = 5 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
elif age < 18:
price = 10 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
elif age > 65:
price = 12 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
else:
price = 15 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
print("Thank you for having dinner with us! \nYour total is {total}, for {dinner}.")
The most succinct way to accomplish this is to bin the ages, determine which bin a given age falls into, and then use the index to return the price.
np.digitize accomplishes that task
the parameter bins, contains the ages, and determines which index in the list, a given value fits into. bins is exclusive, therefore the ranges are 0-4, 5-9, 10-17, 18-65 and 66+.
the ranges correspond to index 0, 1, 2, 3, and 4.
idx is used to return the corresponding price per age range
Use a function to return the cost, instead of a bunch of if-elif statements
The directions in yellow, don't require the name or the age of the person to be returned.
Everything required to print at the end, can be calculated from maintaining a list of cost, containing the price of each customer.
print(f'some string {}') is an f-String
Type Hints are used in functions (e.g. def calc_cost(value: int) -> float:).
import numpy as np
def calc_cost(value: int) -> float:
prices = [0, 5, 10, 15, 12]
idx = np.digitize(value, bins=[5, 10, 18, 66])
return prices[idx] + prices[idx] * 0.08
cost = list()
while True:
age = input('What is your age? ')
if age == 'exit':
break
cost.append(calc_cost(int(age)))
# if cost is an empty list, nothing prints
if cost:
print(f'The cost for each diner was: {cost}')
print(f'There were {len(cost)} diners.')
print(f'The average cost per diner was: {sum(cost)/len(cost):.02f}')
print(f'The total meal cost: {sum(cost):.02f}')
Output:
What is your age? 4
What is your age? 5
What is your age? 9
What is your age? 10
What is your age? 17
What is your age? 18
What is your age? 65
What is your age? 66
What is your age? exit
The cost for each diner was: [0.0, 5.4, 5.4, 10.8, 10.8, 16.2, 16.2, 12.96]
There were 8 diners.
The average cost per diner was: 9.72
The total meal cost: 77.76
If not allowed to use numpy:
def calc_cost(value: int) -> float
return value + value * 0.08
cost = list()
while True:
age = input("What age is the person eating? ")
if age == 'exit':
break
age = int(age)
if age < 5:
value = 0
elif age < 10:
value = 5
elif age < 18:
value = 10
elif age < 66:
value = 15
else:
value = 12
cost.append(calc_cost(value))
if cost:
print(f'The cost for each diner was: {cost}')
print(f'There were {len(cost)} diners.')
print(f'The average cost per diner was: {sum(cost)/len(cost):.02f}')
print(f'The total meal cost: {sum(cost):.02f}')
Notes:
Don't use break in all the if-elif conditions, because that breaks the while-loop
Anytime you're repeating something, like calculating price, write a function.
Familiarize yourself with python data structures, like list and dict
this one needs to have the amounts added all together and I'm not sure how.
list.append(price) in the loop
sum(list) to get the total

Why do I get Repeat and "Untill" error when I convert a code From Pseudocode to program in Python? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I am converting pseudocode in the python program but I am stuck and giving me error for
REPEAT
and
UNTIL age >= min AND age <= max.
Please let me know how can I fix it. Thank you in advance
BEGIN
REPEAT
min = 18
max = 60
OUTPUT "what is your age?"
INPUT age
IF age < min or age > max THEN
OUTPUT “Error - age must be between 18 and 60 "
ELSE
OUTPUT "Age is accepted "
ENDIF
UNTIL age >= min AND age <= max
END
min = 18
max = 60
age = int(input('What is your age? '))
while not (min <= age <= max):
print('Error - age must be between 18 and 60')
age = int(input('What is your age? '))
print('Age is accepted')
I guess.
The REPEAT ... UNTIL <condition> construct is something like a do ... while-loop in many languages. Python does not have something like this.
I can think of two solutions for this:
while True:
...
if <condition>:
break
or
continue_loop = True
while continue_loop:
...
if <condition>:
continue_loop = False
You could do while loop with a if condition to breakout when criteria is met.
min = 18
max = 60
while True:
print("what is your age?")
INPUT age # or some other command reading from input
if age < min or age > max:
print(“Error - age must be between 18 and 60 ")
else:
print("Age is accepted ")
if age >= min AND age <= max:
break
Have put the min/max and output values outside of loop as there is no reason to re-set it each time.
You could also break out from loop in the else block where you program is happy with inserted value.
This might be a simple example for the code you have written.
min = 18
max = 60
print("Enter your age")
age = int(input())
if(age < min or age > max):
print("Error : Age must be between 18 and 60")
else: print("Age is accepted and you age is "+ str(age))
Repeat until could be defined like that:
min = 0
max = 100
while true:
age = int(input('age: '))
if (min < age < max):
print('age {0} accepted'.format(age))
break;
print('age should be between {0} and {1}'.format(min, max))
age = int(input('age: '))

Accumulator for outer nested loop Python

I'm learning python on my own from a book and solving problems. In one problem, the user inputs amount of rain for each month in one year across a period of years. I need to find the average of rain in each year (sum(monthly rain)/numb_months, and also the average of rain in that period, e.g. in two years. In the following code, I can get the average for each year (I used 3 months only instead of 12 months to avoid tedious input now), but I don't know where I need to put an accumulator for total rain in that period and then average it. I appreciate your help.
number_of_months = 3
years_in_period = int(input("Please enter the number of years in the period. \n"))
for year in range(years_in_period):
yearly_rain = 0
print('Year', year+1)
print('−−−−−−−−−−−−−−−−−')
for month in range(number_of_months):
print('Month', month+1, end='')
monthly_rain = float(input("Please enter rainfall for this month: \n"))
yearly_rain += monthly_rain
average_yearly_rainfall = yearly_rain / number_of_months
print("Average yearly rainfall of year ", year+1, " is ", average_yearly_rainfall)
print("Year total rain is", yearly_rain)
print()
If I understood what you want (to calculate the absolute average of the rain amount during the period), this should do the trick:
number_of_months = 3
years_in_period = int(input("Please enter the number of years in the period. \n"))
total_rain = 0
for year in range(years_in_period):
yearly_rain = 0
print('Year', year+1)
print('−−−−−−−−−−−−−−−−−')
for month in range(number_of_months):
print('Month', month+1, end='')
monthly_rain = float(input("Please enter rainfall for this month: \n"))
yearly_rain += monthly_rain
total_rain += monthly_rain
average_yearly_rainfall = yearly_rain / number_of_months
print("Average yearly rainfall of year ", year+1, " is ", average_yearly_rainfall)
print("Year total rain is", yearly_rain)
print()
total_months = years_in_period * number_of_months
print("Absolute average of rain/month was", total_rain/total_months)
print("Absolute average of rain/year was", total_rain/years_in_period)

Categories

Resources