w3resource

Python Exercise: Calculate a dog's age in dog's years


31. Dog Age in Dog Years

Write a Python program to calculate a dog's age in dog years.
Note: For the first two years, a dog year is equal to 10.5 human years. After that, each dog year equals 4 human years.

Pictorial Presentation:

Python Exercise: Calculate a dog's age in dog's years

Sample Solution:

Python Code:

# Request input from the user to provide a dog's age in human years and convert it to an integer
h_age = int(input("Input a dog's age in human years: "))

# Check if the entered age is less than zero; if true, display an error message and exit the program
if h_age < 0:
    print("Age must be a positive number.")
    exit()
# If the entered age is 2 years or less, calculate the dog's age in dog's years using the formula 10.5 times the human years
elif h_age <= 2:
    d_age = h_age * 10.5
# For ages greater than 2, calculate the dog's age in dog's years using the formula 21 plus 4 times the remaining human years after 2
else:
    d_age = 21 + (h_age - 2) * 4

# Display the calculated dog's age in dog's years
print("The dog's age in dog's years is", d_age) 
  

Sample Output:

Input a dog's age in human years: 12                                                                          
The dog's age in dog's years is 61   

Flowchart :

Flowchart: Calculate a dog's age in dog's years

For more Practice: Solve these Related Problems:

  • Write a Python program to convert a dog's age in human years to dog years using different multipliers for the first two years and subsequent years.
  • Write a Python program to prompt the user for a dog's age and output the equivalent dog years with conditional calculations.
  • Write a Python program to implement the dog age conversion using a function that handles fractional human ages.
  • Write a Python program to calculate dog years by reading input and applying a formula that distinguishes between early and later years.

Go to:


Previous: Write a Python program to print alphabet pattern 'Z'.
Next: Write a Python program to check whether an alphabet is a vowel or consonant.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.