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()
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 10 months ago.
This program calculates depreciation
I want to keep asking user for input until it gives the valid input.
def CalculateDep(amount,nofYears,rate,yearOfPurchase):
for i in range(nofYears):
if (mop.lower() == "n" and i == 0):
percentile = rate * 0.005
elif(mop.lower() == "y" or mop.lower() == "n"):
percentile = rate * 0.01
dep = round((percentile)*amount, 2)
print("") # print blank line for readiblity
print("Dep Charge #" + str(percentile*100) + " % : " + str(dep))
print("On 31-03-" + str(yearOfPurchase+1))
amount = amount - (dep)
yearOfPurchase += 1
print("Value After Depreciation : " + str(round(amount, 2)))
amt = int(input("Enter the Amount : ")) #Initial value of asset
y = int(input("Enter the Number of years : "))
r = float(input("Enter The depreciation Rate : "))
yop = int(input("Enter The Year in Which The Asset is purchased : "))
mop = input("Purchased asset before 1st October ? Answer y or n : ")
CalculateDep(amt, y, r, yop)
Typically this can be accomplished with a while loop
while True:
try:
amt = int(input("Enter the Amount : "))
except ValueError:
print('please enter an int')
else:
break
can someone help me troubleshoot my code the reply from going through the code at the end just loops instead of begining the program again completely would be brilliant is someone could help me thanks and i know its very basic and maybe not the best way to do it but as long as it works its fine.
start = input("Do you want to make an order? ")
while start == "Y" or start == "y" :
title = input("Enter book title: ")
sPrice = float(input("Enter price of book: "))
voucher = input("Do you have a voucher? ")
while sPrice >0 :
amount = float(input("Enter amount of books: "))
while amount >= 1 and amount <= 80 :
if amount >= 5 and amount <= 10 :
disc = 5
elif amount >= 11 and amount <= 50 :
disc = 7.5
elif amount >= 51 and amount <= 80 :
disc = 10
else :
disc = 0
base = sPrice * amount
discVal = (base * disc) / 100
dPrice = base - discVal
if voucher == "Y" or voucher == "y" and dPrice >= 25 :
voucherValue = 25
else :
voucherValue = 0
fPrice = dPrice - voucherValue
print (f"Discount rate: {disc}%")
print (f"Discount value: £{discVal:.2f}")
print (f"Total before discount: £{base:.2f}")
print (f"Total after discount: £{dPrice:.2f}")
if voucher == "Y" or voucher == "y" and dPrice >= 25 :
print (f"Value of voucher: £{voucherValue:.2f}")
print (f"Final cost of order: £{fPrice:.2f}")
else :
print ("ERROR - Invalid amount!")
amount = float(input("Enter amount of books: "))
else :
print ("ERROR - Price too low!")
sPrice = float(input("Enter price of book: "))
else :
start = input("Do you want to make an order? ")
You need to include if at two place just to validate the input value.
Change while sPrice >0 : to if sPrice >0 : and line while amount >= 1 and amount <= 80 : to if amount >= 1 and amount <= 80 :
I am making a number guessing game for a project as a part of my intro to the coding class. I am trying to calculate the total earnings for the user, but I keep getting a type error and I have no idea what I am doing wrong.
print("To begin the game pay two dollars")
print("You can collect your winnings when you stop playing")
import sys
count = 0
Jackpot_wins = 0
Reversed_digits = 0
Digit_WrongPlacement = 0
Digit_RightPlacement = 0
Digit_RightPlacement_two = 0
Digit_WrongPlacement_two = 0
JackpotValue = 100
Reversed_digitsValue = 10
Digit_RightPlacementValue = 10
Digit_WrongPlacementValue = 5
Cost_Per_Play = 2
Game_start = input("Would you like to play? enter 'y' for yes and 'n' for no: ")
if Game_start == "n":
print("Thats ok, maybe next time")
sys.exit()
while Game_start == "y":
count = count + 1
Money_Spent = count * Cost_Per_Play
Player_Number = int(input("Enter a number 0-99: "))
print(Player_Number)
import random
Hidden = random.randint(0,99)
Reversed_digits = (str(Hidden)[::-1])
print(Hidden)
Jackpot = Hidden == Player_Number
PN = int(Player_Number / 10)
RN = int(Hidden / 10)
PN1 = int(Player_Number % 10)
RN1 = int(Hidden % 10)
if Jackpot:
print("Jackpot!!! You win 100 dollars!!!")
Jackpot_wins = int(Jackpot_wins + 1)
elif Player_Number == Reversed_digits:
print("Right digits, wrong order!... You win 10 dollars!")
Reversed_digits = int(Reversed_digits + 1)
elif PN == RN:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement = int(Digit_RightPlacement + 1)
elif RN1 == PN1:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement_two = int(Digit_RightPlacement_two + 1)
elif PN1 == RN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement = int(Digit_WrongPlacement + 1)
elif RN1 == PN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement_two = int(Digit_WrongPlacement_two + 1)
else:
print("Completely wrong")
Game_start = input("To continue type 'y' to end type anything: ")
JP_money = Jackpot_wins * JackpotValue
RD_money = Reversed_digits * Reversed_digitsValue
DRP_money = Digit_RightPlacement * Digit_RightPlacementValue
DRP1_money = Digit_RightPlacement_two * Digit_RightPlacementValue
DWP_money = Digit_WrongPlacement * Digit_WrongPlacementValue
DWP1_money = Digit_WrongPlacement_two * Digit_WrongPlacementValue
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
Total_earnings = Winnings - Money_Spent
if Game_start != "y":
print("See you next time! You played ", count, "rounds.")
print("you spent $ ", Money_Spent)
print("Wow you won the Jackpot", Jackpot_wins, "times!")
print("Your total earnings are", Total_earnings, "Congrats!")
I expected the code to keep tally of the wins and their varying values but I am either getting a type error or a value that is unbelievable like 72727171723
Yes, I tested the code, in your Winning calculation RD_Money is returning string number,
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
For resolving this you can just convert it in the calculation like this
Winnings = JP_money + int(RD_money) + DRP_money + DRP1_money + DWP_money + DWP1_money
or you can do this
RD_money = int(Reversed_digits) * Reversed_digitsValue
This will solve your problem
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