Reputation: 11
why doesn't my code read the first input i put
def get_age():
age = int(input())
if age>=18 and age<=75:
return age
else:
raise ValueError ('Invalid Age')
# TODO: Complete fat_burning_heart_rate() function
def fat_burning_heart_rate(age):
heart_rate = (0.7 * (220 - age))
return heart_rate
if __name__ == "__main__":
age = get_age()
heart_rate = fat_burning_heart_rate(age)
try:
age = get_age()
print("Fat burning heart rate for a", age, "year-old:", '\n',
fat_burning_heart_rate(age), "bpm")
except ValueError as ve:
print(ve.ages[0],
"\nCould not calculate heart rate info.")
when i type in the input it doesnt read it for example if i type a number between 18 and 75 it ignores it but when i type a number outside this range it ends execution.
it doesn't read my input for example if i use the number 45 it wont read it i would just ask for another input
Upvotes: 1
Views: 222
Reputation: 48
In the code you are calling the get_age function twice before and inside the try, so just remove the firt call to the function.
def get_age():
age = int(input())
if age>=18 and age<=75:
return age
else:
raise ValueError ('Invalid Age')
def fat_burning_heart_rate(age):
heart_rate = (0.7 * (220 - age))
return heart_rate
if __name__ == "__main__":
age = 0
heart_rate = fat_burning_heart_rate(age)
try:
age = get_age()
print("Fat burning heart rate for a", age, "year-old:", '\n',
fat_burning_heart_rate(age), "bpm")
except ValueError as ve:
print(ve.ages[0],
"\nCould not calculate heart rate info.")
Instead of delete the statement I assigned a value to age because if not you will see an error like: "NameError: name 'age' is not defined". Don't worry about the value that you assign to the age variable, that value will be replaced by the one that is written in the input
Upvotes: 1
Reputation: 5721
def get_age(age):
try:
age = int(age)
except ValueError:
pass
if type(age) is int and age in range(18, 76):
return age
else:
print("Invalid Age. Please try again.\n")
return get_age(input("Enter Age: "))
def fat_burning_heart_rate(age):
heart_rate = (0.7 * (220 - age))
return heart_rate
if __name__ == "__main__":
age = get_age(input("Enter Age: "))
print(f"Fat burning heart rate for a {age} year-old: \n{fat_burning_heart_rate(age)} bpm")
Output:
Enter Age: 45
Fat burning heart rate for a 45 year-old:
122.49999999999999 bpm
Upvotes: -1