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
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last month.
Here is the code:
print("Welcome to the weight maintenance calculator!")
startWeight = float(input("Input your start weight, in kilograms: "))
height = float(input("Enter your height in centimetres: "))
sex = input("Enter your sex (M/F): ")
age = float(input("Enter your age: "))
dailyActivity = input("Rank your activity level, from 0-5: ")
if ((sex == "M") or (sex == "m")):
startWeightBmr = int((10 * startWeight) + (6.25 * height) - (5 * age) + 5)
if (dailyActivity == 0):
caloriesUsedCurrently = startWeightBmr + 300
print(caloriesUsedCurrently)
if (dailyActivity == 1):
caloriesUsedCurrently = startWeightBmr + 350
print(caloriesUsedCurrently)
if (dailyActivity == 2):
caloriesUsedCurrently = startWeightBmr + 400
print(caloriesUsedCurrently)
Anyway, if you run it, you'll see the issue quite clearly - no matter what number you put in (0, 1 or 2) for the dailyActivity variable, caloriesUsedCurrently is never printed. I'm wondering if there's something wrong with the if blocks, and whether or not they're being executed at all. Could someone please guide me on this one? It will run, so there's no error message, which makes it all the more confusing. Please help!
I tried running this in IDLE to see if it was VSCode that was the issue, but nope, as I suspected it was my code. Running it in IDLE did nothing.
Try:
dailyActivity = int(input("Rank your activity level, from 0-5: "))
Code:
print("Welcome to the weight maintenance calculator!")
startWeight = float(input("Input your start weight, in kilograms: "))
height = float(input("Enter your height in centimetres: "))
sex = input("Enter your sex (M/F): ")
age = float(input("Enter your age: "))
dailyActivity = int(input("Rank your activity level, from 0-5: "))
if ((sex == "M") or (sex == "m")):
startWeightBmr = int((10 * startWeight) + (6.25 * height) - (5 * age) + 5)
if (dailyActivity == 0):
caloriesUsedCurrently = startWeightBmr + 300
print(caloriesUsedCurrently)
if (dailyActivity == 1):
caloriesUsedCurrently = startWeightBmr + 350
print(caloriesUsedCurrently)
if (dailyActivity == 2):
caloriesUsedCurrently = startWeightBmr + 400
print(caloriesUsedCurrently)
Output:-
Welcome to the weight maintenance calculator!
Input your start weight, in kilograms: 60
Enter your height in centimetres: 162
Enter your sex (M/F): m
Enter your age: 19
Rank your activity level, from 0-5: 2
1922
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 is my current code for a tax calculator based on age. I think that it would be easier to update in the future if I used data structures when calculating the brackets. Could someone help me make sense of this?
while True: #Loop the whole program
from datetime import datetime, date #Get the Age of from user input
print("Please enter your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(date_of_birth)
print("You are " ,int(age), " years old.")
#Get the Salary from user input
def get_salary():
while True:
try:
salary = int(input("Please enter your salary: "))
except ValueError:
print("You need to enter a number ")
else:
break
return salary
#Calculate the Amount that needs to be paid, using if,elif,else
def contribution(age):
if age <= 35:
tax = (salary * 0.20)
elif 36 <= age <= 50:
tax = (salary * 0.20)
elif 51 <= age <= 55:
tax = (salary * 0.185)
elif 56 <= age <= 60:
tax = (salary * 0.13)
elif 61 <= age <= 65:
tax = (salary * 0.075)
else:
tax = (salary * 0.05)
return tax
#Print the amount
if __name__ == "__main__": # It's as if the interpreter inserts this at the top of your module when run as the main program.
salary = get_salary() #get salary from get_salary()
tax = contribution(age) #calculate the tax
print("you have to pay", tax, " every month ")
while True:
answer = str(input("Do you need to do another calculation? (y/n): "))
if answer in ("y", "n"):
break
print ("invalid input.")
if answer == "y":
continue
else:
print("Thank you for using this Calculator, Goodbye")
break
So the code that I'm assuming that I need to change is:
#Calculate the Amount that needs to be paid, using if,elif,else
def contribution(age):
if age <= 35:
tax = (salary * 0.20)
elif 36 <= age <= 50:
tax = (salary * 0.20)
elif 51 <= age <= 55:
tax = (salary * 0.185)
elif 56 <= age <= 60:
tax = (salary * 0.13)
elif 61 <= age <= 65:
tax = (salary * 0.075)
else:
tax = (salary * 0.05)
return tax
Also, I'm trying to learn so could you explain by putting #comments into the code :) Thank you!
1. Rewrite the code structure
First of all, I think most programmers do like to put function blocks all together and leave the main logic as clean/short as possible to improve readability. Therefore the 'code structure' like this could be hard to maintain or update in the future.
while True: #Loop the whole program
from datetime import datetime, date #Get the Age of from user input
def calculate_age(born): ...
def get_salary(): ...
def contribution(age): ...
if __name__ == "__main__":
# main logic
...
So this kind of structure is really weird, plus you have lots of variables (date_of_birth, age) declared between functions. Would be hard to do the update/maintenance.
If I were you, I'd firstly revise the code like this way
from datetime import datetime, date #Get the Age of from user input
def calculate_age(born): ...
def get_salary(): ...
def contribution(age): ...
if __name__ == "__main__": # It's as if the interpreter inserts this at the top of your module when run as the main program.
program_continue = 'y'
while program_continue.upper() in ['Y', 'YES']:
print("Please enter your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
age = calculate_age(date_of_birth)
print("You are " ,int(age), " years old.")
salary = get_salary() #get salary from get_salary()
tax = contribution(age) #calculate the tax
print("you have to pay", tax, " every month ")
program_continue = str(input("Do you need to do another calculation? (y/n): "))
print("Thank you for using this Calculator, Goodbye")
2. Introduce data structure? or class?
Honestly I don't quite understand what do you mean by "using data structure", so I guess make a "class" is the one you wish. Then you have to consider some points:
what should be the attributes for this class? dob, salary, anything else?
what will you expand in the future? name? gender? contact_info? handicapped or not?
Whatever, we just create a class with dob and salary for now.
class Person(object):
def __init__(self, dob, salary):
"""
input dob and salary only, age and tax will be calculated then
"""
self.dob = dob
self.salary = salary
self.age = self.calculate_age()
self.tax = self.contribution()
def calculate_age(self):
today = date.today()
return today.year - self.dob.year - ((today.month, today.day) < (self.dob.month, self.dob.day))
def contribution(self):
if self.age <= 35:
tax = (self.salary * 0.20)
elif 36 <= self.age <= 50:
tax = (self.salary * 0.20)
elif 51 <= self.age <= 55:
tax = (self.salary * 0.185)
elif 56 <= self.age <= 60:
tax = (self.salary * 0.13)
elif 61 <= self.age <= 65:
tax = (self.salary * 0.075)
else:
tax = (self.salary * 0.05)
return tax
So once you create a variable in the class Person, you can access the age, salary, tax via .age, .salary, .tax.
Please notice that I did not put the function get_salary() into the class since it's a function for "asking user's salary" and has nothing to do with the attribute.
The main logic can be rewritten to:
if __name__ == "__main__": # It's as if the interpreter inserts this at the top of your module when run as the main program.
program_continue = 'y'
while program_continue.upper() in ['Y', 'YES']:
print("Please enter your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
salary = get_salary() #get salary from get_salary()
##### THESE ARE THE CHANGES START
person_obj = Person(date_of_birth, salary)
print("You are ", int(person_obj.age), " years old.")
print("you have to pay", int(person_obj.tax), " every month ")
##### THESE ARE THE CHANGES END
program_continue = str(input("Do you need to do another calculation? (y/n): "))
print("Thank you for using this Calculator, Goodbye")
3. Future expansion
Let's say if I want to add name as an attribute now. All I have to do is to modify the Person class. Should be easier for you to update in the future.
Your function is fairly easy to maintain, especially if you rewrite it a little simpler:
def contribution(age):
if age <= 35:
rate = 0.20
elif age <= 50:
rate = 0.20
elif age <= 55:
rate = 0.185
elif age <= 60:
rate = 0.13
elif age <= 65:
rate = 0.075
else:
rate = 0.05
return salary * rate
But you are right to be worried about embedding data in your code like this. So you may do better with something like this:
# near top or read from file:
tax_rates = [ # upper age limit for each rate
(35, 0.20),
(50, 0.20),
(55, 0.185),
(60, 0.13),
(65, 0.075),
(1000, 0.05)
]
# then elsewhere in the code:
def contribution(salary, age):
for limit, rate in tax_rates:
if age <= limit:
return salary * rate
else:
# finally a good use for for ... else!
raise ValueError(f"Age {age} is out of range.")
I would also recommend moving your import statements and function definitions above the main loop and passing values into the functions (e.g., salary) rather than using global variables. That will make it easier to see what is going on.
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)
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