Convert dog ages to human years - python

it as been a long time without programming. I'm doing a function that converts the age of a dog to human years, but I'm getting some mistakes and I am not getting through them. This is my code
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
d_age = float(age)
# If user enters negative number, print message
if(d_age < 0):
print("Age can not be a negative number", age)
# Otherwise, calculate dog's age in human years
elif(d_age == 1):
d_age = 15
elif(d_age == 2):
d_age = 2 * 12
elif(d_age == 3):
d_age = 3 * 9.3
elif(d_age == 4):
d_age = 4 * 8
elif(d_age == 5):
d_age = 5 * 7.2
else:
d_age = 5 * 7.2 + (float(age) - 5) * 7
print("\n \t \'The given dog age", age, "is", d_age, "human years.'")
except ValueError:
print(age, "is an invalid age")
calculator()
and I'm not understanding why d_age < 0 is not working and I'm not getting why it appears as an error "calculator() is not defined". Thanks in advance!
NOTE: I saw that there already is question about this, but I'm doing in a different way.
EDIT: I just didn't do it with dictionaires, because it wasn't yet introduced in the course. I'm just trying to do with what I learned. Thanks anyway.

Looks like your code is not structure correctly. If you move the elif blocks and make some minor changes it will work. See below:
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
d_age = float(age)
# If user enters negative number, print message
if(d_age < 0):
print("Age can not be a negative number", age)
# Otherwise, calculate dog's age in human years
elif(d_age == 1):
d_age = 15
elif(d_age == 2):
d_age == 2 * 12
elif(d_age == 3):
d_age == 3 * 9.3
elif(d_age == 4):
d_age = 4 * 8
elif(d_age == 5):
d_age = 3 * 7.2
else:
d_age = 5 * 7.2 + (age - 5) * 7
print("\n \t \'The given dog age", age, "is", d_age, "human years.")
except ValueError:
print(age, "is an invalid age")
calculator()

How about this?
While statement to keep question looping until you get a valid response.
Dictionary to have a more organised age calculation sheet instead of lots of if statements.
def calculator_dog_age():
age = 0
while age == 0:
age = input("Input dog years: ")
try:
age = int(age)
if 20 > age > 0:
print('A good age was entered:', age)
age_dict = {1: 15, 2: 24, 3: 27.9, 4: 32}
if age in age_dict:
return age_dict[age]
else:
return age * 7.2 + (age - 5) * 7
else:
print('Please enter a realistic age!')
age = 0
except:
print('Please enter an integer!')
age = 0
print(calculator_dog_age())

This is my suggestion, even though the answer was accepted.
def calculator():
age = input("Input dog years: ")
try:
d_age = float(age)
ageDict = {1: 15, 2: 12, 3: 9.3, 4: 8, 5: 7.2}
if d_age in ageDict:
print(round(d_age*ageDict[d_age],2))
else:
print(round(5*7.2+(d_age - 5)*7,2))
except ValueError:
print(age,"is an invalid age")
calculator()

#get user's input on dog_age
dog_age = input("Enter your dog's age in years")
try:
#cast to a float
d_age = float(dog_age)
#convert dog age to human age
#ensure input is not negative
if (d_age > 0):
if (d_age <=1):
h_age = d_age *15
elif (d_age <=2):
h_age = d_age *12
elif (d_age <=3):
h_age = d_age*9.3
elif (d_age <=4):
h_age = d_age*8
elif (d_age <=5):
h_age = d_age*7.2
else:
h_age = 36 + (d_age - 5) *7
human_age = round(h_age,2)
#print instruction for valid input
print('The given dog age', dog_age,'is', str(human_age),'in human years')
else:
print('Age cannot be a negative number.')
except ValueError:
print(dog_age,'is invalid.')
The question I was solving has similar conditions but with different calculations required. I hope it helps (P.S initially I also could not figure out why my dog age <0 condition was not working, turns out, it’s all about blocking the conditions together and indentation use (: )

If anyone struggling with indention error or "SyntaxError: unexpected character after line continuation character" from print("\n \t 'The given dog age", age, "is", d_age, "human years."
The following solution helped me
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
d_age = float(age)
if (d_age> 5):
human_age = (d_age-5)*7+5*7.2
print("The given dog age",str(d_age),"is", str(human_age), "in human years")
elif (d_age>4):
human_age = d_age*7.2
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age>3):
human_age = d_age*8
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age>2):
human_age = d_age*9.3
print("The given dog age",str(d_age),"is",round(human_age,2),"in human years")
elif (d_age>1):
human_age = d_age*12
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age>0):
human_age = d_age*15
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age<0 or d_age==0):
print(d_age, "is a negative number or zero. Age can not be that.")
except:
print(age, "is an invalid age.")
print(traceback.format_exc())
calculator()

Related

My function is not defined properly, can anyone tell me why?

I have a main function, and a getDogYears function that contains the variable dogYears. I have tried moving getDogYears above the main function, and I have tried initializing dogYears in the main function. I know dogYears is outside the scope of the main function, so can anyone tell me how I can make my main function be able to display information found in getDogYears? I'm sure it's something silly, but it would be a great lesson for me. Thank you!
The error: Traceback (most recent call last):
line 38, in
main()
line 21, in main
format(dogYears, ",.1f"), "in dog years.")
NameError: name 'dogYears' is not defined. Did you mean: 'getDogYears'?
FIRST_YEAR_EQUIV = 15
SECOND_YEAR_EQUIV = 9
THREE_PLUS_YEARS_MULTIPLIER = 5
def main():
print("This program calculate's a dog's approximate age in \"dog years\" based on human years.\n")
humanYears = float(input("Dog's age in human years? "))
while humanYears < 0:
print("\nHuman age must be a positive number.")
humanYears = float(input("Dog's age in human years? "))
else:
getDogYears(humanYears)
# end if
print("\nA dog with a human age of", format(humanYears, ",.1f"), "years is",
format(dogYears, ",.1f"), "in dog years.")
def getDogYears(humanYears):
if humanYears <= 1:
dogYears = FIRST_YEAR_EQUIV * humanYears
elif humanYears <= 2:
dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV * (humanYears - 1)
else:
dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV + THREE_PLUS_YEARS_MULTIPLIER * (humanYears - 2)
# DO NOT MODIFY CODE BELOW THIS LINE
if __name__ == "__main__":
main() ```
Do a return dog years from getDogYears(), and do dogYears = getDogYears(humanYears) inside the main() function.
FIRST_YEAR_EQUIV = 15
SECOND_YEAR_EQUIV = 9
THREE_PLUS_YEARS_MULTIPLIER = 5
def main():
print("This program calculate's a dog's approximate age in \"dog years\" based on human years.\n")
humanYears = float(input("Dog's age in human years? "))
while humanYears < 0:
print("\nHuman age must be a positive number.")
humanYears = float(input("Dog's age in human years? "))
else:
dogYears = getDogYears(humanYears)
# end if
print("\nA dog with a human age of", format(humanYears, ",.1f"), "years is",
format(dogYears, ",.1f"), "in dog years.")
def getDogYears(humanYears):
if humanYears <= 1:
dogYears = FIRST_YEAR_EQUIV * humanYears
elif humanYears <= 2:
dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV * (humanYears - 1)
else:
dogYears = FIRST_YEAR_EQUIV + SECOND_YEAR_EQUIV + THREE_PLUS_YEARS_MULTIPLIER * (humanYears - 2)
return dogYears

if age >= 65 or >= 13 syntax [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
print("Welcome to the Ontario Science Centre! ")
location = int(input("Would you like to attend the Science Centre (1), IMAX Film (2), or both (3)? "))
age = int(input("What is your age? "))
id = input("Do you have a student ID? ('y' or 'n') ")
if location == 1:
if id == 'y':
if age <= 2:
print("Your cost for entry will be $0.00")
elif age <= 17:
print("Your cost for entry will be $13.00")
else:
print("Your cost for entry will be $16.00")
elif id == 'n':
if age >= 65 or >= 13:
print("Your cost for entry will be $16.00")
elif age >= 18:
print("Your cost for entry will be $22.00")
elif age >= 3:
print("Your cost for entry will be $13.00")
else:
print("Your cost for entry will be $0.00")
if location == 2:
if id == 'y':
if age <= 2:
print("Your cost for entry will be $0.00")
else:
print("Your cost for entry will be $9.00")
if id == 'n':
if age <= 2:
print("Your cost for entry will be $0.00")
else:
print("Your cost for entry will be $9.00")
if location == 3:
if id == 'y':
print("Your cost for entry will be $22.00")
elif id == 'n':
if age >= 65 or >= 13:
print("Your cost for entry will be $22.00")
elif age >= 18:
print("Your cost for entry will be $28.00")
elif age >= 3:
print("Your cost for entry will be $19.00")
else:
print("Your cost for entry will be $0.00")
Keep getting this error:
Traceback (most recent call last):
File "python", line 15
if age >= 65 or >= 13:
^
SyntaxError: invalid syntax
I tried everything but i can not see a error.
I am also new to python so Im sorry if the error is easy to spot.
You've to do it like this:
if age >= 65 or age >= 13:
Look how i had to put in the age variable before both numbers.
You should look at it in this way:
that each >= returns either True or False, so if 13 is less or equal to nothing, python don't understand it, and probably aslo many other coding languages.
while the others have answered regarding the syntax, I'm curious whether you really meant age >= 65 or age >= 13 or perhaps age >= 65 or age <= 13?
If you did mean age >= 65 or age >= 13, I think age >= 13 is enough as higher than 65 is also higher than 13.
It must be age >= 65 or age >= 13

How to end a program using blank line in python?

fee = []
age = int(input("Enter age: "))
while age != '':
age = int(input("Enter age: "))
if age <= 5:
fee.append(0)
elif age >= 6 and age <= 64:
fee.append(50.00)
else:
fee.append(25.00)
total = sum(fee)
print("Total payment: ", total)
I want to make a program that would sum up the given entrance fees. I don't even know if I'm doing it correctly
You can't compare a string to an integer, that's your main problem. If you retrieve it from the user as a string and check it is indeed an integer or not will work. That code should do the trick:
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
fee = []
r='start'
while r != '':
r = input("Enter age: ")
if RepresentsInt(r):
age = int(r)
if age <= 5:
fee.append(0)
elif age >= 6 and age <= 64:
fee.append(50.00)
else:
fee.append(25.00)
total = sum(fee)
print("Total payment: ", total)
fee = 0
age = int(input("Enter age: "))
while age != '':
try:
age = int(input("Enter age: ")) // to avoid exception of string
except:
break
if age <= 5:
fee += 0 // no need to append if outcome is a number
elif age >= 6 and age <= 64:
fee += 50
else:
fee += 25
total = fee
print("Total payment: ", total)

How would I turn these raw_input answers and input them into my functions?

I'm pretty new to coding so bear with me but how do I make this code work? I'm trying to take the information that is entered by the user and input it into my functions so I can print the total.
def hotel_cost(nights):
return nights * 140
def plane_cost(city):
if city == "Atlanta":
return 220
elif city == "Boston":
return 550
elif city == "Chicago":
return 900
def rental_car_cost(days):
if days >= 7:
return days * 100 - 50
elif days >= 1 and days <= 5:
return days * 100 - 20
a = raw_input("Please choose number of nights: ")
b = raw_input("Please choose which city you are flying to (Atlanta, Boston, Chicago) ")
c = raw_input("Please choose days of rental car use: ")
d = raw_input("Please choose how much spending money you plan on spending: ")
a = nights
b = city
c = days
total = a + b + c + d
print "Your total cost of trip is %d" % total
You need to first convert your numeric input values to numbers and then pass your input values to your functions.
Delete the lines
a = nights
b = city
c = days
Calculate your total with
total = hotel_cost(int(a)) + plane_cost(b) + rental_car_cost(int(c)) + float(d)
I assumed that for the number of nights and rental car days only integers make sense.
I am not sure if this applies in Python version 2. However, you could try this:
a = int(raw_input("Please choose number of nights: ") * 140 )
# Multiplies by 140, but this would defeat the purpose of your functions.
And apply the int function to convert all of your inputs into integers.
You can use input() in Python 2 as it evaluates the input to the correct type. For the functions, you just need to pass your values into them, like this:
def hotel_cost(nights):
return nights * 140
def plane_cost(city):
if city == "Atlanta":
return 220
elif city == "Boston":
return 550
elif city == "Chicago":
return 900
def rental_car_cost(days):
if days >= 7:
return days * 100 - 50
elif days >= 1 and days <= 5:
return days * 100 - 20
nights = input("Please choose number of nights: ")
city = raw_input("Please choose which city you are flying to (Atlanta, Boston, Chicago) ")
rental_duration = input("Please choose days of rental car use: ")
spending_money = input("Please choose how much spending money you plan on spending: ")
total = hotel_cost(nights) + plane_cost(city) + rental_car_cost(rental_duration) + spending_money
print "Your total cost of trip is %d" % total

How do i print an output if the value entered is not an integer

I am trying to do two things here.
I want to print "value entered is not a valid age" if the input is not a number in this code:
age = float(input (' enter your age: '))
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
Also, how can I repeat this program once it is done?
You could check whether input is a valid digit with isdigit method of str. For multiple times you could wrap your code to a function and call it as much as you want:
def func():
age = input (' enter your age: ')
if age.isdigit():
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
else:
print "value entered is not a valid age"
func()
For make this code runnig every time you should add a loop , like while loop , and add a break whenever you want end this loop or add a condition for example run 10 times,and if you want check the input is float , you can add a try section:
counter = 0
while counter < 10:
age = raw_input (' enter your age: ')
try :
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
counter -= 1
except ValueError:
print "value entered is not a valid age"
It is also a good idea to arrange your cases in order, to make it easier to see what is happening (and to make sure you didn't leave an unhandled gap):
while True:
age = input("Enter your age (or just hit Enter to quit): ").strip()
if not age:
print("Goodbye!")
break # exit the while loop
try:
# convert to int
age = int(age)
except ValueError:
# not an int!
print("Value entered is not a valid age")
continue # start the while loop again
if age < 0:
print("Sorry, {} is not a valid age.".format(age))
elif age < 16:
print("You are too young to drive!")
elif age < 95:
print("You are good to drive!")
elif age <= 120:
print("Sorry, you can't risk driving!")
else:
print("What are you, a tree?")

Categories

Resources