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
Related
I am trying to code ticket prices depending on a persons gender and age. I coded the following:
sex=(input("What gender are you?: ")).lower()
age=(input("What age are you?: "))
priceofticket=100
if sex=="male":
print ("Male ticket price is")
if age>= "60":
print(priceofticket*.7, "for senior citizen")
elif age<="60":
print(priceofticket, "for normal citizen")
if sex=="female":
print ("Female ticket price is")
if age>= "60":
print(priceofticket*.5, "for senior citizen")
elif age >"60":
print(priceofticket*.7, "for senior citizen")
This code works fine UNTIL the age goes above 99. After 99 it doesnt return any number. I put a "" around 60 because it wont take an integer data type saying i cannot use str and int together. I think this is the problem but i'm not sure.
Thanks!
You are comparing strings for age, rather than ints.
>>> "100" > "6"
False
Comparison of strings means the above compares "1" to "6" and finds "100" to not be greater than "65".
sex = input("What gender are you?: ").lower()
age = int(input("What age are you?: "))
priceofticket = 100
if sex == "male":
print("Male ticket price is")
if age >= 60:
print(priceofticket * .7, "for senior citizen")
elif age <= 60:
print(priceofticket, "for normal citizen")
if sex == "female":
print("Female ticket price is")
if age >= 60:
print(priceofticket * .5, "for senior citizen")
elif age > 60:
print(priceofticket * .7, "for senior citizen")
There are some other issues with your code.
When checking the age, you do not need elif but can rather just use else.
You can use elif for the sex == "female" condition.
f-strings are your friends when printing.
sex = input("What gender are you?: ").lower()
age = int(input("What age are you?: "))
priceofticket = 100
if sex == "male":
print("Male ticket price is")
if age >= 60:
print(f"{priceofticket * .7} for senior citizen")
else:
print(f"{priceofticket} for normal citizen")
elif sex == "female":
print("Female ticket price is")
if age >= 60:
print(f"{priceofticket * .5} for senior citizen")
else:
print(f"{priceofticket * .7} for senior citizen")
You may also wish to flatten your nested conditionals.
sex = input("What gender are you?: ").lower()
age = int(input("What age are you?: "))
priceofticket = 100
if sex == "male" and age >= 60:
print("Male ticket price is")
print(f"{priceofticket * .7} for senior citizen")
elif sex == "male":
print("Male ticket price is")
print(f"{priceofticket} for normal citizen")
elif sex == "female" and age >= 60:
print("Female ticket price is")
print(f"{priceofticket * .5} for senior citizen")
elif sex == "female":
print("Female ticket price is")
print(f"{priceofticket * .7} for senior citizen")
Try to parse age variable as int type.
Your code should be like the following code:
sex= input("What gender are you?: ").lower()
age= int(input("What age are you?: "))
priceofticket=100
if sex=="male":
print ("Male ticket price is")
if age >= 60:
print(priceofticket*.7, "for senior citizen")
elif age <= 60:
print(priceofticket, "for normal citizen")
if sex=="female":
print ("Female ticket price is")
if age>= 60:
print(priceofticket*.5, "for senior citizen")
elif age > 60:
print(priceofticket*.7, "for senior citizen")
Instead of comparing the input from the user formatted as a string against the string "60", convert the user's input into a number, verify that it works, then compare it against 60 as an integer
You will need to convert age to an integer and compare it with integers.
(Also, those elses can use a bit of simplifying, and there was a copy-paste error in the prose for the female non-senior branch. :-) )
sex = (input("What gender are you?: ")).lower()
age = int(input("What age are you?: "))
priceofticket = 100
if sex == "male":
print("Male ticket price is")
if age >= 60:
print(priceofticket * 0.7, "for senior citizen")
else:
print(priceofticket, "for normal citizen")
if sex == "female":
print("Female ticket price is")
if age >= 60:
print(priceofticket * 0.5, "for senior citizen")
else:
print(priceofticket * 0.7, "for normal citizen")
The 'age' variable is treated as a string and both the if and else branches are failing due to string comparison logic, and hence nothing is printed.
Change the second line to:
age=int(input("What age are you?: "))
And remove the quotes around the numbers in the if..else.. conditions.
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
here is the code=
def main():
print("Enter your age: ")
age= float(input())
while age >= 0:
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
and here is the problem I am trying to solve:
Create a program that begins by reading the ages of all of the guests in a group from the user, with one age entered on each line. The user will enter -1 to indicate that there are no more guests in the group. Then your program should display the admission cost for the group with an appropriate message. The cost should be displayed using two decimal places. Use the following sample run for input and output messages.
You need to move the prompt for input into the loop, otherwise age never changes within the while, creating an infinite loop.
def main():
age = 1
while age >= 0:
print("Enter your age: ")
age = float(input())
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
You never update age after its initial value and so the while loop continues forever, printing a line for each iteration.
You need to put a
age = float(input())
as the last line of the while loop.
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
Hey guys I have to do this payroll program for my programming class, but I'm about to fry my brain, because I can't get to do some if statements with the conditions my assignment is asking for. Here's what I have to do
Salespeople at SoftwarePirates get paid a base salary of $2000 per month. Beyond the base salary, each salesperson earns commission on
the following scale:
Sales | Commission Rate | Bonus
<10000 | 0% | 0
10000 – $100,000 | 2% | 0
$100,001 - $500,00 | 15% | $1000
$500,001 - $1,000,000 | 28% | $5000
$1,000,000 | 35% | $100,000
The following additional conditions apply:
If a salesperson has taken more than 3 vacation days in a month, their pay gets reduced by $200
A salesperson earns a bonus only if they have been with the company for 3 months or more
For salespeople who have been with the company for more than 5 years and who have made sales greater than $100,000 an additional
bonus of $1000 is added
Here's the code I've had so far(it's pretty messy, but I can only use if statements, not while loop or stuff like that since we are following the class book)
name = input("What's your name? ")
time = int(input("Enter the amount of months you've been working for SoftwarePirates Inc.: "))
vacation = input('Have you taken more than 3 days of vacations(yes or no) ')
sales = float(input("What were your sales this year? "))
def comissionOne():
base = 24000
print("Your commision rate is 0%, so your salary for the year is $", base)
if time <=3:
print("No bonus earned")
if vacation == 'yes':
print ("Your salary is reduced by $200 for taking more than 3 days off, leaving you at $", (base-200))
elif vacation == 'no':
print()
def comissionTwo():
base = 24000
print("Your commision rate is 2%, so your salary for the year is $", (base*0.02 + base))
if time <=3:
print("No bonus earned")
if vacation == 'yes':
print ("Your salary is reduced by $200 for taking more than 3 days off, leaving you at $", (base*0.02 + (base-200)))
elif vacation == 'no':
print()
def comissionThree():
print("Your commision rate is 15%, so your salary for the year is $", (base*0.15 + base))
if time <=3:
print("No bonus earned")
elif time > 3 and < 60:
print("Bonus of $1000 earned")
elif time >= 60:
print("Bonus of $1000 for being in the company for over 5 years")
if vacation =='yes':
print ("Your salary is reduced by $200 for taking more than 3 days off, leaving you at $", (base*0.15 + (base-200)))
elif vacation == 'no':
print()
def main():
print("Hi", name)
if sales < 10000:
comissionOne()
elif sales >=10000 and sales <=100000:
comissionTwo()
elif sales >=100001 and sales <=500000:
comissionThree()
elif sales >=500001 and sales <=1000000:
print("Your commision rate is 28%, so your salary for the year is $", (base*0.28 + base))
elif sales >=1000001:
print("Your commision rate is 35%, so your salary for the year is $", (base*0.35 + base))
main()
Thank you, hope anyone can guide me through this! I just don't know how to apply the conditions to the final gross pay.
You're writing your if conditions with multiple checks wrong. When you need to check multiple conditions, you are doing this:
if foo > 0 and < 60:
# then...
But you should be doing:
if foo > 0 and foo < 60:
# then..
or like this:
if 0 < foo < 60:
# then...