I am trying to write a program in which the user enters the age of 8 guests. Each guest's age is priced differently. How can I add each cost together to come up with the total cost for each guest? This is what I have written.
def main():
guest1= int(input("Enter the age of guest 1(in years): "))
guest2 = int(input("Enter the age of guest 2(in years): "))
guest3 = int(input("Enter the age of guest 3(in years): "))
guest4 = int(input("Enter the age of guest 4(in years): "))
guest5 = int(input("Enter the age of guest 5(in years): "))
guest6 = int(input("Enter the age of guest 6(in years): "))
guest7 = int(input("Enter the age of guest 7(in years): "))
guest8 = int(input("Enter the age of guest 8(in years): "))
ages = [guest1, guest2, guest3, guest4, guest5, guest6, guest7, guest8]
getCost(ages)
def getCost(ages):
for age in ages:
if age <=2:
cost = 0
print(cost)
elif age <= 3>12:
cost = 14
print(cost)
elif age >= 65:
cost = 18
print(cost)
else:
cost = 23
print(cost)
main()
You can put all the ages into a list up front by calling input() in a loop instead of copying and pasting it eight times:
ages = [int(input(f"Enter the age of guest {i}(in years): ")) for i in range(1, 9)]
I'd suggest having your getCost function just return the cost for a single age (hint: make this simpler by arranging the age brackets in ascending order, and eliminating them one at a time according to their upper bound):
def getCost(age):
if age < 3:
return 0
elif age < 12:
return 14
elif age < 65:
return 23
else:
return 18
This makes the job of getCost much easier -- then after you've gotten ages you can compute the total cost just by calling getCost(age) for each age and taking the sum of the result:
print(sum(getCost(age) for age in ages))
Splitting the logic into parts like this makes it easy to do other things with the costs; for example, you could show how the total was computed by joining the costs before you sum them:
print(
" + ".join(str(getCost(age)) for age in ages),
"=",
sum(getCost(age) for age in ages)
)
Enter the age of guest 1(in years): 2
Enter the age of guest 2(in years): 9
Enter the age of guest 3(in years): 13
Enter the age of guest 4(in years): 27
Enter the age of guest 5(in years): 44
Enter the age of guest 6(in years): 52
Enter the age of guest 7(in years): 66
Enter the age of guest 8(in years): 81
0 + 14 + 23 + 23 + 23 + 23 + 18 + 18 = 142
You can start by defining a totalCost variable, as a running total that you can keep incrementing after you calculate the cost for each customer. For instance:
def getCost(ages):
totalCost = 0
for age in ages:
if age <=2:
cost = 0
elif age >= 3 and age < 12:
cost = 14
elif age >= 65:
cost = 18
else:
cost = 23
totalCost += cost
return totalCost
Do note that I've assumed age <= 3>12 refers to ages between 3 and 11, inclusive.
It seems that you use function getCost to calculate each cost. A little bit modification of adding a variable to sum up all values will help you get what you want.
def sumCost(ages):
total = 0
for age in ages:
if age <=2:
cost = 0
elif age <= 3>12: # your original code may have some problems here. I just keep it.
cost = 14
elif age >= 65:
cost = 18
else:
cost = 23
total = total + cost
return total
Or you can construct a list of cost then use sum.
def sumCost(ages):
costs = []
for age in ages:
if age <=2:
cost = 0
elif age <= 3>12: # your original code may have some problems here. I just keep it.
cost = 14
elif age >= 65:
cost = 18
else:
cost = 23
costs.append(cost)
total = sum(costs)
return total
Related
Is there a way to simplify the code here using function and loops?
I would like to simplify it but not sure how to.
age1 = int(input("Enter age:"))
if age1 < 12:
price1 = 10
else:
if age1 < 59:
price1 = 20
else:
price1 = 15
age2 = int(input("Enter age:"))
if age2 < 12:
price2 = 10
else:
if age2 < 59:
price2 = 20
else:
price2 = 15
age3 = int(input("Enter age:"))
if age3 < 12:
price3 = 10
else:
if age3 < 59:
price3 = 20
else:
price3 = 15
total = price1 + price2 + price3
print("The total price for the tickets is $" + str(total))
I would do this
people = int(input('Enter number of people: '))
min_age=12
max_age=59
def price(min_age, max_age):
age = int(input("Enter age:"))
if age < min_age:
price = 10
else:
if age < max_age:
price = 20
else:
price = 15
return price
prices = []
for j in range(people):
prices.append(price(min_age, max_age))
total_price = sum(prices)
print("The total price for the tickets is $" + str(total_price))
I would suggest creating a function that, given the age and returns the price. You can also create a function to get the age. It will then be easy to use in a loop or a comprehension to add up the prices:
def getAge(): return int(input("Enter age:"))
def getPrice(age): return 10 if age <12 else 20 if age < 59 else 15
total = sum(getPrice(getAge()) for _ in range(3))
print(f"The total price for the tickets is ${total}")
Enter age:65
Enter age:25
Enter age:9
The total price for the tickets is $45
This will separate computations from user interactions and it will be easy to add validations to the input (such as a permissible age range or to check if the value is numeric)
try using the while statement, in this context;
while true:
# Code goes here
while true: means that when the program is running, execute this code repeatedly until it stops.
I am trying to update my string variable then return it to be printed.
race = 'human'
age = int(x)
def aging(age, maturity):
if x < 13:
maturity = 'Child'
elif x>13 and x<18:
maturity = 'Teenager'
elif x>18 and x<65:
maturity = 'Adult'
elif x>65 and x<99:
maturity = 'Senior'
else:
maturity = 'Dead'
aging(age, maturity)
x=int(input('Please enter age: '))
print ("Age is",age)
print ("You are a "+maturity)
The end product, however, is always
Please enter age: 9
Age is 9
You are a none
How can I get the maturity string to update?
Let's address your program as a whole -- the major issue I see is that your data is embedded in your code. Let's separate out the data to simplify the code:
MATURITIES = {
'a Child': (0, 12),
'a Teenager': (13, 17),
'an Adult': (18, 64),
'a Senior': (65, 99),
}
def aging(age):
for maturity, (lower, upper) in MATURITIES.items():
if lower <= age <= upper:
return maturity
return 'Dead'
age = int(input('Please enter age: '))
print("Your age is", age)
print("You are", aging(age))
You need to refactor your code - remove x, change where you define variables/take input, and return something (maturity):
def aging(age):
if age < 13:
maturity = 'Child'
elif age > 13 and age < 18:
maturity = 'Teenager'
elif age > 18 and age < 65:
maturity = 'Adult'
elif age > 65 and age < 99:
maturity = 'Senior'
else:
maturity = 'Dead'
return maturity
age = int(input('Please enter age: '))
maturity = aging(age)
print ("Age is" + age)
print("You are a " + maturity)
Output:
Please enter age: 9
Age is 9
You are a Child
Use return
def aging(age, maturity):
if x < 13:
maturity = 'Child'
elif x>13 and x<18:
maturity = 'Teenager'
elif x>18 and x<65:
maturity = 'Adult'
elif x>65 and x<99:
maturity = 'Senior'
else:
maturity = 'Dead'
return age, maturity
race = 'human'
age = int(input('Please enter age: '))
age, maturity = aging(age, maturity)
print ("Age is",age)
print ("You are a "+maturity)
I recommend your function to return maturity.
You can global the variable, but it is considered a bad practice.
I did a few corrections on your code, it should work fine like this:
def aging(age):
if age < 13:
maturity = 'Child'
elif age >= 13 and age <18:
maturity = 'Teenager'
elif age >= 18 and age <65:
maturity = 'Adult'
elif age >= 65 and age < 99:
maturity = 'Senior'
else:
maturity = 'Dead'
return maturity
age = int(input('Please enter age: '))
print ("Age is", age)
print ("You are a", aging(age))
I want to write a program to display birth date using strings. Please check the code:
dob = int(input("enter your birth day"))
if dob > 31 or dob < 1:
print("invalid")
mob = int(input("enter your birth month"))
if mob > 12 or mob < 1:
print("invalid")
yob = int(input("enter your birth year"))
date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(date[0], date[1], date[2])
print(bday)
Output:
I want to make this program in a way that a valid date can be printed eg:
32/23/2020 is invalid and therefore must not be printed.
You can do
while True:
dob = int(input("enter your birth day"))
if not 1 <= dob <= 31:
print("invalid")
continue
break
while True:
mob = int(input("enter your birth month"))
if not 1 <= mob <= 12:
print("invalid")
continue
break
yob = int(input("enter your birth year"))
date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(date[0], date[1], date[2])
print(bday)
This code will ask for day and month until they will be valid and then insert the year and you will get the print statement to print validate date.
Try to understand it, it's simple:
dob = int(input("enter your birth day"))
if dob not in range(1,32):
print("invalid")
mob = int(input("enter your birth month"))
if mob not in range(1,13) :
print("invalid")
yob = int(input("enter your birth year"))
if yob not in range(1900,2021):
print("invalid")
date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(date[0], date[1], date[2])
print(bday)
You have to use or operator, your value will never be greater than 31 and lower than 1 at the same time
if dob > 31 or dob < 1
print("Invalid")
Also you may want to ask again until the value is valid, not just telling the use, use a while loop for that
dob = 0
while dob > 31 or dob < 1:
dob = int(input("enter your birth day: "))
mob = 0
while mob > 12 or mob < 1:
mob = int(input("enter your birth month: "))
yob = int(input("enter your birth year: "))
date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(*date) # * operator is for unpacking the list
print(bday)
Demo
enter your birth day: 32
enter your birth day: 35
enter your birth day: 15
enter your birth month: 55
enter your birth month: 20
enter your birth month: 10
enter your birth year: 1950
Your birthday is on: 15/10/1950
Im attempting to write a code where the user if prompted for todays date and their birthdate in order to determine their age. The age will determine how much their ticket price will be. If they are 14 and younger the price would be five dollars. If they are 15 to 64 the price would be nine dollars and if they are 65 and older the price would be 7.50. It would ask if the customer has a coupon, which would take off one dollar off their price. What I have so far:
print ("Hello, welcome to Hopper's Computer Museum! To determine your enterance fee, please enter the following:")
print ('Your Date of Birth (mm dd yyyy)')
Date_of_Birth = input("--->")
print ('Todays Date: (mm dd yyyy)')
Todays_Date = input("--->")
age = (tYear-bYear)
if (bMonth > tMonth):
age == age-1
if (bMonth == tMonth and
bDay > tDay):
age == age-1
if age < 14:
price==5.00
elif age > 15 and age < 64:
price==9.00
elif age > 65:
price==7.50
print ('Do you have a coupon (y/n)?')
Discount = input("--->")
if Discount == "y" or Discount == "Y":
price = price-1
elif Discount == "n" or Discount == "N":
price = price
print ('Your admission fee is $4.00 enjoy your visit!')
I know that I need define my variables such as tYear, bYear, bDay, ect, but I'm not sure what I should assign them to.
You can use map to assign values to tYear, bYear etc. You can do following instead of Date_of_birth = input('--->')
bDay,bMonth,bYear = map(int,raw_input('--->').split())
This will assign bDay, bMonth and bYear as per requirement if the input format is 'dd mm yyyy'. Similarly for today's date you can write:
tDay,tMonth,tYear = map(int,raw_input('--->').split())
Alternate option is to calculate age using datetime. Follow this - Age from birthdate in python
I have this assignment for school work, this is pretty basic stuff i gather but I'm new to this language so I'm still a little nooby. I get the aforementioned error upon testing each module with the error being specific to this line and this line alone.
def data(n, p, gn, s):
name[x] = input("Please enter the customer's name.")
n.append(name[x])
phone = int(input("Please enter the customer's Phone Number."))
if len.str(phone[x]) == 11:
p.append(attendance[x])
else : phone[x] = int(input("Please enter the customer's Phone Number."))
if len.str(phone[x]) == 11:
p.append(attendance[x])
groupno[x] = int(input("Please enter the number of diners in the group - length must be 11 characters."))
if 1 >= groupno[x] <=20:
gn.append(groupno[x])
else: groupno[x] = int(input("Please enter the number of diners in the group - between 1 & 20."))
gn.append(groupno[x])
score[x] = int(input("Please enter the rating of the meal."))
if 1 >= score[x] <=3:
s.append(score[x])
else: score[x] = int(input("Please enter the rating of the meal - between 1 & 10."))
if 1 >= score[x] <=3:
s.append(score[x])
data()
It looks like you are trying to store information about multiple customers, I suggest you use a dictionary instead:
def data():
name = input("Please enter the customer's name.")
temp_phone = int(input("Please enter the customer's Phone Number."))
while len.str(temp_phone) != 11:
temp_phone = int(input("Please enter the customer's Phone Number."))
phone = temp_phone
temp_groupno = int(input("Please enter the number of diners in the group (maximum 20 diners)"))
while not (1 <= groupno <=20):
temp_groupno = int(input("Please enter the number of diners in the group (maximum 20)"))
group = temp_groupno
temp_score = int(input("Please enter the rating of the meal (between 1 and 10)"))
while not (1 <= temp_score <= 3):
temp_score = int(input("Please enter the rating of the meal - between 1 & 10."))
score = temp_score
return {'name': name, 'phone': phone, 'group': group, 'score': score}
customers = []
customers.append(data())
customers.append(data())
print(customers)
Your function require 4 parameters and you have given it none.
When you define a function like so: def foo(a,b,c,d), you need to supply it with a,b,c and d.
name[x] = input("Please enter the customer's name.")
n.append(name[x])
This will also give you an error as x is undefined.